Compare commits
120
Commits
d036d756f4
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58d99e52c5 | ||
|
|
f643656eb4 | ||
|
|
c8e0c554b3 | ||
|
|
813bbbf324 | ||
|
|
016f0f8c43 | ||
|
|
e4fe775819 | ||
|
|
a0beee43cb | ||
|
|
b62e7a5766 | ||
|
|
1df745f646 | ||
|
|
cfc47215ae | ||
|
|
3a9dbbb60b | ||
|
|
f8574c387d | ||
|
|
9f4a7d7b2d | ||
|
|
7595df5df9 | ||
|
|
139afad052 | ||
|
|
65fbb77b27 | ||
|
|
b79e5bb0ea | ||
|
|
73b7544572 | ||
|
|
8bf0b7d343 | ||
|
|
23fc2c3577 | ||
|
|
dbf0b2e299 | ||
|
|
72e6cdbeea | ||
|
|
57f7803e9e | ||
|
|
c4322bb7d5 | ||
|
|
0efd724f02 | ||
|
|
18ec0c4dc2 | ||
|
|
8681af531d | ||
|
|
e35a76437b | ||
|
|
5465fb7b27 | ||
|
|
ac4d65808a | ||
|
|
d5495a31d9 | ||
|
|
ef713c692a | ||
|
|
fd4146476b | ||
|
|
c4d71078b3 | ||
|
|
9d5f04bf7c | ||
|
|
997e779af9 | ||
|
|
0f0b3a2821 | ||
|
|
6b63b4372b | ||
|
|
0b77634de1 | ||
|
|
54c86a6f39 | ||
|
|
a2d50a92f2 | ||
|
|
63ec4bb9b5 | ||
|
|
3b596a6355 | ||
|
|
165524c05c | ||
|
|
d57901f9f5 | ||
|
|
932f2429da | ||
|
|
10ef75abe6 | ||
|
|
52a4a2844f | ||
|
|
2fed94a25c | ||
|
|
8dc5ab2b54 | ||
|
|
f0c2f70968 | ||
|
|
4e860800a7 | ||
|
|
2fbd4c9fd0 | ||
|
|
2aa29da3ff | ||
|
|
79d9efad73 | ||
|
|
6c488a4731 | ||
|
|
77642bcd94 | ||
|
|
e998b0c06e | ||
|
|
ef22e2bc6c | ||
|
|
72e12d62bc | ||
|
|
b9dc39bf55 | ||
|
|
7d0bd38de2 | ||
|
|
f2f990bd3b | ||
|
|
46ef87e86e | ||
|
|
57c4275a23 | ||
|
|
c6b398fa98 | ||
|
|
b6676877c3 | ||
|
|
47723c6403 | ||
|
|
3135c41b21 | ||
|
|
1be261f944 | ||
|
|
a0fac39c99 | ||
|
|
91938f2427 | ||
|
|
f8a9c0e649 | ||
|
|
443d0a6190 | ||
|
|
d0969cb322 | ||
|
|
b201f5cd58 | ||
|
|
0d95b4b562 | ||
|
|
5dcf77f79f | ||
|
|
a6f9fabcec | ||
|
|
c29436f845 | ||
|
|
b661101a4a | ||
|
|
151427a675 | ||
|
|
dd30d4cbcc | ||
|
|
b8bb44e62a | ||
|
|
a6577482ac | ||
|
|
8c9842c193 | ||
|
|
3b31976e31 | ||
|
|
5da177dbf8 | ||
|
|
169c36734a | ||
|
|
68c25790fd | ||
|
|
c0894cbab1 | ||
|
|
8a0f5b6775 | ||
|
|
f7d144e440 | ||
|
|
6187f35a62 | ||
|
|
0edb2c5565 | ||
|
|
649144897b | ||
|
|
6674a6690b | ||
|
|
a87609261b | ||
|
|
844879773f | ||
|
|
34fed4702d | ||
|
|
9332f6ddb8 | ||
|
|
b841f202a7 | ||
|
|
822767ac64 | ||
|
|
f320717f84 | ||
|
|
6cce293683 | ||
|
|
8d9d0c4591 | ||
|
|
f191729b58 | ||
|
|
2080a88eb8 | ||
|
|
45818de9f1 | ||
|
|
584fbfadf5 | ||
|
|
194a55a03f | ||
|
|
cb4c19f9e4 | ||
|
|
b3c01545ab | ||
|
|
f5b246a50e | ||
|
|
13a1160ad2 | ||
|
|
10a77a9d1b | ||
|
|
569848b97e | ||
|
|
4c8dadc7bc | ||
|
|
1c2cd2506b | ||
|
|
3d1c030a6f |
@@ -136,3 +136,9 @@ auto-imports.d.ts
|
||||
components.d.ts
|
||||
.eslintrc-auto-import.json
|
||||
|
||||
# ---> WorkBuddy 本地工作目录
|
||||
# 内含 AI 工作记忆与每日日志:写明本机绝对路径与调试上下文,且每次会话都在追加,
|
||||
# 提交只会污染 diff 与 blame,多人还会在同一文件上产生无意义的行级冲突。
|
||||
# 需要团队共享的结论请写入 AGENTS.md 或 .serena/memories/,不要放这里。
|
||||
/.workbuddy/
|
||||
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
"scripts": {
|
||||
"dev": "vite --host",
|
||||
"build": "pnpm run type-check:publish && vite build",
|
||||
"build:zip": "pnpm run build && powershell -NoProfile -Command \"New-Item -ItemType Directory -Force -Path release | Out-Null; Compress-Archive -Path dist\\* -DestinationPath release\\gao-customer-h5.zip -Force\"",
|
||||
"twa:build": "cd twa && pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 build --manifest=./twa-manifest.json",
|
||||
"twa:update": "cd twa && pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 update --skipVersionUpgrade --manifest=./twa-manifest.json",
|
||||
"twa:validate": "pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 validate --url=https://gao.imyeyu.com/",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --ext .ts,.vue",
|
||||
"type-check": "vue-tsc -p tsconfig.app.json --noEmit",
|
||||
@@ -29,6 +33,7 @@
|
||||
"timi-web": "link:E:/WebProject/timi-web",
|
||||
"timi-web-api": "link:E:/WebProject/timi-web-api",
|
||||
"ts-node": "^10.9.2",
|
||||
"vconsole": "^3.15.1",
|
||||
"vue": "^3.5.16",
|
||||
"vue-draggable-next": "^2.3.0",
|
||||
"vue-echarts": "^8.0.1",
|
||||
|
||||
Generated
+31
-7
@@ -4,11 +4,6 @@ settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
patchedDependencies:
|
||||
tdesign-mobile-vue@1.16.0:
|
||||
hash: zwjpdqqohmbknbgri7osfh6nzy
|
||||
path: patches/tdesign-mobile-vue@1.16.0.patch
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
@@ -36,7 +31,7 @@ importers:
|
||||
version: 3.0.4(typescript@5.8.3)(vue@3.5.40(typescript@5.8.3))
|
||||
tdesign-mobile-vue:
|
||||
specifier: ^1.16.0
|
||||
version: 1.16.0(patch_hash=zwjpdqqohmbknbgri7osfh6nzy)(vue@3.5.40(typescript@5.8.3))
|
||||
version: 1.16.0(vue@3.5.40(typescript@5.8.3))
|
||||
timi-tdesign-mobile:
|
||||
specifier: link:E:/WebProject/timi-tdesign-mobile
|
||||
version: link:../timi-tdesign-mobile
|
||||
@@ -49,6 +44,9 @@ importers:
|
||||
ts-node:
|
||||
specifier: ^10.9.2
|
||||
version: 10.9.2(@types/node@24.13.3)(typescript@5.8.3)
|
||||
vconsole:
|
||||
specifier: ^3.15.1
|
||||
version: 3.15.1
|
||||
vue:
|
||||
specifier: ^3.5.16
|
||||
version: 3.5.40(typescript@5.8.3)
|
||||
@@ -909,6 +907,13 @@ packages:
|
||||
resolution: {integrity: sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
copy-text-to-clipboard@3.2.2:
|
||||
resolution: {integrity: sha512-T6SqyLd1iLuqPA90J5N4cTalrtovCySh58iiZDGJ6FGznbclKh4UI+FGacQSgFzwKG77W7XT5gwbVEbd9cIH1A==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
core-js@3.50.0:
|
||||
resolution: {integrity: sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==}
|
||||
|
||||
cors@2.8.6:
|
||||
resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}
|
||||
engines: {node: '>= 0.10'}
|
||||
@@ -1444,6 +1449,9 @@ packages:
|
||||
muggle-string@0.4.1:
|
||||
resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==}
|
||||
|
||||
mutation-observer@1.0.3:
|
||||
resolution: {integrity: sha512-M/O/4rF2h776hV7qGMZUH3utZLO/jK7p8rnNgGkjKUw8zCGjRQPxB8z6+5l8+VjRUQ3dNYu4vjqXYLr+U8ZVNA==}
|
||||
|
||||
nanoid@3.3.16:
|
||||
resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
@@ -1876,6 +1884,9 @@ packages:
|
||||
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
|
||||
engines: {node: '>= 0.8'}
|
||||
|
||||
vconsole@3.15.1:
|
||||
resolution: {integrity: sha512-KH8XLdrq9T5YHJO/ixrjivHfmF2PC2CdVoK6RWZB4yftMykYIaXY1mxZYAic70vADM54kpMQF+dYmvl5NRNy1g==}
|
||||
|
||||
vite@6.4.3:
|
||||
resolution: {integrity: sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==}
|
||||
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
|
||||
@@ -2768,6 +2779,10 @@ snapshots:
|
||||
dependencies:
|
||||
is-what: 5.5.0
|
||||
|
||||
copy-text-to-clipboard@3.2.2: {}
|
||||
|
||||
core-js@3.50.0: {}
|
||||
|
||||
cors@2.8.6:
|
||||
dependencies:
|
||||
object-assign: 4.1.1
|
||||
@@ -3338,6 +3353,8 @@ snapshots:
|
||||
|
||||
muggle-string@0.4.1: {}
|
||||
|
||||
mutation-observer@1.0.3: {}
|
||||
|
||||
nanoid@3.3.16: {}
|
||||
|
||||
natural-compare@1.4.0: {}
|
||||
@@ -3661,7 +3678,7 @@ snapshots:
|
||||
'@babel/runtime': 7.29.7
|
||||
vue: 3.5.40(typescript@5.8.3)
|
||||
|
||||
tdesign-mobile-vue@1.16.0(patch_hash=zwjpdqqohmbknbgri7osfh6nzy)(vue@3.5.40(typescript@5.8.3)):
|
||||
tdesign-mobile-vue@1.16.0(vue@3.5.40(typescript@5.8.3)):
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@use-gesture/vanilla': 10.3.1
|
||||
@@ -3823,6 +3840,13 @@ snapshots:
|
||||
|
||||
vary@1.1.2: {}
|
||||
|
||||
vconsole@3.15.1:
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
copy-text-to-clipboard: 3.2.2
|
||||
core-js: 3.50.0
|
||||
mutation-observer: 1.0.3
|
||||
|
||||
vite@6.4.3(@types/node@24.13.3)(less@4.8.0)(terser@5.49.0):
|
||||
dependencies:
|
||||
esbuild: 0.25.12
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[
|
||||
{
|
||||
"relation": [
|
||||
"delegate_permission/common.handle_all_urls",
|
||||
"delegate_permission/common.use_as_origin"
|
||||
],
|
||||
"target": {
|
||||
"namespace": "android_app",
|
||||
"package_name": "com.imyeyu.gao.customer",
|
||||
"sha256_cert_fingerprints": [
|
||||
"3E:9C:CC:8A:29:71:18:74:BB:56:AA:88:AD:62:E1:F3:AC:F2:70:07:C4:67:D9:32:B8:A2:4B:B7:E7:8E:06:34"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -1,11 +1,13 @@
|
||||
{
|
||||
"name": "Gao Customer H5",
|
||||
"short_name": "Gao H5",
|
||||
"id": "/",
|
||||
"name": "糕店客户管理",
|
||||
"short_name": "糕店管理",
|
||||
"display": "standalone",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#ffffff",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"orientation": "portrait",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icons/icon-192.png",
|
||||
|
||||
@@ -9,6 +9,8 @@ export type CustomerPage = Page<Customer> & {
|
||||
keyword?: string;
|
||||
storeId?: string;
|
||||
tagIdList?: string[];
|
||||
beginCreatedAt?: number;
|
||||
endCreatedAt?: number;
|
||||
};
|
||||
|
||||
async function list(page: CustomerPage): Promise<PageResult<Customer>> {
|
||||
@@ -19,6 +21,8 @@ async function list(page: CustomerPage): Promise<PageResult<Customer>> {
|
||||
keyword: page.keyword || page.likesExample?.code || page.likesExample?.name || page.likesExample?.telephone,
|
||||
storeId: page.storeId || req.equalsExample?.storeId,
|
||||
tagIdList: page.tagIdList || [],
|
||||
beginCreatedAt: page.beginCreatedAt,
|
||||
endCreatedAt: page.endCreatedAt,
|
||||
orderMap: page.orderMap || {}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { axios } from "timi-web-api";
|
||||
import { withCurrentStoreId } from "@/utils/store";
|
||||
import type { CustomerProduct, CustomerProductPage, CustomerProductPageResult } from "@/types/CustomerProduct";
|
||||
|
||||
const URI = "/gao/sales/order/customer-product";
|
||||
|
||||
async function list(page: CustomerProductPage): Promise<CustomerProductPageResult<CustomerProduct>> {
|
||||
return await axios.post(`${URI}/list`, withCurrentStoreId(page));
|
||||
}
|
||||
|
||||
export default { list };
|
||||
@@ -0,0 +1,44 @@
|
||||
import { axios } from "timi-web-api";
|
||||
import type { PageResult } from "timi-web-api";
|
||||
import type {
|
||||
FollowUpReminder,
|
||||
FollowUpReminderPage,
|
||||
FollowUpReminderPayload
|
||||
} from "@/types/FollowUpReminder";
|
||||
|
||||
const BASE_URI = "/gao/customer/follow-up-reminder";
|
||||
|
||||
/** 客户跟进提醒接口。 */
|
||||
const FollowUpReminderAPI = {
|
||||
async list(page: FollowUpReminderPage): Promise<PageResult<FollowUpReminder>> {
|
||||
return await axios.post(`${BASE_URI}/list`, page);
|
||||
},
|
||||
|
||||
async detail(id: string): Promise<FollowUpReminder> {
|
||||
return await axios.post(`${BASE_URI}/detail`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
async create(payload: FollowUpReminderPayload): Promise<string> {
|
||||
return await axios.post(`${BASE_URI}/create`, payload);
|
||||
},
|
||||
|
||||
async update(payload: FollowUpReminderPayload): Promise<void> {
|
||||
return await axios.post(`${BASE_URI}/update`, payload);
|
||||
},
|
||||
|
||||
async complete(id: string): Promise<void> {
|
||||
return await axios.post(`${BASE_URI}/complete`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
},
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
return await axios.post(`${BASE_URI}/delete`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default FollowUpReminderAPI;
|
||||
@@ -12,6 +12,9 @@ async function detail(id: string): Promise<OrderFulfillment> {
|
||||
async function create(request: OrderFulfillmentCreateRequest): Promise<OrderFulfillment> {
|
||||
return await axios.post(`${URI}/create`, request);
|
||||
}
|
||||
async function createAndVerify(request: OrderFulfillmentCreateRequest): Promise<OrderFulfillment> {
|
||||
return await axios.post(`${URI}/create-and-verify`, request);
|
||||
}
|
||||
async function prepareStock(request: FulfillmentPrepareStockRequest): Promise<OrderFulfillment> {
|
||||
return await axios.post(`${URI}/prepare-stock`, request);
|
||||
}
|
||||
@@ -28,4 +31,4 @@ async function revoke(request: FulfillmentRevokeRequest): Promise<OrderFulfillme
|
||||
return await axios.post(`${URI}/revoke`, request);
|
||||
}
|
||||
|
||||
export default { list, detail, create, prepareStock, verify, reject, cancel, revoke };
|
||||
export default { list, detail, create, createAndVerify, prepareStock, verify, reject, cancel, revoke };
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
import { axios } from "timi-web-api";
|
||||
|
||||
/** 门店智能助手聊天请求。 */
|
||||
export interface GaoAiChatRequest {
|
||||
message: string;
|
||||
conversationId?: string;
|
||||
/** GLOBAL_MANAGER 兼任店长时使用当前选中门店。 */
|
||||
storeId?: string;
|
||||
}
|
||||
|
||||
/** 历史会话列表排序方式。 */
|
||||
export type GaoAiConversationSortBy = "created_at" | "-created_at" | "updated_at" | "-updated_at";
|
||||
|
||||
/** 历史会话列表请求。 */
|
||||
export interface GaoAiConversationListRequest {
|
||||
lastId?: string;
|
||||
limit?: number;
|
||||
sortBy?: GaoAiConversationSortBy;
|
||||
}
|
||||
|
||||
/** 历史会话。 */
|
||||
export interface GaoAiConversation {
|
||||
id: string;
|
||||
name?: string;
|
||||
status?: string;
|
||||
introduction?: string;
|
||||
"created_at"?: number | string;
|
||||
"updated_at"?: number | string;
|
||||
}
|
||||
|
||||
/** 历史会话列表响应。 */
|
||||
export interface GaoAiConversationListResponse {
|
||||
"has_more"?: boolean;
|
||||
limit?: number;
|
||||
data?: GaoAiConversation[];
|
||||
}
|
||||
|
||||
/** 历史会话消息读取请求。 */
|
||||
export interface GaoAiConversationReadRequest {
|
||||
conversationId: string;
|
||||
firstId?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/** 历史会话消息。 */
|
||||
export interface GaoAiConversationMessage {
|
||||
id: string;
|
||||
"conversation_id"?: string;
|
||||
query?: string;
|
||||
answer?: string;
|
||||
"created_at"?: number | string;
|
||||
status?: string;
|
||||
feedback?: unknown;
|
||||
}
|
||||
|
||||
/** 历史会话消息列表响应。 */
|
||||
export interface GaoAiConversationReadResponse {
|
||||
"has_more"?: boolean;
|
||||
limit?: number;
|
||||
data?: GaoAiConversationMessage[];
|
||||
}
|
||||
|
||||
/** 智能助手 SSE 事件。 */
|
||||
export interface GaoAiStreamEvent {
|
||||
event: string;
|
||||
data: string;
|
||||
}
|
||||
|
||||
/** 智能助手 HTTP 错误。 */
|
||||
export class GaoAiHttpError extends Error {
|
||||
readonly status: number;
|
||||
readonly code?: string;
|
||||
|
||||
constructor(status: number, message: string, code?: string) {
|
||||
super(message);
|
||||
this.name = "GaoAiHttpError";
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
/** 智能助手流式响应错误。 */
|
||||
export class GaoAiStreamError extends Error {
|
||||
readonly code?: string;
|
||||
|
||||
constructor(message: string, code?: string) {
|
||||
super(message);
|
||||
this.name = "GaoAiStreamError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
const chatPath = "/gao/ai/chat";
|
||||
const conversationBasePath = "/gao/ai/conversation";
|
||||
|
||||
/**
|
||||
* 查询当前登录用户的历史会话。
|
||||
*
|
||||
* @param request 历史会话分页请求
|
||||
*/
|
||||
export async function listConversations(
|
||||
request: GaoAiConversationListRequest = {}
|
||||
): Promise<GaoAiConversationListResponse> {
|
||||
return await axios.post(`${conversationBasePath}/list`, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定历史会话的消息。
|
||||
*
|
||||
* @param request 历史会话读取请求
|
||||
*/
|
||||
export async function readConversation(
|
||||
request: GaoAiConversationReadRequest
|
||||
): Promise<GaoAiConversationReadResponse> {
|
||||
return await axios.post(`${conversationBasePath}/read`, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定历史会话。
|
||||
*
|
||||
* @param conversationId 会话 ID
|
||||
*/
|
||||
export async function deleteConversation(conversationId: string): Promise<void> {
|
||||
await axios.post(`${conversationBasePath}/delete`, undefined, {
|
||||
params: { conversationId }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起门店智能助手聊天请求。
|
||||
*
|
||||
* @param request 聊天请求
|
||||
* @param token 当前登录令牌
|
||||
* @param signal 请求取消信号
|
||||
*/
|
||||
export async function chat(request: GaoAiChatRequest, token: string, signal: AbortSignal): Promise<Response> {
|
||||
const apiBaseURL = import.meta.env.VITE_API_BASE_URL as string | undefined;
|
||||
const url = new URL(chatPath, apiBaseURL || window.location.origin);
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "text/event-stream",
|
||||
"Content-Type": "application/json"
|
||||
};
|
||||
if (token) {
|
||||
// 系统现有接口使用 Token;Authorization 兼容智能助手实施协议。
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
headers.Token = token;
|
||||
}
|
||||
|
||||
return await fetch(url, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(request),
|
||||
credentials: "include",
|
||||
signal
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取并解析 SSE 流。
|
||||
*
|
||||
* @param response 聊天响应
|
||||
* @param onEvent 事件处理函数
|
||||
*/
|
||||
export async function readSseStream(
|
||||
response: Response,
|
||||
onEvent: (event: GaoAiStreamEvent) => Promise<void>
|
||||
): Promise<void> {
|
||||
if (!response.body) {
|
||||
throw new GaoAiStreamError("智能助手没有返回可读取的数据流", "EMPTY_STREAM");
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
buffer = await consumeSseBuffer(buffer, onEvent, false);
|
||||
}
|
||||
|
||||
buffer += decoder.decode();
|
||||
await consumeSseBuffer(buffer, onEvent, true);
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
async function consumeSseBuffer(
|
||||
buffer: string,
|
||||
onEvent: (event: GaoAiStreamEvent) => Promise<void>,
|
||||
isFinal: boolean
|
||||
): Promise<string> {
|
||||
const normalizedBuffer = buffer.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
||||
const blockList = normalizedBuffer.split("\n\n");
|
||||
const remain = isFinal ? "" : blockList.pop() || "";
|
||||
for (const block of blockList) {
|
||||
const event = parseSseBlock(block);
|
||||
if (event) {
|
||||
await onEvent(event);
|
||||
}
|
||||
}
|
||||
if (isFinal && remain.trim()) {
|
||||
const event = parseSseBlock(remain);
|
||||
if (event) {
|
||||
await onEvent(event);
|
||||
}
|
||||
}
|
||||
return remain;
|
||||
}
|
||||
|
||||
function parseSseBlock(block: string): GaoAiStreamEvent | undefined {
|
||||
let event = "message";
|
||||
const dataLineList: string[] = [];
|
||||
for (const line of block.split("\n")) {
|
||||
if (line.startsWith("event:")) {
|
||||
event = line.slice(6).trim() || "message";
|
||||
} else if (line.startsWith("data:")) {
|
||||
const data = line.slice(5);
|
||||
dataLineList.push(data.startsWith(" ") ? data.slice(1) : data);
|
||||
}
|
||||
}
|
||||
if (!dataLineList.length) {
|
||||
return undefined;
|
||||
}
|
||||
return { event, data: dataLineList.join("\n") };
|
||||
}
|
||||
|
||||
/** 将非 2xx 响应转换为不携带原始响应正文的错误。 */
|
||||
export async function ensureChatResponse(response: Response): Promise<void> {
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
let code: string | undefined;
|
||||
let message = "智能助手请求失败,请稍后重试";
|
||||
try {
|
||||
const payload = await response.json() as {
|
||||
code?: unknown;
|
||||
message?: unknown;
|
||||
error?: unknown;
|
||||
};
|
||||
if (typeof payload.code === "string") {
|
||||
code = payload.code;
|
||||
}
|
||||
if (typeof payload.message === "string" && payload.message.trim()) {
|
||||
message = payload.message.trim();
|
||||
} else if (typeof payload.error === "string" && payload.error.trim()) {
|
||||
message = payload.error.trim();
|
||||
}
|
||||
} catch {
|
||||
// 非 JSON 错误响应使用上面的安全默认文案。
|
||||
}
|
||||
throw new GaoAiHttpError(response.status, message, code);
|
||||
}
|
||||
|
||||
/** 解析 SSE 数据,解析失败时返回原始文本。 */
|
||||
export function parseSseData(data: string): unknown {
|
||||
if (data === "[DONE]") {
|
||||
return data;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(data) as unknown;
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { axios } from "timi-web-api";
|
||||
import type { GaoPointChartReq, GaoPointDailyStatView, GaoPointRedemptionProductRankView } from "@/types/GaoChart";
|
||||
import { getStoreChartCache } from "@/utils/storeChartCache";
|
||||
import { withCurrentStoreId } from "@/utils/store";
|
||||
|
||||
const BASE_URI = "/gao/store/chart";
|
||||
|
||||
/** 查询按日汇总的获得积分、消耗积分及两者差值。 */
|
||||
async function dailyTrend(req: GaoPointChartReq): Promise<GaoPointDailyStatView[]> {
|
||||
return await requestList("point-daily-trend", "/point/ledger/daily", req);
|
||||
}
|
||||
|
||||
/** 查询兑换积分最高的前 10 个产品,不扣除退回积分。 */
|
||||
async function redemptionProductRank(req: GaoPointChartReq): Promise<GaoPointRedemptionProductRankView[]> {
|
||||
return await requestList("point-redemption-product-rank", "/point/redemption/product/rank", req);
|
||||
}
|
||||
|
||||
async function requestList<T>(name: string, path: string, req: GaoPointChartReq): Promise<T[]> {
|
||||
const request = withCurrentStoreId(req);
|
||||
return await getStoreChartCache(`gao-point:${name}:${JSON.stringify(request)}`, async () => await axios.post(`${BASE_URI}${path}`, request));
|
||||
}
|
||||
|
||||
export default {
|
||||
dailyTrend,
|
||||
redemptionProductRank
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
import { axios } from "timi-web-api";
|
||||
import type { Role } from "timi-web-api";
|
||||
|
||||
const BASE_URI = "/gao/role";
|
||||
|
||||
export const GaoRoleAPI = {
|
||||
/** 查询登录用户所属门店内可管理的角色。 */
|
||||
async managementList(): Promise<Role[]> {
|
||||
return await axios.post(`${BASE_URI}/management/list`);
|
||||
}
|
||||
};
|
||||
+66
-2
@@ -7,11 +7,20 @@ import type {
|
||||
PointLedger,
|
||||
PointLedgerPage,
|
||||
PointRule,
|
||||
GroovyScript
|
||||
GroovyScript,
|
||||
PointRedeemSku,
|
||||
PointRedeemSkuPage,
|
||||
PointRedemption,
|
||||
PointRedemptionCreateRequest,
|
||||
PointRedemptionPage,
|
||||
PointRedemptionReturn,
|
||||
PointRedemptionReturnRequest
|
||||
} from "@/types/Point";
|
||||
import { getCurrentStoreId, withCurrentStoreId, withCurrentStorePage } from "@/utils/store";
|
||||
|
||||
const BASE_URI = "/gao/customer/point";
|
||||
const REDEEM_SKU_URI = "/gao/point/redeem-sku";
|
||||
const REDEMPTION_URI = "/gao/point/redemption";
|
||||
|
||||
type ListOptions = {
|
||||
allStores?: boolean;
|
||||
@@ -118,6 +127,50 @@ async function ruleRemove(id: string): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
async function redeemSkuList(page: PointRedeemSkuPage): Promise<PageResult<PointRedeemSku>> {
|
||||
return await axios.post(`${REDEEM_SKU_URI}/list`, { ...page, storeId: page.storeId || getCurrentStoreId() });
|
||||
}
|
||||
|
||||
async function redeemSkuDetail(id: string, storeId?: string): Promise<PointRedeemSku> {
|
||||
return await axios.post(`${REDEEM_SKU_URI}/detail`, undefined, { params: { id, storeId: storeId || getCurrentStoreId() || undefined } });
|
||||
}
|
||||
|
||||
async function redeemSkuCreate(item: PointRedeemSku): Promise<PointRedeemSku> {
|
||||
return await axios.post(`${REDEEM_SKU_URI}/create`, withCurrentStoreId(item));
|
||||
}
|
||||
|
||||
async function redeemSkuUpdate(item: PointRedeemSku): Promise<PointRedeemSku> {
|
||||
return await axios.post(`${REDEEM_SKU_URI}/update`, item);
|
||||
}
|
||||
|
||||
async function redeemSkuDisable(id: string): Promise<void> {
|
||||
await axios.post(`${REDEEM_SKU_URI}/disable`, undefined, { params: { id, storeId: getCurrentStoreId() || undefined } });
|
||||
}
|
||||
|
||||
async function redeemSkuRemove(id: string): Promise<void> {
|
||||
await axios.post(`${REDEEM_SKU_URI}/delete`, undefined, { params: { id, storeId: getCurrentStoreId() || undefined } });
|
||||
}
|
||||
|
||||
async function redemptionList(page: PointRedemptionPage): Promise<PageResult<PointRedemption>> {
|
||||
return await axios.post(`${REDEMPTION_URI}/list`, { ...page, storeId: page.storeId || getCurrentStoreId() });
|
||||
}
|
||||
|
||||
async function redemptionDetail(id: string, storeId?: string): Promise<PointRedemption> {
|
||||
return await axios.post(`${REDEMPTION_URI}/detail`, undefined, { params: { id, storeId: storeId || getCurrentStoreId() || undefined } });
|
||||
}
|
||||
|
||||
async function redemptionCreate(request: PointRedemptionCreateRequest): Promise<PointRedemption> {
|
||||
return await axios.post(`${REDEMPTION_URI}/create`, withCurrentStoreId(request));
|
||||
}
|
||||
|
||||
async function redemptionReturn(request: PointRedemptionReturnRequest): Promise<PointRedemption> {
|
||||
return await axios.post(`${REDEMPTION_URI}/return`, request);
|
||||
}
|
||||
|
||||
async function redemptionReturnList(redemptionId: string): Promise<PointRedemptionReturn[]> {
|
||||
return await axios.post(`${REDEMPTION_URI}/return/list`, undefined, { params: { redemptionId, storeId: getCurrentStoreId() || undefined } });
|
||||
}
|
||||
|
||||
export default {
|
||||
list,
|
||||
detailByCustomerId,
|
||||
@@ -130,5 +183,16 @@ export default {
|
||||
ruleCreate,
|
||||
ruleUpdate,
|
||||
ruleSort,
|
||||
ruleRemove
|
||||
ruleRemove,
|
||||
redeemSkuList,
|
||||
redeemSkuDetail,
|
||||
redeemSkuCreate,
|
||||
redeemSkuUpdate,
|
||||
redeemSkuDisable,
|
||||
redeemSkuRemove,
|
||||
redemptionList,
|
||||
redemptionDetail,
|
||||
redemptionCreate,
|
||||
redemptionReturn,
|
||||
redemptionReturnList
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
ProductSpec,
|
||||
ProductSpecValue,
|
||||
ProductStock,
|
||||
ProductStockBatchRequest,
|
||||
ProductStockProduct,
|
||||
ProductStockChangeRequest,
|
||||
ProductStockManualRevokeRequest,
|
||||
@@ -61,6 +62,10 @@ async function disable(id: string): Promise<void> {
|
||||
await axios.post(`${PRODUCT_URI}/disable`, undefined, { params: { id } });
|
||||
}
|
||||
|
||||
async function remove(id: string): Promise<void> {
|
||||
await axios.post(`${PRODUCT_URI}/delete`, undefined, { params: { id } });
|
||||
}
|
||||
|
||||
async function skuDetail(id: string): Promise<ProductSku> {
|
||||
return await axios.post(`${PRODUCT_URI}/sku/detail`, undefined, { params: { id } });
|
||||
}
|
||||
@@ -85,10 +90,18 @@ async function specCreate(spec: ProductSpec): Promise<string> {
|
||||
return await axios.post(`${PRODUCT_URI}/spec/create`, spec);
|
||||
}
|
||||
|
||||
async function specUpdate(spec: ProductSpec): Promise<void> {
|
||||
await axios.post(`${PRODUCT_URI}/spec/update`, spec);
|
||||
}
|
||||
|
||||
async function specValueCreate(value: ProductSpecValue): Promise<string> {
|
||||
return await axios.post(`${PRODUCT_URI}/spec/value/create`, value);
|
||||
}
|
||||
|
||||
async function specValueUpdate(value: ProductSpecValue): Promise<void> {
|
||||
await axios.post(`${PRODUCT_URI}/spec/value/update`, value);
|
||||
}
|
||||
|
||||
async function sellableList(page: ProductPage): Promise<Product[]> {
|
||||
return await axios.post(`${PRODUCT_URI}/sellable/list`, withCurrentStoreId(page));
|
||||
}
|
||||
@@ -107,6 +120,10 @@ async function stockDetail(skuId: string, storeId?: string): Promise<ProductStoc
|
||||
});
|
||||
}
|
||||
|
||||
async function stockBatchDetail(request: ProductStockBatchRequest): Promise<ProductStock[]> {
|
||||
return await axios.post(`${STOCK_URI}/batch-detail`, withCurrentStoreId(request));
|
||||
}
|
||||
|
||||
async function initialIn(request: ProductStockChangeRequest): Promise<ProductStock> {
|
||||
return await axios.post(`${STOCK_URI}/initial-in`, withCurrentStoreId(request));
|
||||
}
|
||||
@@ -150,17 +167,21 @@ export default {
|
||||
create,
|
||||
update,
|
||||
disable,
|
||||
remove,
|
||||
skuDetail,
|
||||
skuCreate,
|
||||
skuUpdate,
|
||||
skuDisable,
|
||||
specList,
|
||||
specCreate,
|
||||
specUpdate,
|
||||
specValueCreate,
|
||||
specValueUpdate,
|
||||
sellableList,
|
||||
stockList,
|
||||
stockProductList,
|
||||
stockDetail,
|
||||
stockBatchDetail,
|
||||
initialIn,
|
||||
manualIn,
|
||||
manualOut,
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
SalesOrderCancelRequest,
|
||||
SalesOrderPage,
|
||||
SalesOrderPageResult,
|
||||
SalesOrderSummary,
|
||||
SalesOrderUpdateRequest
|
||||
} from "@/types/SalesOrder";
|
||||
|
||||
@@ -22,6 +23,9 @@ const FUND_URI = "/gao/fund/record";
|
||||
async function list(page: SalesOrderPage): Promise<SalesOrderPageResult<SalesOrder>> {
|
||||
return await axios.post(`${ORDER_URI}/list`, withCurrentStoreId(page));
|
||||
}
|
||||
async function summary(page: SalesOrderPage): Promise<SalesOrderSummary> {
|
||||
return await axios.post(`${ORDER_URI}/summary`, withCurrentStoreId(page));
|
||||
}
|
||||
async function detail(id: string): Promise<SalesOrder> {
|
||||
return await axios.post(`${ORDER_URI}/detail`, undefined, { params: { id } });
|
||||
}
|
||||
@@ -37,6 +41,9 @@ async function cancel(request: SalesOrderCancelRequest): Promise<SalesOrder> {
|
||||
async function receivePayment(request: OrderPaymentReceiveRequest): Promise<FundRecord> {
|
||||
return await axios.post(`${ORDER_URI}/payment/receive`, request);
|
||||
}
|
||||
async function receivePaymentAndVerify(request: OrderPaymentReceiveRequest): Promise<FundRecord> {
|
||||
return await axios.post(`${ORDER_URI}/payment/receive-and-verify`, request);
|
||||
}
|
||||
async function verifyPayment(id: string): Promise<FundRecord> {
|
||||
return await axios.post(`${ORDER_URI}/payment/verify`, undefined, { params: { id } });
|
||||
}
|
||||
@@ -72,11 +79,13 @@ async function myReceiveRecordDetail(id: string): Promise<FundRecord> {
|
||||
|
||||
export default {
|
||||
list,
|
||||
summary,
|
||||
detail,
|
||||
createDirectProduct,
|
||||
update,
|
||||
cancel,
|
||||
receivePayment,
|
||||
receivePaymentAndVerify,
|
||||
verifyPayment,
|
||||
rejectPayment,
|
||||
cancelPayment,
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { axios } from "timi-web-api";
|
||||
import { axios } from "timi-web-api/api/BaseAPI";
|
||||
import type { Page, PageResult } from "timi-web-api";
|
||||
import type { Store, StoreBusinessDay } from "@/types/Store";
|
||||
|
||||
|
||||
+11
-1
@@ -1,6 +1,7 @@
|
||||
import { axios } from "timi-web-api";
|
||||
import type { Page, PageResult } from "timi-web-api";
|
||||
import type { Tag, TagApply, TagBizType } from "@/types/Tag";
|
||||
import { getCurrentStoreId } from "@/utils/store";
|
||||
|
||||
const BASE_URI = "/gao/tag";
|
||||
|
||||
@@ -15,7 +16,16 @@ async function detail(id: string): Promise<Tag> {
|
||||
}
|
||||
|
||||
async function create(tag: Tag): Promise<Tag> {
|
||||
return await axios.post(`${BASE_URI}/create`, tag);
|
||||
const ownerId = tag.ownerId || getCurrentStoreId();
|
||||
if (!ownerId) {
|
||||
throw new Error("无法确定标签所属门店");
|
||||
}
|
||||
|
||||
return await axios.post(`${BASE_URI}/create`, {
|
||||
...tag,
|
||||
ownerType: tag.ownerType || "GAO_STORE",
|
||||
ownerId
|
||||
});
|
||||
}
|
||||
|
||||
async function update(tag: Tag): Promise<void> {
|
||||
|
||||
@@ -79,23 +79,31 @@ html.theme-dark body {
|
||||
text-overflow: unset;
|
||||
}
|
||||
|
||||
.t-cell__title {
|
||||
.t-cell {
|
||||
|
||||
.t-cell__title {
|
||||
|
||||
.t-cell__title-text {
|
||||
min-width: unset;
|
||||
white-space: nowrap;
|
||||
text-overflow: unset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.t-dialog__footer {
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.t-pull-down-refresh {
|
||||
height: auto;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.t-dropdown-menu {
|
||||
|
||||
&:after {
|
||||
display: none;
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:deep(.t-dropdown-menu__item) {
|
||||
@@ -111,21 +119,22 @@ html.theme-dark body {
|
||||
|
||||
.center-tips {
|
||||
color: var(--tui-gray);
|
||||
margin: 0 auto;
|
||||
padding: .75rem;
|
||||
text-align: center;
|
||||
font-size: .875rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
flex: none;
|
||||
display: block;
|
||||
border-radius: .875rem;
|
||||
border-radius: .875rem !important;
|
||||
|
||||
&.fallback {
|
||||
color: #2563EB;
|
||||
color: #FFF;
|
||||
display: flex;
|
||||
font-size: 1.25rem;
|
||||
background: #DBEAFE;
|
||||
background: var(--td-brand-color);
|
||||
align-items: center;
|
||||
font-weight: 600;
|
||||
justify-content: center;
|
||||
@@ -143,6 +152,52 @@ html.theme-dark body {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.fix-cell-title-clip {
|
||||
|
||||
.t-cell__title {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.glass-header,
|
||||
.filters.glass {
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: -1;
|
||||
position: absolute;
|
||||
|
||||
mask: linear-gradient(to top, transparent 0%, #000 60%);
|
||||
-webkit-mask: linear-gradient(to top, transparent 0%, #000 60%);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
}
|
||||
}
|
||||
|
||||
.glass-bottom {
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: -1;
|
||||
position: absolute;
|
||||
|
||||
mask: linear-gradient(to bottom, transparent 0%, #000 60%);
|
||||
-webkit-mask: linear-gradient(to bottom, transparent 0%, #000 60%);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
}
|
||||
}
|
||||
|
||||
.entrance-fade-up-enter-active {
|
||||
transition: opacity .4s ease, transform .4s ease;
|
||||
transition-delay: var(--entrance-delay, 0ms);
|
||||
|
||||
@@ -93,13 +93,6 @@ const photoURL = computed(() => customer.value ? getCustomerPhotoURL(customer.va
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.avatar .t-image__img) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.customer-cell {
|
||||
.code {
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<div v-else class="empty-block" v-text="emptyText" />
|
||||
<div v-else class="center-tips" v-text="emptyText" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -115,22 +115,6 @@ function handleRemove(customer: Customer): void {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
}
|
||||
|
||||
.empty-block {
|
||||
color: #52607a;
|
||||
margin: 1rem;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
background: #f8fbff;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.avatar .t-image__img) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
<div v-if="customer" class="customer-profile-card">
|
||||
<div v-if="photoURL" class="avatar-trigger" @click="handlePhotoClick">
|
||||
<t-image :src="photoURL" :alt="customerName" fit="cover" class="avatar" />
|
||||
<div @click.stop>
|
||||
<teleport to="body">
|
||||
<t-image-viewer
|
||||
v-model:visible="photoViewerVisible"
|
||||
:images="photoViewerImages"
|
||||
show-index
|
||||
/>
|
||||
</div>
|
||||
</teleport>
|
||||
</div>
|
||||
<div v-else class="avatar fallback" v-text="avatarText" />
|
||||
<div class="content">
|
||||
|
||||
@@ -70,6 +70,7 @@ type SelectionMode = "single" | "multiple";
|
||||
|
||||
interface Props {
|
||||
enableScan?: boolean;
|
||||
initialKeyword?: string;
|
||||
modelValue: string | string[];
|
||||
visible: boolean;
|
||||
selectionMode?: SelectionMode;
|
||||
@@ -78,6 +79,7 @@ interface Props {
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
enableScan: true,
|
||||
initialKeyword: "",
|
||||
selectionMode: "single",
|
||||
storeId: ""
|
||||
});
|
||||
@@ -289,6 +291,7 @@ watch(() => props.visible, async (value) => {
|
||||
return;
|
||||
}
|
||||
syncDraftSelection();
|
||||
keyword.value = props.initialKeyword;
|
||||
await reloadCustomers();
|
||||
});
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import type { EChartsOption } from "echarts";
|
||||
import ChartRangeSlider from "@/components/ChartRangeSlider.vue";
|
||||
import { useStoreChart, useStoreChartWindow } from "@/pages/store/component/useStoreChart";
|
||||
|
||||
type ChartOptionBuilder = (visibleDateTextList: string[]) => EChartsOption;
|
||||
type ChartOptionBuilder = (visibleDateTextList: string[], chartWidth: number) => EChartsOption;
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
caption?: string;
|
||||
@@ -42,6 +42,7 @@ const props = withDefaults(defineProps<{
|
||||
});
|
||||
|
||||
const dateTextList = computed(() => props.dateTextList);
|
||||
const chartWidth = ref(window.innerWidth);
|
||||
const {
|
||||
rangeText,
|
||||
showSlider: chartShowSlider,
|
||||
@@ -51,9 +52,27 @@ const {
|
||||
handleSliderChange
|
||||
} = useStoreChartWindow(dateTextList);
|
||||
const option = computed<EChartsOption>(() => typeof props.option === "function"
|
||||
? props.option(visibleDateTextList.value)
|
||||
? props.option(visibleDateTextList.value, chartWidth.value)
|
||||
: props.option);
|
||||
const { chartElement } = useStoreChart(option);
|
||||
let resizeObserver: ResizeObserver | undefined;
|
||||
|
||||
onMounted(() => {
|
||||
resizeObserver = new window.ResizeObserver(updateChartWidth);
|
||||
if (chartElement.value) {
|
||||
resizeObserver.observe(chartElement.value);
|
||||
updateChartWidth();
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
resizeObserver?.disconnect();
|
||||
resizeObserver = undefined;
|
||||
});
|
||||
|
||||
function updateChartWidth(): void {
|
||||
chartWidth.value = chartElement.value?.clientWidth || window.innerWidth;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<div class="content">
|
||||
<div v-text="confirmText" />
|
||||
<div v-if="canUpdate" class="photo-part">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
title="核销照片(可选)"
|
||||
:model-value="photoList"
|
||||
v-model:photo-items="photoItemList"
|
||||
@@ -18,7 +18,9 @@
|
||||
:loading="isPhotoUploading"
|
||||
:show-remove="false"
|
||||
:show-viewer-actions="false"
|
||||
@add="capturePhoto"
|
||||
@add="selectPhotoFile"
|
||||
@capture-photo="capturePhoto"
|
||||
@capture-video="captureVideo"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -27,21 +29,38 @@
|
||||
ref="photoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept="*/*"
|
||||
multiple
|
||||
@change="handlePhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="photoCameraInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
@change="handlePhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="videoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="video/*"
|
||||
capture="environment"
|
||||
@change="handlePhotoSelected"
|
||||
>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { AttachmentAPI, type Attachment } from "timi-web-api";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import type { EventRecord } from "@/types/EventRecord";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { compressUploadImageList } from "@/utils/imageCompression";
|
||||
import { Message } from "@/utils/message";
|
||||
import { saveCapturedFilesFromInput } from "@/utils/twaBridge";
|
||||
|
||||
defineOptions({
|
||||
name: "EventRecordVerifyDialog"
|
||||
@@ -65,6 +84,8 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const photoInputRef = ref<HTMLInputElement>();
|
||||
const photoCameraInputRef = ref<HTMLInputElement>();
|
||||
const videoInputRef = ref<HTMLInputElement>();
|
||||
const photoItemList = ref<PhotoItem[]>([]);
|
||||
const isPhotoUploading = ref(false);
|
||||
const isSubmitting = ref(false);
|
||||
@@ -87,32 +108,43 @@ function buildPhotoItemList(attachmentList?: Attachment[]): PhotoItem[] {
|
||||
.map(item => ({
|
||||
attachment: item,
|
||||
attachType: item.attachType || "PHOTO",
|
||||
mimeType: item.mimeType,
|
||||
previewUrl: getAttachmentReadURL(item.id || ""),
|
||||
url: getAttachmentReadURL(item.id || "", 90)
|
||||
}));
|
||||
}
|
||||
|
||||
function capturePhoto(): void {
|
||||
photoCameraInputRef.value?.click();
|
||||
}
|
||||
|
||||
function selectPhotoFile(): void {
|
||||
photoInputRef.value?.click();
|
||||
}
|
||||
|
||||
function captureVideo(): void {
|
||||
videoInputRef.value?.click();
|
||||
}
|
||||
|
||||
async function handlePhotoSelected(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const fileList = Array.from(input.files || []);
|
||||
if (!fileList.length) {
|
||||
return;
|
||||
}
|
||||
saveCapturedFilesFromInput(input, fileList);
|
||||
|
||||
isPhotoUploading.value = true;
|
||||
try {
|
||||
const compressedFileList = await compressUploadImageList(fileList);
|
||||
const tempFileList = await AttachmentAPI.upload(compressedFileList);
|
||||
for (const item of tempFileList) {
|
||||
for (const [index, item] of tempFileList.entries()) {
|
||||
if (!item.id) {
|
||||
continue;
|
||||
}
|
||||
photoItemList.value.push({
|
||||
attachType: "PHOTO",
|
||||
mimeType: fileList[index]?.type,
|
||||
tempFileId: item.id,
|
||||
url: AttachmentAPI.getTempReadURL(item.id)
|
||||
});
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
<template>
|
||||
<div class="page-transition">
|
||||
<router-view v-slot="{ Component }">
|
||||
<transition :name="transitionName">
|
||||
<div :key="route.path" class="pages">
|
||||
<component :is="Component" />
|
||||
</div>
|
||||
</transition>
|
||||
</router-view>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { RouteLocationNormalized } from "vue-router";
|
||||
import { useGlobalUIStore } from "@/store/globalUI";
|
||||
|
||||
defineOptions({
|
||||
name: "PageTransition"
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const globalUIStore = useGlobalUIStore();
|
||||
|
||||
const transitionName = ref("push-left");
|
||||
const pageBackground = computed(() => globalUIStore.bodyBackground);
|
||||
|
||||
// ---------- 路由深度计算 ----------
|
||||
|
||||
const pathCache = new Map<string, number>();
|
||||
|
||||
function calcDepth(sourceRoute: RouteLocationNormalized): number {
|
||||
const queryDepth = parseTransitionDepth(sourceRoute.query.transitionDepth);
|
||||
if (queryDepth !== undefined) {
|
||||
return queryDepth;
|
||||
}
|
||||
|
||||
if (!sourceRoute.meta.dynamicDepth) {
|
||||
return Number(sourceRoute.meta.depth ?? 0);
|
||||
}
|
||||
|
||||
const fullPath = sourceRoute.fullPath;
|
||||
const cachedDepth = pathCache.get(fullPath);
|
||||
if (cachedDepth !== undefined) {
|
||||
return cachedDepth;
|
||||
}
|
||||
|
||||
const baseDepth = Number(sourceRoute.meta.baseDepth ?? 0);
|
||||
const pathSegments = fullPath.split("?")[0].split("/").filter((pathSegment) => pathSegment !== "");
|
||||
const depth = baseDepth + (pathSegments.length - 1);
|
||||
pathCache.set(fullPath, depth);
|
||||
return depth;
|
||||
}
|
||||
|
||||
function parseTransitionDepth(value: unknown): number | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
return parseTransitionDepth(value[0]);
|
||||
}
|
||||
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const text = value.trim();
|
||||
if (!text) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const depth = Number(text);
|
||||
if (!Number.isInteger(depth) || depth < 0 || 20 < depth) {
|
||||
return undefined;
|
||||
}
|
||||
return depth;
|
||||
}
|
||||
|
||||
const unregisterGuard = router.beforeEach((to, from) => {
|
||||
const toDepth = calcDepth(to);
|
||||
const fromDepth = calcDepth(from);
|
||||
|
||||
if (fromDepth < toDepth) {
|
||||
transitionName.value = "push-left";
|
||||
} else if (toDepth < fromDepth) {
|
||||
transitionName.value = "push-right";
|
||||
} else {
|
||||
transitionName.value = "";
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
unregisterGuard();
|
||||
pathCache.clear();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
@easing: cubic-bezier(.19, 1, .22, 1);
|
||||
@duration: 520ms;
|
||||
@brightness: .98;
|
||||
@shadow-intensity: .15;
|
||||
@page-offset: 25%;
|
||||
|
||||
.page-transition {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
overflow-x: hidden;
|
||||
|
||||
// 此 wrapper 必须独立,不可将 class=pages 直接加在 <component> 上:
|
||||
// 否则页面 root element 与动画容器同为一个 DOM 节点,
|
||||
// 页面自身的 padding 会使 position:fixed; width:100% 的盒子溢出视口。
|
||||
.pages {
|
||||
height: 100%;
|
||||
background: v-bind(pageBackground);
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
// ---------- push-left / push-right 公共激活状态 ----------
|
||||
|
||||
.push-left-enter-active,
|
||||
.push-left-leave-active,
|
||||
.push-right-enter-active,
|
||||
.push-right-leave-active {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: fixed;
|
||||
transition: transform @duration @easing, opacity .2s linear;
|
||||
backface-visibility: hidden;
|
||||
}
|
||||
|
||||
// ---------- 前进:下一页从右滑入,当前页缩退到左侧 ----------
|
||||
|
||||
.push-left-enter-from {
|
||||
transform: translate3d(100%, 0, 0);
|
||||
box-shadow: -4px 0 16px rgba(0, 0, 0, @shadow-intensity);
|
||||
}
|
||||
|
||||
.push-left-enter-to {
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
|
||||
.push-left-leave-active {
|
||||
transition: all @duration @easing, filter .3s;
|
||||
}
|
||||
|
||||
.push-left-leave-to {
|
||||
filter: brightness(@brightness);
|
||||
transform: translate3d(-@page-offset, 0, 0);
|
||||
}
|
||||
|
||||
// ---------- 返回:当前页从右滑出,上一页从左侧复位 ----------
|
||||
|
||||
.push-right-enter-active {
|
||||
z-index: 0;
|
||||
transition: transform @duration @easing, opacity .3s;
|
||||
}
|
||||
|
||||
.push-right-enter-from {
|
||||
transform: translate3d(-@page-offset, 0, 0);
|
||||
}
|
||||
|
||||
.push-right-enter-to {
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
|
||||
.push-right-leave-active {
|
||||
z-index: 1;
|
||||
transition: transform @duration @easing, box-shadow .3s;
|
||||
}
|
||||
|
||||
.push-right-leave-from {
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
|
||||
.push-right-leave-to {
|
||||
transform: translate3d(105%, 0, 0);
|
||||
box-shadow: 4px 0 16px rgba(0, 0, 0, @shadow-intensity);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -34,11 +34,13 @@
|
||||
<t-icon name="close" size="1rem" />
|
||||
</t-button>
|
||||
</div>
|
||||
<teleport to="body">
|
||||
<t-image-viewer
|
||||
v-model:visible="photoViewerVisible"
|
||||
:images="photoViewerImages"
|
||||
show-index
|
||||
/>
|
||||
</teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,569 +0,0 @@
|
||||
<template>
|
||||
<div v-bind="$attrs" class="photo-scroller">
|
||||
<div class="t-form__label" :class="{ required }">
|
||||
<slot name="title">
|
||||
<span v-text="title" />
|
||||
</slot>
|
||||
</div>
|
||||
<div class="photo-shell" :class="{ 'without-add': !showAdd }">
|
||||
<div class="items">
|
||||
<div v-if="!displayPhotoList.length" class="empty" v-text="emptyText" />
|
||||
<div
|
||||
v-for="(item, index) in displayPhotoList"
|
||||
:key="`${item.url}-${item.attachType}-${index}`"
|
||||
class="item"
|
||||
>
|
||||
<t-button variant="text" class="preview-trigger" @click="openPhotoViewer(index)">
|
||||
<t-image
|
||||
class="image"
|
||||
:src="item.url"
|
||||
:alt="getAttachTypeText(item.attachType)"
|
||||
fit="cover"
|
||||
/>
|
||||
</t-button>
|
||||
<div
|
||||
v-if="showTypeLabel"
|
||||
class="type-label white glass-black clip-text"
|
||||
v-text="getAttachTypeText(item.attachType)"
|
||||
/>
|
||||
<t-button
|
||||
v-if="showRemove && hasRemovablePhotos"
|
||||
theme="danger"
|
||||
class="remove"
|
||||
shape="circle"
|
||||
size="extra-small"
|
||||
@click="removePhoto(index)"
|
||||
>
|
||||
<t-icon name="close" size="1rem" />
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="showAdd" class="add-trigger">
|
||||
<t-button
|
||||
v-if="addActionList.length === 1"
|
||||
theme="primary"
|
||||
variant="dashed"
|
||||
class="add"
|
||||
:loading="isBusy"
|
||||
:disabled="isBusy"
|
||||
@click="handleAddAction(addActionList[0])"
|
||||
>
|
||||
<span v-text="addActionList[0].text" />
|
||||
</t-button>
|
||||
<t-popover
|
||||
v-else
|
||||
v-model:visible="addPopoverVisible"
|
||||
placement="left"
|
||||
theme="light"
|
||||
>
|
||||
<t-button
|
||||
class="add"
|
||||
theme="primary"
|
||||
variant="dashed"
|
||||
:loading="isBusy"
|
||||
:disabled="isBusy"
|
||||
>
|
||||
<span v-text="addText" />
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="add-actions">
|
||||
<t-button
|
||||
v-for="(action, index) in addActionList"
|
||||
:key="`${action.emit}-${index}`"
|
||||
variant="text"
|
||||
:theme="action.theme"
|
||||
class="add-action"
|
||||
:disabled="isBusy"
|
||||
@click="handleAddAction(action)"
|
||||
>
|
||||
<template #icon v-if="action.icon">
|
||||
<t-icon :name="action.icon" />
|
||||
</template>
|
||||
<span v-text="action.text" />
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-popover>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
v-if="props.upload"
|
||||
ref="fileInput"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
@change="handleFileChange"
|
||||
/>
|
||||
</div>
|
||||
<t-image-viewer
|
||||
v-model:visible="photoViewerVisible"
|
||||
:images="photoViewerImages"
|
||||
show-index
|
||||
@close="photoActionVisible = false"
|
||||
@index-change="handlePhotoViewerIndexChange"
|
||||
>
|
||||
<template #delete-btn>
|
||||
<div v-if="showViewerActions" class="viewer-action" @click.stop>
|
||||
<t-popover
|
||||
v-model:visible="photoActionVisible"
|
||||
placement="bottom"
|
||||
theme="light"
|
||||
:show-arrow="false"
|
||||
>
|
||||
<t-button class="white" variant="text">
|
||||
<t-icon name="ellipsis" />
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="actions" @click.stop>
|
||||
<div class="title">修改类型</div>
|
||||
<div class="type">
|
||||
<t-button
|
||||
class="button"
|
||||
v-for="item in attachTypeOptions"
|
||||
:key="item.value"
|
||||
:theme="item.value === currentPhotoItem?.attachType ? 'primary' : 'default'"
|
||||
variant="text"
|
||||
size="extra-small"
|
||||
:disabled="isSubmitting"
|
||||
@click="changePhotoType(item.value)"
|
||||
>
|
||||
<span v-text="item.text" />
|
||||
</t-button>
|
||||
</div>
|
||||
<t-divider />
|
||||
<t-button
|
||||
class="button delete-action"
|
||||
theme="danger"
|
||||
size="extra-small"
|
||||
variant="text"
|
||||
:disabled="isSubmitting"
|
||||
@click="removeCurrentPhoto"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="delete" />
|
||||
</template>
|
||||
删除
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-popover>
|
||||
</div>
|
||||
</template>
|
||||
</t-image-viewer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { ButtonProps } from "tdesign-mobile-vue";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import { Message } from "@/utils/message";
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
});
|
||||
|
||||
interface Props {
|
||||
addActions?: readonly AddAction[];
|
||||
addText?: string;
|
||||
editMode?: boolean;
|
||||
emptyText?: string;
|
||||
fallbackImage?: string;
|
||||
loading?: boolean;
|
||||
modelValue: string[];
|
||||
photoItems?: readonly PhotoItem[];
|
||||
required?: boolean;
|
||||
upload?: (fileList: File[]) => Promise<PhotoItem[]>;
|
||||
showViewerActions?: boolean;
|
||||
showAdd?: boolean;
|
||||
showRemove?: boolean;
|
||||
showTypeLabel?: boolean;
|
||||
submit?: (photoItems: PhotoItem[]) => Promise<void>;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
type AddAction = {
|
||||
icon?: string;
|
||||
emit: string;
|
||||
text: string;
|
||||
theme?: ButtonProps["theme"];
|
||||
};
|
||||
|
||||
type ViewerPhotoItem = PhotoItem & {
|
||||
sourceIndex: number;
|
||||
};
|
||||
|
||||
const ATTACH_TYPE_TEXT_MAP: Record<string, string> = {
|
||||
ADDITIONAL: "附加照片",
|
||||
PHOTO: "照片",
|
||||
POINT_CARD: "积分卡",
|
||||
OTHER: "其他文件"
|
||||
};
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
addActions: () => [],
|
||||
title: "照片列表",
|
||||
addText: "拍照",
|
||||
editMode: false,
|
||||
emptyText: "暂无照片",
|
||||
loading: false,
|
||||
required: false,
|
||||
showAdd: true,
|
||||
showRemove: true,
|
||||
showTypeLabel: true,
|
||||
showViewerActions: true
|
||||
});
|
||||
|
||||
type Emits = {
|
||||
(event: string): void;
|
||||
(event: "update:modelValue", value: string[]): void;
|
||||
(event: "update:photoItems", value: PhotoItem[]): void;
|
||||
};
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
const photoViewerVisible = ref(false);
|
||||
const photoViewerImages = ref<string[]>([]);
|
||||
const photoViewerItems = ref<ViewerPhotoItem[]>([]);
|
||||
const photoViewerIndex = ref(0);
|
||||
const photoActionVisible = ref(false);
|
||||
const isSubmitting = ref(false);
|
||||
const isUploading = ref(false);
|
||||
const addPopoverVisible = ref(false);
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const addActionList = computed<readonly AddAction[]>(() => props.addActions.length ? props.addActions : [{
|
||||
emit: "add",
|
||||
text: props.addText,
|
||||
theme: "default"
|
||||
}]);
|
||||
const isBusy = computed(() => props.loading || isSubmitting.value || isUploading.value);
|
||||
const displayPhotoList = computed<PhotoItem[]>(() => {
|
||||
if (props.photoItems?.length) {
|
||||
return props.photoItems.map(normalizePhotoItem);
|
||||
}
|
||||
if (props.modelValue.length) {
|
||||
return props.modelValue.map(url => ({ url, attachType: "PHOTO" }));
|
||||
}
|
||||
|
||||
return props.fallbackImage ? [{ url: props.fallbackImage, attachType: "PHOTO" }] : [];
|
||||
});
|
||||
const hasRemovablePhotos = computed(() => !!props.photoItems?.length || !!props.modelValue.length);
|
||||
const attachTypeOptions = [
|
||||
{ text: "照片", value: "PHOTO" },
|
||||
{ text: "积分卡", value: "POINT_CARD" },
|
||||
{ text: "其他文件", value: "OTHER" }
|
||||
] as const;
|
||||
const currentPhotoItem = computed(() => photoViewerItems.value[photoViewerIndex.value]);
|
||||
|
||||
function getAttachTypeText(attachType?: string): string {
|
||||
return ATTACH_TYPE_TEXT_MAP[attachType || "PHOTO"] || "其他文件";
|
||||
}
|
||||
|
||||
function handleAddAction(action?: AddAction): void {
|
||||
if (!action) {
|
||||
return;
|
||||
}
|
||||
addPopoverVisible.value = false;
|
||||
if (action.emit === "add" && props.upload) {
|
||||
fileInput.value?.click();
|
||||
return;
|
||||
}
|
||||
emit(action.emit);
|
||||
}
|
||||
|
||||
async function handleFileChange(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const fileList = Array.from(input.files || []);
|
||||
if (!fileList.length || !props.upload) {
|
||||
return;
|
||||
}
|
||||
|
||||
isUploading.value = true;
|
||||
try {
|
||||
const uploadedPhotoItems = await props.upload(fileList);
|
||||
if (!uploadedPhotoItems.length) {
|
||||
return;
|
||||
}
|
||||
const nextPhotoItems = [...displayPhotoList.value, ...uploadedPhotoItems];
|
||||
emit("update:photoItems", nextPhotoItems);
|
||||
emit("update:modelValue", nextPhotoItems.map(item => item.url));
|
||||
} catch {
|
||||
Message.error("照片上传失败");
|
||||
} finally {
|
||||
isUploading.value = false;
|
||||
input.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function removePhoto(index: number): Promise<void> {
|
||||
if (index < 0 || displayPhotoList.value.length <= index) {
|
||||
return;
|
||||
}
|
||||
|
||||
await applyPhotoItems(displayPhotoList.value.filter((_, itemIndex) => itemIndex !== index));
|
||||
}
|
||||
|
||||
function openPhotoViewer(index: number): void {
|
||||
const viewerItems = displayPhotoList.value.map((item, sourceIndex) => ({ item, sourceIndex }));
|
||||
const rotatedItems = [...viewerItems.slice(index), ...viewerItems.slice(0, index)];
|
||||
photoViewerItems.value = rotatedItems.map(({ item, sourceIndex }) => ({ ...item, sourceIndex }));
|
||||
photoViewerImages.value = photoViewerItems.value.map(item => item.previewUrl || item.url);
|
||||
photoViewerIndex.value = 0;
|
||||
photoActionVisible.value = false;
|
||||
photoViewerVisible.value = true;
|
||||
}
|
||||
|
||||
function handlePhotoViewerIndexChange(index: number): void {
|
||||
photoViewerIndex.value = index;
|
||||
photoActionVisible.value = false;
|
||||
}
|
||||
|
||||
async function changePhotoType(attachType: string): Promise<void> {
|
||||
const currentItem = currentPhotoItem.value;
|
||||
if (!currentItem || currentItem.attachType === attachType) {
|
||||
photoActionVisible.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const nextPhotoItems = displayPhotoList.value.map((item, index) => index === currentItem.sourceIndex ? {
|
||||
...item,
|
||||
attachType
|
||||
} : item);
|
||||
await applyPhotoItems(nextPhotoItems);
|
||||
}
|
||||
|
||||
async function removeCurrentPhoto(): Promise<void> {
|
||||
const currentItem = currentPhotoItem.value;
|
||||
if (!currentItem) {
|
||||
return;
|
||||
}
|
||||
|
||||
await applyPhotoItems(displayPhotoList.value.filter((_, index) => index !== currentItem.sourceIndex));
|
||||
}
|
||||
|
||||
async function applyPhotoItems(nextPhotoItems: PhotoItem[]): Promise<void> {
|
||||
if (isSubmitting.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!props.editMode && !props.submit) {
|
||||
Message.warning("展示模式未配置照片保存方法");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!props.editMode) {
|
||||
isSubmitting.value = true;
|
||||
try {
|
||||
await props.submit!(nextPhotoItems);
|
||||
} catch {
|
||||
Message.error("照片修改失败");
|
||||
return;
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
emit("update:photoItems", nextPhotoItems);
|
||||
emit("update:modelValue", nextPhotoItems.map(item => item.url));
|
||||
photoActionVisible.value = false;
|
||||
photoViewerVisible.value = false;
|
||||
}
|
||||
|
||||
function normalizePhotoItem(item: PhotoItem): PhotoItem {
|
||||
return {
|
||||
...item,
|
||||
attachType: item.attachType || item.attachment?.attachType || "PHOTO"
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.photo-scroller {
|
||||
gap: .375rem;
|
||||
width: 100%;
|
||||
display: grid;
|
||||
|
||||
.file-input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.photo-shell {
|
||||
display: grid;
|
||||
gap: .75rem;
|
||||
grid-template-columns: minmax(0, 1fr) 5.5rem;
|
||||
align-items: start;
|
||||
|
||||
&.without-add {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.items {
|
||||
gap: .75rem;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: thin;
|
||||
|
||||
.empty {
|
||||
width: 100%;
|
||||
color: #52607a;
|
||||
display: flex;
|
||||
padding: 1rem 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #f8fbff;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
.item {
|
||||
width: 5.5rem;
|
||||
height: 5.5rem;
|
||||
flex: 0 0 5.5rem;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 1rem;
|
||||
|
||||
.preview-trigger {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
cursor: pointer;
|
||||
background: transparent;
|
||||
|
||||
.image {
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.type-label {
|
||||
width: 100%;
|
||||
bottom: 0;
|
||||
padding: .125rem .5rem;
|
||||
position: absolute;
|
||||
overflow: hidden;
|
||||
font-size: .875rem;
|
||||
text-align: center;
|
||||
line-height: 1.2;
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.remove {
|
||||
top: .375rem;
|
||||
right: .375rem;
|
||||
position: absolute;
|
||||
|
||||
:deep(.t-button__content) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.t-form__label {
|
||||
&.required::before {
|
||||
color: var(--td-error-color, #e34d59);
|
||||
content: "*";
|
||||
margin-right: .25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.add-trigger {
|
||||
--td-popover-padding: 0 .5rem;
|
||||
width: 5.5rem;
|
||||
height: 5.5rem;
|
||||
|
||||
:deep(.t-popover__content) {
|
||||
border-radius: .875rem;
|
||||
}
|
||||
|
||||
.add {
|
||||
--td-button-border-radius: .875rem;
|
||||
|
||||
width: 5.5rem;
|
||||
height: 5.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.add-actions {
|
||||
gap: .25rem;
|
||||
display: grid;
|
||||
padding: .5rem 0;
|
||||
|
||||
.add-action {
|
||||
--td-button-medium-height: 32px;
|
||||
--td-button-medium-padding-horizontal: 10px;
|
||||
|
||||
gap: .5rem;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
font-weight: unset;
|
||||
justify-content: start;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.viewer-action {
|
||||
color: #fff;
|
||||
margin-left: -1rem;
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
min-width: 8rem;
|
||||
flex-direction: column;
|
||||
|
||||
.title {
|
||||
padding: 0 .75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.type {
|
||||
display: flex;
|
||||
justify-content: start;
|
||||
flex-direction: column;
|
||||
|
||||
.button {
|
||||
text-indent: 1.5em;
|
||||
}
|
||||
}
|
||||
|
||||
.button {
|
||||
justify-content: start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.photo-scroller {
|
||||
.field-title,
|
||||
.photo-empty {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.photo-empty {
|
||||
color: #e2e8f0;
|
||||
background: rgba(15, 23, 42, .72);
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
|
||||
.add {
|
||||
background: rgba(37, 99, 235, .16);
|
||||
border-color: rgba(96, 165, 250, .28);
|
||||
|
||||
span {
|
||||
color: #93c5fd;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -8,27 +8,8 @@
|
||||
@click="open"
|
||||
>
|
||||
<span class="picker-text" v-text="selectedProductName || props.placeholder" />
|
||||
<template #help>
|
||||
<div v-if="selectedSku" class="selected-tags">
|
||||
<t-tag
|
||||
v-for="entry in selectedSkuSpecEntries"
|
||||
:key="`${entry.specName}-${entry.valueName}`"
|
||||
size="small"
|
||||
theme="primary"
|
||||
variant="light-outline"
|
||||
:content="entry.valueName"
|
||||
/>
|
||||
<t-tag
|
||||
v-if="!selectedSkuSpecEntries.length"
|
||||
size="small"
|
||||
theme="primary"
|
||||
variant="light-outline"
|
||||
:content="selectedSku.specSummary || selectedSku.name || '默认 SKU'"
|
||||
/>
|
||||
<t-tag v-if="selectedUnit?.name" size="small" :content="selectedUnit.name" />
|
||||
</div>
|
||||
</template>
|
||||
</t-form-item>
|
||||
<product-sku-form-item :sku="selectedSku" :unit="selectedUnit" />
|
||||
<bottom-popup
|
||||
v-model="visible"
|
||||
title="选择产品 SKU"
|
||||
@@ -37,7 +18,6 @@
|
||||
@left-button-click="close"
|
||||
>
|
||||
<div class="popup">
|
||||
<div class="products">
|
||||
<div class="search-wrap">
|
||||
<t-input v-model="keyword" class="search" borderless placeholder="搜索产品名称或编码" />
|
||||
</div>
|
||||
@@ -51,14 +31,14 @@
|
||||
@change="handleProductChange"
|
||||
>
|
||||
<t-collapse-panel
|
||||
class="item"
|
||||
v-for="(product, productIndex) in visibleProductList"
|
||||
:key="getProductKey(product, productIndex)"
|
||||
:value="getProductKey(product, productIndex)"
|
||||
class="panel"
|
||||
placement="bottom"
|
||||
>
|
||||
<template #header>
|
||||
<div class="product-header">
|
||||
<div class="header">
|
||||
<t-image
|
||||
v-if="getProductPhotoURL(product)"
|
||||
:src="getProductPhotoURL(product)"
|
||||
@@ -67,10 +47,7 @@
|
||||
class="avatar"
|
||||
/>
|
||||
<div v-else class="avatar fallback" v-text="(product.name || product.code || '产').slice(0, 1)" />
|
||||
<div class="product-info">
|
||||
<strong v-text="product.name || '未命名产品'" />
|
||||
<span v-text="`${product.code || '-'} · ${product.skuList?.length || 0} 个 SKU`" />
|
||||
</div>
|
||||
<strong class="clip-text" v-text="product.name || '未命名产品'" />
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="isExpandedProduct(product, productIndex)" class="selection">
|
||||
@@ -91,10 +68,6 @@
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="matchedSku" class="sku-card">
|
||||
<div class="sku-title">
|
||||
<strong v-text="matchedSku.name || matchedSku.specSummary || '默认 SKU'" />
|
||||
<span v-if="matchedSku.code" v-text="matchedSku.code" />
|
||||
</div>
|
||||
<div class="units">
|
||||
<t-button
|
||||
v-for="unit in saleableUnits(matchedSku)"
|
||||
@@ -116,17 +89,24 @@
|
||||
<div v-else class="empty" v-text="loading ? '正在加载可售产品' : '暂无可售产品'" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import type { Product, ProductSku, ProductSkuUnit, ProductSpec, ProductSpecValue } from "@/types/Product";
|
||||
import ProductSkuFormItem from "@/components/ProductSkuFormItem.vue";
|
||||
import type {
|
||||
Product,
|
||||
ProductSelection,
|
||||
ProductSku,
|
||||
ProductSkuUnit,
|
||||
ProductSpec,
|
||||
ProductSpecValue
|
||||
} from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatProductAmount, getProductPhotoURL, getProductSkuSpecEntries } from "@/utils/product";
|
||||
import { formatProductAmount, getProductPhotoURL } from "@/utils/product";
|
||||
|
||||
interface Props {
|
||||
modelValue: { skuId: string; skuUnitId: string } | undefined;
|
||||
@@ -137,7 +117,10 @@ interface Props {
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), { label: "产品", requiredMark: false, placeholder: "请选择产品 SKU" });
|
||||
const emit = defineEmits<{ "update:modelValue": [value: Props["modelValue"]] }>();
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: Props["modelValue"]];
|
||||
select: [selection: ProductSelection];
|
||||
}>();
|
||||
const visible = ref(false);
|
||||
const loading = ref(false);
|
||||
const keyword = ref("");
|
||||
@@ -152,10 +135,9 @@ const selectedProduct = computed(() => {
|
||||
}
|
||||
return props.selectedProduct || productList.value.find(item => item.skuList?.some(sku => sku.id === props.modelValue?.skuId));
|
||||
});
|
||||
const selectedSku = computed(() => selectedProduct.value?.skuList?.find(item => item.id === props.modelValue?.skuId));
|
||||
const selectedUnit = computed(() => selectedSku.value?.unitList?.find(item => item.id === props.modelValue?.skuUnitId));
|
||||
const selectedProductName = computed(() => selectedProduct.value?.name || "");
|
||||
const selectedSkuSpecEntries = computed(() => getProductSkuSpecEntries(selectedSku.value || { specValueIdList: [] }, selectedProduct.value?.specList || []));
|
||||
const selectedSku = computed(() => selectedProduct.value?.skuList?.find(sku => sku.id === props.modelValue?.skuId));
|
||||
const selectedUnit = computed(() => selectedSku.value?.unitList?.find(unit => unit.id === props.modelValue?.skuUnitId));
|
||||
const filteredProductList = computed(() => {
|
||||
const text = keyword.value.toLocaleLowerCase();
|
||||
return productList.value.filter(item => !text || `${item.name}${item.code}`.toLocaleLowerCase().includes(text));
|
||||
@@ -242,6 +224,11 @@ function selectUnit(sku: ProductSku, skuUnitId: string): void {
|
||||
if (!sku.id || !skuUnitId) {
|
||||
return;
|
||||
}
|
||||
const product = activeProduct.value;
|
||||
const unit = sku.unitList?.find(item => item.id === skuUnitId);
|
||||
if (product && unit) {
|
||||
emit("select", { product, sku, unit });
|
||||
}
|
||||
emit("update:modelValue", { skuId: sku.id, skuUnitId });
|
||||
close();
|
||||
}
|
||||
@@ -249,84 +236,18 @@ function selectUnit(sku: ProductSku, skuUnitId: string): void {
|
||||
|
||||
<style scoped lang="less">
|
||||
.product-selector {
|
||||
|
||||
.picker-text {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.selected-tags {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
.popup {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: 1rem 0;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.selection {
|
||||
overflow-y: auto;
|
||||
|
||||
.specs {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.spec {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.values,
|
||||
.units {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sku-card {
|
||||
margin-top: 1.25rem;
|
||||
padding: .75rem;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-radius: .875rem;
|
||||
|
||||
.sku-title {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
|
||||
span {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.units {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
margin-top: .75rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.price {
|
||||
margin-left: .25rem;
|
||||
font-size: .75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.products {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.search-wrap {
|
||||
@@ -349,43 +270,64 @@ function selectUnit(sku: ProductSku, skuUnitId: string): void {
|
||||
padding-bottom: env(safe-area-inset-bottom, 0);
|
||||
|
||||
.collapse {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
margin: 0;
|
||||
|
||||
.product-header {
|
||||
.item {
|
||||
--td-collapse-content-padding: .25rem 1rem .75rem 1rem;
|
||||
|
||||
.header {
|
||||
gap: .75rem;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
|
||||
.avatar {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
flex: 0 0 auto;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: .75rem !important;
|
||||
}
|
||||
}
|
||||
|
||||
.product-info {
|
||||
gap: .25rem;
|
||||
.selection {
|
||||
overflow-y: auto;
|
||||
|
||||
.specs {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
|
||||
strong,
|
||||
span {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
.spec {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.values,
|
||||
.units {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
span {
|
||||
color: var(--td-text-color-secondary);
|
||||
.sku-card {
|
||||
padding: .5rem;
|
||||
border: 1px dashed var(--td-brand-color);
|
||||
margin-top: .5rem;
|
||||
border-radius: .875rem;
|
||||
|
||||
.units {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.price {
|
||||
margin-left: .25rem;
|
||||
font-size: .75rem;
|
||||
}
|
||||
}
|
||||
|
||||
&:active {
|
||||
opacity: .7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<template>
|
||||
<t-form-item v-if="skuText || unitText" label="产品 SKU" content-align="right">
|
||||
<product-sku-tags :fallback="skuText" :unit="unitText" />
|
||||
</t-form-item>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import ProductSkuTags from "@/components/ProductSkuTags.vue";
|
||||
import type { ProductSku, ProductSkuUnit } from "@/types/Product";
|
||||
|
||||
defineOptions({ name: "ProductSkuFormItem" });
|
||||
|
||||
interface Props {
|
||||
sku?: ProductSku;
|
||||
unit?: ProductSkuUnit;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
||||
const skuText = computed(() => props.sku?.name?.trim() || props.sku?.specSummary?.trim() || "");
|
||||
const unitText = computed(() => props.unit?.name?.trim() || "");
|
||||
</script>
|
||||
@@ -16,7 +16,7 @@
|
||||
import type { ProductSkuSpecSnapshot } from "@/types/Product";
|
||||
import { getProductSkuSnapshotText } from "@/utils/product";
|
||||
|
||||
defineOptions({ name: "ProductSkuSnapshotTags" });
|
||||
defineOptions({ name: "ProductSkuTags" });
|
||||
|
||||
interface Props {
|
||||
productName?: string | null;
|
||||
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<t-table
|
||||
class="product-stock-preview"
|
||||
:columns="columns"
|
||||
:data="items"
|
||||
row-key="skuId"
|
||||
table-layout="fixed"
|
||||
vertical-align="middle"
|
||||
>
|
||||
<template #product="{ row }">
|
||||
<span class="product clip-text" v-text="row.productName || '未命名产品'" />
|
||||
</template>
|
||||
<template #required="{ row }">
|
||||
<span v-text="row.baseQuantity" />
|
||||
</template>
|
||||
<template #available="{ row }">
|
||||
<span v-text="row.availableQuantity" />
|
||||
</template>
|
||||
<template #check="{ row }">
|
||||
<strong :class="row.shortageQuantity ? 'shortage' : 'sufficient'" v-text="row.shortageQuantity ? '缺少' : '充足'" />
|
||||
</template>
|
||||
<template #footerSummary>
|
||||
<div class="orange tips">仅供参考,以实际提交为准</div>
|
||||
</template>
|
||||
</t-table>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { ProductStockPreviewItem } from "@/utils/productStock";
|
||||
|
||||
defineOptions({
|
||||
name: "ProductStockPreview"
|
||||
});
|
||||
|
||||
defineProps<{
|
||||
items: ProductStockPreviewItem[];
|
||||
}>();
|
||||
|
||||
const columns = [
|
||||
{ colKey: "product", title: "产品", width: "40%", ellipsis: true },
|
||||
{ colKey: "required", title: "需求", width: "20%", align: "right", cell: "required" },
|
||||
{ colKey: "available", title: "可用", width: "20%", align: "right", cell: "available" },
|
||||
{ colKey: "check", title: "校验", width: "20%", align: "center", cell: "check" }
|
||||
];
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.product-stock-preview {
|
||||
--td-component-border: transparent;
|
||||
|
||||
.product {
|
||||
min-width: 0;
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sufficient {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
||||
.shortage {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
|
||||
:deep(.t-table__content) {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
:deep(th),
|
||||
:deep(td) {
|
||||
padding: .25rem .375rem;
|
||||
}
|
||||
|
||||
.tips {
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,16 +1,19 @@
|
||||
<template>
|
||||
<t-popup v-model="popupVisible" placement="bottom">
|
||||
<div class="tag-selector bg-white">
|
||||
<div class="title-bar">
|
||||
<t-button variant="text" size="small" @click="cancelSelection">取消</t-button>
|
||||
<h3 class="title">选择标签</h3>
|
||||
<t-button theme="primary" variant="text" size="small" @click="confirmSelection">确定</t-button>
|
||||
</div>
|
||||
<div class="search-row">
|
||||
<bottom-popup
|
||||
v-model="popupVisible"
|
||||
title="选择标签"
|
||||
height="78vh"
|
||||
left-button-text="取消"
|
||||
right-button-text="确定"
|
||||
@left-button-click="cancelSelection"
|
||||
@right-button-click="confirmSelection"
|
||||
>
|
||||
<div class="tag-selector">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
class="input"
|
||||
size="small"
|
||||
v-model.trim="keyword"
|
||||
v-model="keyword"
|
||||
borderless
|
||||
clearable
|
||||
placeholder="搜索标签"
|
||||
@@ -19,7 +22,7 @@
|
||||
<t-input
|
||||
class="input"
|
||||
size="small"
|
||||
v-model.trim="newTagName"
|
||||
v-model="newTagName"
|
||||
borderless
|
||||
clearable
|
||||
placeholder="新增标签名称"
|
||||
@@ -29,10 +32,12 @@
|
||||
size="small"
|
||||
:loading="isCreating"
|
||||
:disabled="isCreating"
|
||||
content="新增"
|
||||
@click="createTag"
|
||||
>新增</t-button>
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div class="list-wrap">
|
||||
<div class="list">
|
||||
<t-tag
|
||||
v-for="(item, index) in visibleTagList"
|
||||
@@ -46,13 +51,15 @@
|
||||
>
|
||||
<span v-text="getTagName(item)" />
|
||||
</t-tag>
|
||||
<div v-if="!visibleTagList.length" class="empty" v-text="emptyText" />
|
||||
<div v-if="!visibleTagList.length" class="center-tips" v-text="emptyText" />
|
||||
</div>
|
||||
</div>
|
||||
</t-popup>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { Message } from "@/utils/message";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import TagAPI from "@/api/TagAPI";
|
||||
@@ -198,33 +205,20 @@ watch(() => props.visible, async (value) => {
|
||||
|
||||
<style scoped lang="less">
|
||||
.tag-selector {
|
||||
display: flex;
|
||||
height: 78vh;
|
||||
padding-top: 1rem;
|
||||
border-radius: 1.25rem 1.25rem 0 0;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
min-height: 0;
|
||||
|
||||
.title-bar {
|
||||
padding: 0 1rem;
|
||||
display: grid;
|
||||
grid-template-columns: 4rem 1fr 4rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.search-row {
|
||||
.filters {
|
||||
gap: .5rem;
|
||||
top: 0;
|
||||
display: flex;
|
||||
padding: 1rem;
|
||||
padding: .5rem 1rem;
|
||||
position: sticky;
|
||||
align-items: center;
|
||||
|
||||
.input {
|
||||
--td-input-vertical-padding: 6px;
|
||||
--td-input-vertical-padding: .5rem 1rem;
|
||||
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: .875rem;
|
||||
@@ -233,13 +227,10 @@ watch(() => props.visible, async (value) => {
|
||||
|
||||
.list {
|
||||
gap: .75rem;
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
padding: 0 1rem 1rem;
|
||||
flex-wrap: wrap;
|
||||
align-content: flex-start;
|
||||
padding: 0 1rem calc(1rem + env(safe-area-inset-bottom, 0)) 1rem;
|
||||
|
||||
.item {
|
||||
flex: 1 1 auto;
|
||||
@@ -248,22 +239,10 @@ watch(() => props.visible, async (value) => {
|
||||
max-width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: #52607a;
|
||||
padding: 2rem 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.tag-selector {
|
||||
background: rgba(15, 23, 42, .96);
|
||||
|
||||
.empty {
|
||||
color: #94a3b8;
|
||||
}
|
||||
}
|
||||
:global(.bottom-popup:has(.tag-selector) .body) {
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/** 过滤项支持的值类型。 */
|
||||
export type FilterValue = string | number | boolean;
|
||||
|
||||
/** 一个过滤组的选中值。 */
|
||||
export type FilterValueList = FilterValue[];
|
||||
|
||||
/** 过滤组的选项控件类型。 */
|
||||
export type FilterControl = "checkbox" | "radio";
|
||||
|
||||
/** 过滤弹窗的值模型。 */
|
||||
export type FilterModel = Record<string, FilterValueList>;
|
||||
|
||||
/** 过滤项配置。 */
|
||||
export interface FilterOption {
|
||||
label: string;
|
||||
value: FilterValue;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/** 过滤值变化上下文。 */
|
||||
export interface FilterChangeContext {
|
||||
group: FilterGroup;
|
||||
groupKey: string;
|
||||
value: FilterValueList;
|
||||
previousValue: FilterValueList;
|
||||
changedValue?: FilterValue;
|
||||
checked?: boolean;
|
||||
modelValue: FilterModel;
|
||||
}
|
||||
|
||||
/** 过滤值变化回调返回值。数组用于替换当前组,对象用于修改一个或多个组。 */
|
||||
export type FilterChangeResult = FilterValueList | Partial<FilterModel> | void;
|
||||
|
||||
/** 过滤值变化回调。 */
|
||||
export type FilterChangeHandler = (context: FilterChangeContext) => FilterChangeResult;
|
||||
|
||||
/** 过滤组配置。 */
|
||||
export interface FilterGroup {
|
||||
key: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
options: FilterOption[];
|
||||
control?: FilterControl;
|
||||
multiple?: boolean;
|
||||
columns: number;
|
||||
readonly?: boolean;
|
||||
readonlyText?: string;
|
||||
onChange?: FilterChangeHandler;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
<template>
|
||||
<bottom-popup
|
||||
v-model="popupVisible"
|
||||
:title="props.title"
|
||||
:height="props.height"
|
||||
:left-button-text="props.leftButtonText"
|
||||
:right-button-text="props.rightButtonText"
|
||||
:z-index="props.zIndex"
|
||||
:overlay-props="props.overlayProps"
|
||||
@left-button-click="reset"
|
||||
@right-button-click="confirm"
|
||||
>
|
||||
<div class="filter-popup bg-white">
|
||||
<slot name="before" />
|
||||
<section v-for="group in props.groups" :key="group.key" class="section">
|
||||
<div class="title">
|
||||
<strong v-text="group.title" />
|
||||
<span v-if="group.description" v-text="group.description" />
|
||||
</div>
|
||||
<slot :name="`group-${group.key}-before`" :group="group" :value="getGroupValue(group)" />
|
||||
<div v-if="group.readonly" class="fixed-filter">
|
||||
<t-icon name="layers" />
|
||||
<span v-text="group.readonlyText || '当前条件已固定'" />
|
||||
</div>
|
||||
<t-radio-group
|
||||
v-else-if="group.control === 'radio' && group.options.length"
|
||||
:model-value="getSingleGroupValue(group)"
|
||||
class="radio-options"
|
||||
:style="{ gridTemplateColumns: `repeat(${group.columns}, minmax(0, 1fr))` }"
|
||||
@change="value => changeRadioGroup(group, value)"
|
||||
>
|
||||
<t-radio
|
||||
v-for="option in group.options"
|
||||
:key="String(option.value)"
|
||||
class="radio-option"
|
||||
:value="option.value"
|
||||
:disabled="option.disabled"
|
||||
:block="false"
|
||||
borderless
|
||||
>
|
||||
<span v-text="option.label" />
|
||||
</t-radio>
|
||||
</t-radio-group>
|
||||
<t-checkbox-group
|
||||
v-else-if="group.options.length"
|
||||
:model-value="getGroupValue(group)"
|
||||
class="options"
|
||||
:style="{ gridTemplateColumns: `repeat(${group.columns}, minmax(0, 1fr))` }"
|
||||
@change="(value, context) => changeGroup(group, value, context)"
|
||||
>
|
||||
<t-checkbox
|
||||
v-for="option in group.options"
|
||||
:key="String(option.value)"
|
||||
class="option"
|
||||
:value="option.value"
|
||||
:label="option.label"
|
||||
:disabled="option.disabled"
|
||||
icon="line"
|
||||
borderless
|
||||
/>
|
||||
</t-checkbox-group>
|
||||
<slot :name="`group-${group.key}`" :group="group" :value="getGroupValue(group)" />
|
||||
<slot :name="`group-${group.key}-after`" :group="group" :value="getGroupValue(group)" />
|
||||
</section>
|
||||
<slot name="after" />
|
||||
<slot />
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import type {
|
||||
FilterChangeContext,
|
||||
FilterChangeHandler,
|
||||
FilterChangeResult,
|
||||
FilterGroup,
|
||||
FilterModel,
|
||||
FilterValue,
|
||||
FilterValueList
|
||||
} from "./FilterPopup";
|
||||
|
||||
defineOptions({ name: "FilterPopup" });
|
||||
|
||||
interface Props {
|
||||
modelValue: FilterModel;
|
||||
visible: boolean;
|
||||
groups: FilterGroup[];
|
||||
title?: string;
|
||||
height?: string | number;
|
||||
leftButtonText?: string;
|
||||
rightButtonText?: string;
|
||||
resetValue?: FilterModel;
|
||||
zIndex?: number;
|
||||
overlayProps?: Record<string, unknown>;
|
||||
onFilterChange?: FilterChangeHandler;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
title: "筛选",
|
||||
height: "auto",
|
||||
leftButtonText: "重置",
|
||||
rightButtonText: "确定"
|
||||
});
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: FilterModel];
|
||||
"update:visible": [value: boolean];
|
||||
change: [value: FilterModel, context: FilterChangeContext];
|
||||
reset: [value: FilterModel];
|
||||
confirm: [value: FilterModel];
|
||||
}>();
|
||||
|
||||
const popupVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: value => emit("update:visible", value)
|
||||
});
|
||||
|
||||
function getGroupValue(group: FilterGroup): FilterValueList {
|
||||
const value = props.modelValue[group.key] || [];
|
||||
return group.multiple === false ? value.slice(-1) : value;
|
||||
}
|
||||
|
||||
function getSingleGroupValue(group: FilterGroup): FilterValue | undefined {
|
||||
return getGroupValue(group)[0];
|
||||
}
|
||||
|
||||
function changeRadioGroup(group: FilterGroup, value: unknown): void {
|
||||
changeGroup(group, isFilterValue(value) ? [value] : [], { current: value, type: "check" });
|
||||
}
|
||||
|
||||
function changeGroup(group: FilterGroup, value: unknown, changeContext: unknown): void {
|
||||
const previousValue = [...getGroupValue(group)];
|
||||
const checkboxValue = toFilterValueList(value);
|
||||
const contextValue = getChangedValue(changeContext);
|
||||
const checked = getCheckedState(changeContext);
|
||||
const nextValue = normalizeGroupValue(group, checkboxValue, contextValue, checked);
|
||||
const nextModel = cloneFilterModel(props.modelValue);
|
||||
nextModel[group.key] = nextValue;
|
||||
const context: FilterChangeContext = {
|
||||
group,
|
||||
groupKey: group.key,
|
||||
value: [...nextValue],
|
||||
previousValue,
|
||||
changedValue: contextValue,
|
||||
checked,
|
||||
modelValue: cloneFilterModel(nextModel)
|
||||
};
|
||||
|
||||
const groupResult = group.onChange?.(context);
|
||||
const groupModel = applyChangeResult(nextModel, group.key, groupResult);
|
||||
const finalContext: FilterChangeContext = {
|
||||
...context,
|
||||
value: [...(groupModel[group.key] || [])],
|
||||
modelValue: cloneFilterModel(groupModel)
|
||||
};
|
||||
const finalModel = applyChangeResult(groupModel, group.key, props.onFilterChange?.(finalContext));
|
||||
emit("update:modelValue", finalModel);
|
||||
emit("change", finalModel, finalContext);
|
||||
}
|
||||
|
||||
function normalizeGroupValue(
|
||||
group: FilterGroup,
|
||||
value: FilterValueList,
|
||||
changedValue?: FilterValue,
|
||||
checked?: boolean
|
||||
): FilterValueList {
|
||||
if (group.multiple !== false || value.length < 2) {
|
||||
return value;
|
||||
}
|
||||
if (checked !== false && changedValue !== undefined) {
|
||||
return [changedValue];
|
||||
}
|
||||
return value.slice(-1);
|
||||
}
|
||||
|
||||
function applyChangeResult(model: FilterModel, groupKey: string, result: FilterChangeResult): FilterModel {
|
||||
if (!result) {
|
||||
return model;
|
||||
}
|
||||
if (Array.isArray(result)) {
|
||||
return { ...model, [groupKey]: toFilterValueList(result) };
|
||||
}
|
||||
const nextModel = cloneFilterModel(model);
|
||||
for (const [key, value] of Object.entries(result)) {
|
||||
if (Array.isArray(value)) {
|
||||
nextModel[key] = toFilterValueList(value);
|
||||
}
|
||||
}
|
||||
return nextModel;
|
||||
}
|
||||
|
||||
function toFilterValueList(value: unknown): FilterValueList {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
return value.filter(isFilterValue);
|
||||
}
|
||||
|
||||
function isFilterValue(value: unknown): value is FilterValue {
|
||||
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
||||
}
|
||||
|
||||
function getChangedValue(value: unknown): FilterValue | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const current = (value as { current?: unknown }).current;
|
||||
return isFilterValue(current) ? current : undefined;
|
||||
}
|
||||
|
||||
function getCheckedState(value: unknown): boolean | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const type = (value as { type?: unknown }).type;
|
||||
return type === "check" ? true : type === "uncheck" ? false : undefined;
|
||||
}
|
||||
|
||||
function cloneFilterModel(model: FilterModel): FilterModel {
|
||||
return Object.fromEntries(Object.entries(model).map(([key, value]) => [key, toFilterValueList(value)]));
|
||||
}
|
||||
|
||||
function createEmptyFilterModel(): FilterModel {
|
||||
return Object.fromEntries(props.groups.map(group => [group.key, []]));
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
const value = cloneFilterModel(props.resetValue || createEmptyFilterModel());
|
||||
emit("update:modelValue", value);
|
||||
emit("reset", value);
|
||||
}
|
||||
|
||||
function confirm(): void {
|
||||
emit("confirm", cloneFilterModel(props.modelValue));
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
:global(.bottom-popup:has(.filter-popup)) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 86vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:global(.bottom-popup:has(.filter-popup) .body) {
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
touch-action: pan-y;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.filter-popup {
|
||||
padding: 0 1rem 1rem;
|
||||
|
||||
.section {
|
||||
padding: 1rem 0 0;
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
margin-bottom: .75rem;
|
||||
justify-content: space-between;
|
||||
|
||||
strong {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
span {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.options,
|
||||
.radio-options {
|
||||
gap: .5rem;
|
||||
display: grid;
|
||||
padding-bottom: .25rem;
|
||||
|
||||
.option,
|
||||
.radio-option {
|
||||
margin: 0;
|
||||
border: 1px solid var(--td-component-border);
|
||||
padding: .5rem;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: .75rem;
|
||||
justify-content: start;
|
||||
|
||||
:deep(input) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:deep(.t-checkbox__label),
|
||||
:deep(.t-radio__label) {
|
||||
font-size: .75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
:deep(.t-radio__icon),
|
||||
:deep(.t-checkbox__icon) {
|
||||
margin-right: .25rem;
|
||||
}
|
||||
|
||||
&:has(:deep(.t-checkbox__icon--checked)),
|
||||
&:has(:deep(.t-radio__icon--checked)) {
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-brand-color-light);
|
||||
border-color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.fixed-filter {
|
||||
gap: .5rem;
|
||||
color: var(--td-brand-color);
|
||||
display: flex;
|
||||
padding: .75rem;
|
||||
font-size: .8125rem;
|
||||
background: var(--td-brand-color-light);
|
||||
align-items: center;
|
||||
border-radius: .5rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,300 @@
|
||||
<template>
|
||||
<div v-bind="$attrs" class="media-selector">
|
||||
<div class="t-form__label" :class="{ required }">
|
||||
<slot name="title">
|
||||
<span v-text="title" />
|
||||
</slot>
|
||||
</div>
|
||||
<div class="photo-shell" :class="{ 'without-add': !showAdd }">
|
||||
<div class="items">
|
||||
<div v-if="!displayMediaList.length" class="empty" v-text="emptyText" />
|
||||
<media-selector-item
|
||||
v-for="(item, index) in displayMediaList"
|
||||
:key="`${item.url}-${item.attachType}-${index}`"
|
||||
:item="item"
|
||||
:removable="hasRemovablePhotos"
|
||||
:show-remove="showRemove === true"
|
||||
:show-type-label="showTypeLabel === true"
|
||||
@preview="openMediaViewer(index)"
|
||||
@remove="removePhoto(index)"
|
||||
/>
|
||||
</div>
|
||||
<media-selector-add
|
||||
v-if="showAdd"
|
||||
:add-actions="props.addActions ?? []"
|
||||
:add-text="props.addText ?? '选择'"
|
||||
:busy="isBusy"
|
||||
:upload-enabled="!!props.upload"
|
||||
@add="handleAdd"
|
||||
@action="handleAddAction"
|
||||
@capture-photo="handleCapturePhoto"
|
||||
@capture-video="handleCaptureVideo"
|
||||
@file-change="handleFileChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<media-selector-viewer
|
||||
v-model:visible="photoViewerVisible"
|
||||
:images="photoViewerImages"
|
||||
:items="photoViewerItems"
|
||||
:viewer-z-index="props.viewerZIndex"
|
||||
:show-actions="showViewerActions === true"
|
||||
:submitting="isSubmitting"
|
||||
@change-type="changePhotoType"
|
||||
@remove="removePhotoBySourceIndex"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import MediaSelectorAdd from "./MediaSelectorAdd.vue";
|
||||
import MediaSelectorItem from "./MediaSelectorItem.vue";
|
||||
import MediaSelectorViewer from "./MediaSelectorViewer.vue";
|
||||
import type { MediaSelectorAddAction, MediaSelectorViewerItem } from "./types";
|
||||
import { getMediaPreviewURL, normalizePhotoItem } from "./utils";
|
||||
import type { PhotoItem } from "@/types/Photo.ts";
|
||||
import { Message } from "@/utils/message.ts";
|
||||
import { saveCapturedFilesFromInput } from "@/utils/twaBridge";
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
});
|
||||
|
||||
interface Props {
|
||||
addActions?: readonly MediaSelectorAddAction[];
|
||||
addText?: string;
|
||||
editMode?: boolean;
|
||||
emptyText?: string;
|
||||
fallbackImage?: string;
|
||||
loading?: boolean;
|
||||
modelValue: string[];
|
||||
photoItems?: readonly PhotoItem[];
|
||||
required?: boolean;
|
||||
upload?: (fileList: File[]) => Promise<PhotoItem[]>;
|
||||
showViewerActions?: boolean;
|
||||
showAdd?: boolean;
|
||||
showRemove?: boolean;
|
||||
showTypeLabel?: boolean;
|
||||
submit?: (photoItems: PhotoItem[]) => Promise<void>;
|
||||
title?: string;
|
||||
viewerZIndex?: number;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
addActions: () => [],
|
||||
title: "媒体列表",
|
||||
addText: "选择",
|
||||
editMode: false,
|
||||
emptyText: "暂无照片",
|
||||
loading: false,
|
||||
required: false,
|
||||
showAdd: true,
|
||||
showRemove: true,
|
||||
showTypeLabel: false,
|
||||
showViewerActions: true
|
||||
});
|
||||
|
||||
type Emits = {
|
||||
add: [];
|
||||
action: [value: MediaSelectorAddAction];
|
||||
"capture-photo": [];
|
||||
"capture-video": [];
|
||||
"update:modelValue": [value: string[]];
|
||||
"update:photoItems": [value: PhotoItem[]];
|
||||
};
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
function handleAddAction(action: MediaSelectorAddAction): void {
|
||||
emit("action", action);
|
||||
}
|
||||
|
||||
function handleAdd(): void {
|
||||
emit("add");
|
||||
}
|
||||
|
||||
function handleCapturePhoto(): void {
|
||||
emit("capture-photo");
|
||||
}
|
||||
|
||||
function handleCaptureVideo(): void {
|
||||
emit("capture-video");
|
||||
}
|
||||
|
||||
const photoViewerVisible = ref(false);
|
||||
const photoViewerImages = ref<string[]>([]);
|
||||
const photoViewerItems = ref<MediaSelectorViewerItem[]>([]);
|
||||
const isSubmitting = ref(false);
|
||||
const isUploading = ref(false);
|
||||
const isBusy = computed(() => props.loading || isSubmitting.value || isUploading.value);
|
||||
|
||||
const displayMediaList = computed<PhotoItem[]>(() => {
|
||||
if (props.photoItems?.length) {
|
||||
return props.photoItems.map(normalizePhotoItem);
|
||||
}
|
||||
if (props.modelValue.length) {
|
||||
return props.modelValue.map(url => ({ url, attachType: "PHOTO" }));
|
||||
}
|
||||
|
||||
return props.fallbackImage ? [{ url: props.fallbackImage, attachType: "PHOTO" }] : [];
|
||||
});
|
||||
const hasRemovablePhotos = computed(() => !!props.photoItems?.length || !!props.modelValue.length);
|
||||
|
||||
async function handleFileChange(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const fileList = Array.from(input.files || []);
|
||||
if (!fileList.length || !props.upload) {
|
||||
return;
|
||||
}
|
||||
saveCapturedFilesFromInput(input, fileList);
|
||||
|
||||
isUploading.value = true;
|
||||
try {
|
||||
const uploadedPhotoItems = await props.upload(fileList);
|
||||
if (!uploadedPhotoItems.length) {
|
||||
return;
|
||||
}
|
||||
const nextPhotoItems = [...displayMediaList.value, ...uploadedPhotoItems.map((item, index) => ({
|
||||
...item,
|
||||
mimeType: item.mimeType || item.attachment?.mimeType || fileList[index]?.type
|
||||
}))];
|
||||
emit("update:photoItems", nextPhotoItems);
|
||||
emit("update:modelValue", nextPhotoItems.map(item => item.url));
|
||||
} catch {
|
||||
Message.error("媒体上传失败");
|
||||
} finally {
|
||||
isUploading.value = false;
|
||||
input.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function removePhoto(index: number): Promise<void> {
|
||||
if (index < 0 || displayMediaList.value.length <= index) {
|
||||
return;
|
||||
}
|
||||
|
||||
await applyPhotoItems(displayMediaList.value.filter((_, itemIndex) => itemIndex !== index));
|
||||
}
|
||||
|
||||
function openMediaViewer(index: number): void {
|
||||
openPhotoViewer(index);
|
||||
}
|
||||
|
||||
function openPhotoViewer(index: number): void {
|
||||
const viewerItems = displayMediaList.value.map((item, sourceIndex) => ({ item, sourceIndex }));
|
||||
const imageIndex = viewerItems.findIndex(({ sourceIndex }) => sourceIndex === index);
|
||||
if (imageIndex < 0) {
|
||||
return;
|
||||
}
|
||||
const rotatedItems = [...viewerItems.slice(imageIndex), ...viewerItems.slice(0, imageIndex)];
|
||||
photoViewerItems.value = rotatedItems.map(({ item, sourceIndex }) => ({ ...item, sourceIndex }));
|
||||
photoViewerImages.value = photoViewerItems.value.map(getMediaPreviewURL);
|
||||
photoViewerVisible.value = true;
|
||||
}
|
||||
|
||||
async function changePhotoType(sourceIndex: number, attachType: string): Promise<void> {
|
||||
const currentItem = displayMediaList.value[sourceIndex];
|
||||
if (!currentItem || currentItem.attachType === attachType) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextPhotoItems = displayMediaList.value.map((item, index) => index === sourceIndex ? {
|
||||
...item,
|
||||
attachType
|
||||
} : item);
|
||||
await applyPhotoItems(nextPhotoItems);
|
||||
}
|
||||
|
||||
async function removePhotoBySourceIndex(sourceIndex: number): Promise<void> {
|
||||
if (!displayMediaList.value[sourceIndex]) {
|
||||
return;
|
||||
}
|
||||
|
||||
await applyPhotoItems(displayMediaList.value.filter((_, index) => index !== sourceIndex));
|
||||
}
|
||||
|
||||
async function applyPhotoItems(nextPhotoItems: PhotoItem[]): Promise<void> {
|
||||
if (isSubmitting.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!props.editMode && !props.submit) {
|
||||
Message.warning("展示模式未配置媒体保存方法");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!props.editMode) {
|
||||
isSubmitting.value = true;
|
||||
try {
|
||||
await props.submit!(nextPhotoItems);
|
||||
} catch {
|
||||
Message.error("媒体修改失败");
|
||||
return;
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
emit("update:photoItems", nextPhotoItems);
|
||||
emit("update:modelValue", nextPhotoItems.map(item => item.url));
|
||||
photoViewerVisible.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.media-selector {
|
||||
gap: .375rem;
|
||||
width: 100%;
|
||||
display: grid;
|
||||
|
||||
.photo-shell {
|
||||
display: grid;
|
||||
gap: .75rem;
|
||||
grid-template-columns: minmax(0, 1fr) 5.5rem;
|
||||
align-items: start;
|
||||
|
||||
&.without-add {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.items {
|
||||
gap: .75rem;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: thin;
|
||||
|
||||
.empty {
|
||||
width: 100%;
|
||||
color: #52607a;
|
||||
display: flex;
|
||||
padding: 1rem 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #f8fbff;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
.t-form__label {
|
||||
&.required::before {
|
||||
color: var(--td-error-color, #e34d59);
|
||||
content: "*";
|
||||
margin-right: .25rem;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.media-selector .empty {
|
||||
color: #e2e8f0;
|
||||
background: rgba(15, 23, 42, .72);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,210 @@
|
||||
<template>
|
||||
<div class="add-trigger">
|
||||
<t-popover
|
||||
v-model:visible="capturePopoverVisible"
|
||||
placement="left"
|
||||
theme="light"
|
||||
>
|
||||
<t-button
|
||||
class="capture"
|
||||
theme="primary"
|
||||
variant="dashed"
|
||||
:loading="busy"
|
||||
:disabled="busy"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="camera" />
|
||||
</template>
|
||||
拍摄
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="add-actions">
|
||||
<t-button
|
||||
v-for="(action, index) in captureActionList"
|
||||
:key="`${action.emit}-${index}`"
|
||||
variant="text"
|
||||
:theme="action.theme"
|
||||
class="add-action"
|
||||
:disabled="busy"
|
||||
@click="handleCaptureAction(action)"
|
||||
>
|
||||
<template #icon v-if="action.icon">
|
||||
<t-icon :name="action.icon" />
|
||||
</template>
|
||||
<span v-text="action.text" />
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-popover>
|
||||
<t-button
|
||||
class="file"
|
||||
theme="primary"
|
||||
variant="dashed"
|
||||
:loading="busy"
|
||||
:disabled="busy"
|
||||
@click="handleFileAction"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="file-attachment" />
|
||||
</template>
|
||||
<span v-text="addText" />
|
||||
</t-button>
|
||||
</div>
|
||||
<input
|
||||
v-if="uploadEnabled"
|
||||
ref="fileInput"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="*/*"
|
||||
multiple
|
||||
@change="handleFileChange"
|
||||
/>
|
||||
<input
|
||||
v-if="uploadEnabled"
|
||||
ref="photoFileInput"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
@change="handleFileChange"
|
||||
/>
|
||||
<input
|
||||
v-if="uploadEnabled"
|
||||
ref="videoFileInput"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="video/*"
|
||||
capture="environment"
|
||||
@change="handleFileChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { MediaSelectorAddAction } from "./types";
|
||||
|
||||
interface Props {
|
||||
addActions: readonly MediaSelectorAddAction[];
|
||||
addText: string;
|
||||
busy: boolean;
|
||||
uploadEnabled: boolean;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
const emit = defineEmits<{
|
||||
add: [];
|
||||
action: [value: MediaSelectorAddAction];
|
||||
"capture-photo": [];
|
||||
"capture-video": [];
|
||||
"file-change": [value: Event];
|
||||
}>();
|
||||
|
||||
const capturePopoverVisible = ref(false);
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const photoFileInput = ref<HTMLInputElement>();
|
||||
const videoFileInput = ref<HTMLInputElement>();
|
||||
const captureActionList = computed<readonly MediaSelectorAddAction[]>(() => [{
|
||||
icon: "camera",
|
||||
emit: "capture-photo",
|
||||
text: "拍照片",
|
||||
theme: "primary"
|
||||
}, {
|
||||
icon: "video-camera-1",
|
||||
emit: "capture-video",
|
||||
text: "录视频",
|
||||
theme: "primary"
|
||||
}, ...props.addActions]);
|
||||
|
||||
function handleFileAction(): void {
|
||||
capturePopoverVisible.value = false;
|
||||
if (props.uploadEnabled) {
|
||||
fileInput.value?.click();
|
||||
return;
|
||||
}
|
||||
emit("add");
|
||||
}
|
||||
|
||||
function handleCaptureAction(action: MediaSelectorAddAction): void {
|
||||
capturePopoverVisible.value = false;
|
||||
if (action.emit === "capture-photo") {
|
||||
if (props.uploadEnabled) {
|
||||
photoFileInput.value?.click();
|
||||
return;
|
||||
}
|
||||
emit("capture-photo");
|
||||
return;
|
||||
}
|
||||
if (action.emit === "capture-video") {
|
||||
if (props.uploadEnabled) {
|
||||
videoFileInput.value?.click();
|
||||
return;
|
||||
}
|
||||
emit("capture-video");
|
||||
return;
|
||||
}
|
||||
emit("action", action);
|
||||
}
|
||||
|
||||
function handleFileChange(event: Event): void {
|
||||
emit("file-change", event);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.add-trigger {
|
||||
--td-popover-padding: 0 .5rem;
|
||||
gap: .375rem;
|
||||
width: 5.5rem;
|
||||
height: 5.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
:deep(.t-popover__content) {
|
||||
border-radius: .875rem;
|
||||
}
|
||||
|
||||
.capture,
|
||||
.file {
|
||||
--td-button-border-radius: .875rem;
|
||||
|
||||
width: 5.5rem;
|
||||
height: 2.5625rem;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.add-actions {
|
||||
gap: .25rem;
|
||||
display: grid;
|
||||
padding: .5rem 0;
|
||||
|
||||
.add-action {
|
||||
--td-button-medium-height: 32px;
|
||||
--td-button-medium-padding-horizontal: 10px;
|
||||
|
||||
gap: .5rem;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
font-weight: unset;
|
||||
justify-content: start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.file-input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.capture,
|
||||
.file {
|
||||
background: rgba(37, 99, 235, .16);
|
||||
border-color: rgba(96, 165, 250, .28);
|
||||
|
||||
span {
|
||||
color: #93c5fd;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,137 @@
|
||||
<template>
|
||||
<div class="item">
|
||||
<t-button variant="text" class="preview-trigger" @click="emit('preview')">
|
||||
<div v-if="isVideoItem(item)" class="video-thumbnail">
|
||||
<t-image
|
||||
v-if="getMediaThumbnailURL(item)"
|
||||
class="image"
|
||||
:src="getMediaThumbnailURL(item)"
|
||||
:alt="getAttachTypeText(item.attachType)"
|
||||
fit="cover"
|
||||
/>
|
||||
<video
|
||||
v-else
|
||||
:src="getMediaPreviewURL(item)"
|
||||
muted
|
||||
playsinline
|
||||
preload="metadata"
|
||||
/>
|
||||
<t-icon class="play" name="play-circle-filled" size="2rem" />
|
||||
</div>
|
||||
<t-image
|
||||
v-else
|
||||
class="image"
|
||||
:src="item.url"
|
||||
:alt="getAttachTypeText(item.attachType)"
|
||||
fit="cover"
|
||||
/>
|
||||
</t-button>
|
||||
<div
|
||||
v-if="showTypeLabel"
|
||||
class="type-label white glass-black clip-text"
|
||||
v-text="getAttachTypeText(item.attachType)"
|
||||
/>
|
||||
<t-button
|
||||
v-if="showRemove && removable"
|
||||
theme="danger"
|
||||
class="remove"
|
||||
shape="circle"
|
||||
size="extra-small"
|
||||
@click="emit('remove')"
|
||||
>
|
||||
<t-icon name="close" size="1rem" />
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { PhotoItem } from "@/types/Photo.ts";
|
||||
import {
|
||||
getAttachTypeText,
|
||||
getMediaPreviewURL,
|
||||
getMediaThumbnailURL,
|
||||
isVideoItem
|
||||
} from "./utils";
|
||||
|
||||
interface Props {
|
||||
item: PhotoItem;
|
||||
removable: boolean;
|
||||
showRemove: boolean;
|
||||
showTypeLabel: boolean;
|
||||
}
|
||||
|
||||
defineProps<Props>();
|
||||
const emit = defineEmits<{
|
||||
preview: [];
|
||||
remove: [];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.item {
|
||||
width: 5.5rem;
|
||||
height: 5.5rem;
|
||||
flex: 0 0 5.5rem;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 1rem;
|
||||
|
||||
.preview-trigger {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
cursor: pointer;
|
||||
background: transparent;
|
||||
|
||||
.image {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.video-thumbnail {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
background: #0f172a;
|
||||
|
||||
video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.play {
|
||||
inset: 50% auto auto 50%;
|
||||
opacity: .7;
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.type-label {
|
||||
width: 100%;
|
||||
bottom: 0;
|
||||
padding: .125rem .5rem;
|
||||
position: absolute;
|
||||
overflow: hidden;
|
||||
font-size: .875rem;
|
||||
text-align: center;
|
||||
line-height: 1.2;
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.remove {
|
||||
top: .375rem;
|
||||
right: .375rem;
|
||||
position: absolute;
|
||||
|
||||
:deep(.t-button__content) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,237 @@
|
||||
<template>
|
||||
<teleport to="body">
|
||||
<t-image-viewer
|
||||
v-model:visible="viewerVisible"
|
||||
:images="images"
|
||||
:style="{ zIndex: props.viewerZIndex }"
|
||||
show-index
|
||||
@close="handleClose"
|
||||
@index-change="handleIndexChange"
|
||||
>
|
||||
<template #image="params">
|
||||
<div
|
||||
v-if="isVideoViewerItem(params.index)"
|
||||
:class="[params.className, 'viewer-video-wrap']"
|
||||
:style="params.style"
|
||||
@click.stop
|
||||
@pointerdown.stop
|
||||
@pointermove.stop
|
||||
@pointerup.stop
|
||||
@touchstart.stop
|
||||
@touchmove.stop
|
||||
@touchend.stop
|
||||
>
|
||||
<video
|
||||
:src="getViewerMediaURL(params.index)"
|
||||
class="viewer-video"
|
||||
controls
|
||||
playsinline
|
||||
preload="metadata"
|
||||
@loadedmetadata="handleViewerVideoLoaded($event, params)"
|
||||
@transitionstart="params.onTransitionstart"
|
||||
@transitionend="params.onTransitionend"
|
||||
/>
|
||||
</div>
|
||||
<img
|
||||
v-else
|
||||
:src="params.src"
|
||||
:class="params.className"
|
||||
:style="params.style"
|
||||
:alt="getViewerAlt(params.index)"
|
||||
@load="params.onLoad"
|
||||
@transitionstart="params.onTransitionstart"
|
||||
@transitionend="params.onTransitionend"
|
||||
/>
|
||||
</template>
|
||||
<template #delete-btn>
|
||||
<div v-if="showActions" class="viewer-action" @click.stop>
|
||||
<t-popover
|
||||
v-model:visible="photoActionVisible"
|
||||
placement="bottom"
|
||||
theme="light"
|
||||
:show-arrow="false"
|
||||
>
|
||||
<t-button class="white" variant="text">
|
||||
<t-icon name="ellipsis" />
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="actions" @click.stop>
|
||||
<div class="title">修改类型</div>
|
||||
<div class="type">
|
||||
<t-button
|
||||
v-for="item in attachTypeOptions"
|
||||
:key="item.value"
|
||||
:theme="item.value === currentPhotoItem?.attachType ? 'primary' : 'default'"
|
||||
variant="text"
|
||||
size="extra-small"
|
||||
:disabled="submitting"
|
||||
@click="changePhotoType(item.value)"
|
||||
>
|
||||
<span v-text="item.text" />
|
||||
</t-button>
|
||||
</div>
|
||||
<t-divider />
|
||||
<t-button
|
||||
class="button delete-action"
|
||||
theme="danger"
|
||||
size="extra-small"
|
||||
variant="text"
|
||||
:disabled="submitting"
|
||||
@click="removeCurrentPhoto"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="delete" />
|
||||
</template>
|
||||
删除
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-popover>
|
||||
</div>
|
||||
</template>
|
||||
</t-image-viewer>
|
||||
</teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { ImageSlotParams } from "tdesign-mobile-vue";
|
||||
import type { MediaSelectorViewerItem } from "./types";
|
||||
import { getAttachTypeText, getMediaPreviewURL, isVideoItem } from "./utils";
|
||||
|
||||
interface Props {
|
||||
images: string[];
|
||||
items: readonly MediaSelectorViewerItem[];
|
||||
showActions: boolean;
|
||||
submitting: boolean;
|
||||
visible: boolean;
|
||||
viewerZIndex?: number;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
const emit = defineEmits<{
|
||||
(event: "update:visible", value: boolean): void;
|
||||
(event: "change-type", sourceIndex: number, attachType: string): void;
|
||||
(event: "remove", sourceIndex: number): void;
|
||||
}>();
|
||||
|
||||
const viewerVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: value => emit("update:visible", value)
|
||||
});
|
||||
const viewerIndex = ref(0);
|
||||
const photoActionVisible = ref(false);
|
||||
const attachTypeOptions = [
|
||||
{ text: "照片", value: "PHOTO" },
|
||||
{ text: "积分卡", value: "POINT_CARD" },
|
||||
{ text: "其他文件", value: "OTHER" }
|
||||
] as const;
|
||||
const currentPhotoItem = computed(() => props.items[viewerIndex.value]);
|
||||
|
||||
watch(() => props.visible, value => {
|
||||
if (value) {
|
||||
viewerIndex.value = 0;
|
||||
photoActionVisible.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose(): void {
|
||||
photoActionVisible.value = false;
|
||||
emit("update:visible", false);
|
||||
}
|
||||
|
||||
function handleIndexChange(index: number): void {
|
||||
viewerIndex.value = index;
|
||||
photoActionVisible.value = false;
|
||||
}
|
||||
|
||||
function isVideoViewerItem(index?: number): boolean {
|
||||
const item = getViewerItem(index);
|
||||
return !!item && isVideoItem(item);
|
||||
}
|
||||
|
||||
function getViewerItem(index?: number): MediaSelectorViewerItem | undefined {
|
||||
return index === undefined ? undefined : props.items[index];
|
||||
}
|
||||
|
||||
function getViewerMediaURL(index?: number): string {
|
||||
const item = getViewerItem(index);
|
||||
return item ? getMediaPreviewURL(item) : "";
|
||||
}
|
||||
|
||||
function getViewerAlt(index?: number): string {
|
||||
return getAttachTypeText(getViewerItem(index)?.attachType);
|
||||
}
|
||||
|
||||
function handleViewerVideoLoaded(event: Event, params: ImageSlotParams): void {
|
||||
const video = event.currentTarget as HTMLVideoElement;
|
||||
if (video.videoHeight > 0) {
|
||||
video.height = video.videoHeight;
|
||||
}
|
||||
params.onLoad?.(event);
|
||||
}
|
||||
|
||||
function changePhotoType(attachType: string): void {
|
||||
const currentItem = currentPhotoItem.value;
|
||||
photoActionVisible.value = false;
|
||||
if (!currentItem || currentItem.attachType === attachType) {
|
||||
return;
|
||||
}
|
||||
emit("change-type", currentItem.sourceIndex, attachType);
|
||||
}
|
||||
|
||||
function removeCurrentPhoto(): void {
|
||||
const currentItem = currentPhotoItem.value;
|
||||
photoActionVisible.value = false;
|
||||
if (currentItem) {
|
||||
emit("remove", currentItem.sourceIndex);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.viewer-action {
|
||||
color: #fff;
|
||||
margin-left: -1rem;
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
min-width: 8rem;
|
||||
flex-direction: column;
|
||||
|
||||
.title {
|
||||
padding: 0 .75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.type {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
margin-left: 1.5rem;
|
||||
flex-direction: column;
|
||||
justify-content: start;
|
||||
}
|
||||
|
||||
.button {
|
||||
justify-content: start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.viewer-video-wrap {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.viewer-video {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-height: 100%;
|
||||
background: #0f172a;
|
||||
object-fit: contain;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { ButtonProps } from "tdesign-mobile-vue";
|
||||
import type { PhotoItem } from "@/types/Photo.ts";
|
||||
|
||||
export type MediaSelectorAddAction = {
|
||||
icon?: string;
|
||||
emit: string;
|
||||
text: string;
|
||||
theme?: ButtonProps["theme"];
|
||||
};
|
||||
|
||||
export type MediaSelectorViewerItem = PhotoItem & {
|
||||
sourceIndex: number;
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { PhotoItem } from "@/types/Photo.ts";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment.ts";
|
||||
|
||||
const ATTACH_TYPE_TEXT_MAP: Record<string, string> = {
|
||||
ADDITIONAL: "附加照片",
|
||||
PHOTO: "照片",
|
||||
POINT_CARD: "积分卡",
|
||||
OTHER: "其他文件"
|
||||
};
|
||||
|
||||
/** 缩略图宽度查询串,地址中出现即表示已带缩略图参数 */
|
||||
const THUMBNAIL_WIDTH_QUERY = "thumbWidth=";
|
||||
|
||||
/** 缩略图兜底尺寸(像素),用于地址未带缩略图参数但可定位附件的场景 */
|
||||
const FALLBACK_THUMBNAIL_SIZE = 128;
|
||||
|
||||
export function getAttachTypeText(attachType?: string): string {
|
||||
return ATTACH_TYPE_TEXT_MAP[attachType || "PHOTO"] || "其他文件";
|
||||
}
|
||||
|
||||
export function getMediaPreviewURL(item: PhotoItem): string {
|
||||
return item.previewUrl || item.url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析媒体缩略图地址。
|
||||
*
|
||||
* 后端读附件接口只要带缩略图参数,视频附件同样返回该视频的缩略帧,
|
||||
* 因此视频在列表中统一按图片渲染;临时上传文件没有缩略图,返回空字符串由调用方降级。
|
||||
*/
|
||||
export function getMediaThumbnailURL(item: PhotoItem): string {
|
||||
if (item.url.includes(THUMBNAIL_WIDTH_QUERY)) {
|
||||
return item.url;
|
||||
}
|
||||
|
||||
const attachmentId = item.attachment?.id;
|
||||
return attachmentId ? getAttachmentReadURL(attachmentId, FALLBACK_THUMBNAIL_SIZE) : "";
|
||||
}
|
||||
|
||||
export function isVideoItem(item: PhotoItem): boolean {
|
||||
const mimeType = (item.mimeType || item.attachment?.mimeType || "").toLowerCase();
|
||||
if (mimeType.startsWith("video/")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return /\.(avi|m4v|mkv|mov|mp4|mpeg|mpg|ogv|webm|wmv)(?:$|[?#])/i.test(item.url);
|
||||
}
|
||||
|
||||
export function normalizePhotoItem(item: PhotoItem): PhotoItem {
|
||||
return {
|
||||
...item,
|
||||
attachType: item.attachType || item.attachment?.attachType || "PHOTO",
|
||||
mimeType: item.mimeType || item.attachment?.mimeType
|
||||
};
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
import type { ObjectDirective } from "vue";
|
||||
|
||||
const ENTRANCE_DURATION = 400;
|
||||
const ACTIVE_CLASS = "entrance-fade-up-enter-active";
|
||||
const FROM_CLASS = "entrance-fade-up-enter-from";
|
||||
const TO_CLASS = "entrance-fade-up-enter-to";
|
||||
const STATE_KEY = Symbol("entrance-transition-state");
|
||||
|
||||
type EntranceTransitionValue = number | string | { delay?: number | string } | undefined;
|
||||
|
||||
interface EntranceTransitionState {
|
||||
frameId?: number;
|
||||
timerId?: number;
|
||||
delay: number;
|
||||
}
|
||||
|
||||
type EntranceTransitionElement = HTMLElement & {
|
||||
[STATE_KEY]?: EntranceTransitionState;
|
||||
};
|
||||
|
||||
function getDelay(value: EntranceTransitionValue): number {
|
||||
const rawDelay = typeof value === "object" && value !== null ? value.delay : value;
|
||||
const delay = Number(rawDelay ?? 0);
|
||||
return Number.isFinite(delay) ? Math.max(0, delay) : 0;
|
||||
}
|
||||
|
||||
function setDelay(element: EntranceTransitionElement, delay: number): void {
|
||||
element.style.setProperty("--entrance-delay", `${delay}ms`);
|
||||
}
|
||||
|
||||
function cleanup(element: EntranceTransitionElement): void {
|
||||
const state = element[STATE_KEY];
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.frameId !== undefined) {
|
||||
window.cancelAnimationFrame(state.frameId);
|
||||
}
|
||||
if (state.timerId !== undefined) {
|
||||
window.clearTimeout(state.timerId);
|
||||
}
|
||||
|
||||
element.classList.remove(ACTIVE_CLASS, FROM_CLASS, TO_CLASS);
|
||||
element.style.removeProperty("--entrance-delay");
|
||||
delete element[STATE_KEY];
|
||||
}
|
||||
|
||||
const vEntranceTransition: ObjectDirective<HTMLElement, EntranceTransitionValue> = {
|
||||
beforeMount(element, binding) {
|
||||
if (!(element instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = element as EntranceTransitionElement;
|
||||
const delay = getDelay(binding.value);
|
||||
target[STATE_KEY] = { delay };
|
||||
setDelay(target, delay);
|
||||
target.classList.add(ACTIVE_CLASS, FROM_CLASS);
|
||||
},
|
||||
|
||||
mounted(element) {
|
||||
if (!(element instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = element as EntranceTransitionElement;
|
||||
const state = target[STATE_KEY];
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.frameId = window.requestAnimationFrame(() => {
|
||||
state.frameId = window.requestAnimationFrame(() => {
|
||||
state.frameId = undefined;
|
||||
target.classList.remove(FROM_CLASS);
|
||||
target.classList.add(TO_CLASS);
|
||||
state.timerId = window.setTimeout(() => cleanup(target), ENTRANCE_DURATION + state.delay);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
updated(element, binding) {
|
||||
if (!(element instanceof HTMLElement) || binding.value === binding.oldValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = element as EntranceTransitionElement;
|
||||
const state = target[STATE_KEY];
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.delay = getDelay(binding.value);
|
||||
setDelay(target, state.delay);
|
||||
},
|
||||
|
||||
beforeUnmount(element) {
|
||||
if (element instanceof HTMLElement) {
|
||||
cleanup(element as EntranceTransitionElement);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default vEntranceTransition;
|
||||
@@ -2,7 +2,12 @@
|
||||
<div class="main-layout">
|
||||
<app-nav-bar @height-change="onChangeNavBarHeight" />
|
||||
<div class="router-view">
|
||||
<page-transition />
|
||||
<page-transition
|
||||
:keep-alive="shouldKeepAlive"
|
||||
:page-background="globalUIStore.bodyBackground"
|
||||
page-class="page"
|
||||
:respect-reduced-motion="false"
|
||||
/>
|
||||
</div>
|
||||
<t-tab-bar
|
||||
v-model="tabVal"
|
||||
@@ -33,16 +38,25 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import AppNavBar from "@/components/navbar/index.vue";
|
||||
import PageTransition from "@/components/PageTransition.vue";
|
||||
import { useGlobalUIStore } from "@/store/globalUI";
|
||||
import { useTabBarStore } from "@/store/tabBarStore";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import { PageTransition } from "timi-tdesign-mobile";
|
||||
import { useUserStore } from "timi-web-api/store";
|
||||
import type { RouteLocationNormalizedLoaded } from "vue-router";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const globalUIStore = useGlobalUIStore();
|
||||
const tabBarStore = useTabBarStore();
|
||||
const userStore = useUserStore();
|
||||
|
||||
const cachedRouteNames = new Set(["SalesOrderList", "ProductList", "ProductStockList"]);
|
||||
|
||||
function shouldKeepAlive(sourceRoute: RouteLocationNormalizedLoaded): boolean {
|
||||
return cachedRouteNames.has(String(sourceRoute.name));
|
||||
}
|
||||
|
||||
// ---------- 导航边距 ----------
|
||||
|
||||
const navBarHeight = ref("0px");
|
||||
@@ -183,6 +197,7 @@ const tabBarHeight = computed(() => {
|
||||
|
||||
.tab-bar {
|
||||
--td-tab-bar-height: 52px;
|
||||
--td-tab-bar-active-bg: var(--td-brand-color-2);
|
||||
|
||||
bottom: 1rem;
|
||||
opacity: 1;
|
||||
|
||||
+30
-8
@@ -4,20 +4,38 @@ import router from "@/router";
|
||||
import Root from "@/Root.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
|
||||
import { configureUserStore, useUserStore } from "timi-web-api/store";
|
||||
import Network from "timi-web-api/utils/Network";
|
||||
import { VCan, VRole } from "timi-web-api/utils/directives/Access";
|
||||
import type { ApiResponse } from "timi-web-api";
|
||||
import { Message } from "@/utils/message";
|
||||
import { initializeTwaBridge } from "@/utils/twaBridge";
|
||||
import { VEntranceTransition } from "timi-tdesign-mobile";
|
||||
import timiWebStyle from "../../timi-web/src/assets/style/timi-web.less?inline";
|
||||
import tdesignCustomStyle from "../../timi-tdesign-mobile/src/assets/style/tdesign-custom.less?inline";
|
||||
|
||||
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
|
||||
import "tdesign-mobile-vue/es/style/index.css";
|
||||
import "timi-web/style.css";
|
||||
import "timi-tdesign-mobile/style.css";
|
||||
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
|
||||
import "@/assets/styles/tdesign-custom.css";
|
||||
import "@/assets/styles/global.less";
|
||||
import TimiWebUI from "timi-web";
|
||||
import { configureUserStore, Network, useUserStore, VCan, VRole } from "timi-web-api";
|
||||
import type { ApiResponse } from "timi-web-api";
|
||||
import { Message } from "@/utils/message";
|
||||
import vEntranceTransition from "@/directives/entranceTransition";
|
||||
|
||||
export const pinia = createPinia();
|
||||
const apiBaseURL = import.meta.env.VITE_API_BASE_URL as string | undefined;
|
||||
const libraryOverrideStyleId = "library-override-style";
|
||||
|
||||
initializeTwaBridge();
|
||||
|
||||
function mountLibraryOverrideStyle(): void {
|
||||
const oldStyle = document.getElementById(libraryOverrideStyleId);
|
||||
oldStyle?.remove();
|
||||
|
||||
const style = document.createElement("style");
|
||||
style.id = libraryOverrideStyleId;
|
||||
style.textContent = `${timiWebStyle}\n${tdesignCustomStyle}`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
if (apiBaseURL) {
|
||||
Network.axios.defaults.baseURL = apiBaseURL;
|
||||
@@ -47,10 +65,9 @@ Network.setGlobalRequestInterceptor((config: any) => {
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = createApp(Root);
|
||||
app.use(pinia);
|
||||
app.use(TimiWebUI);
|
||||
app.directive("can", VCan);
|
||||
app.directive("role", VRole);
|
||||
app.directive("entrance-transition", vEntranceTransition);
|
||||
app.directive("entrance-transition", VEntranceTransition);
|
||||
|
||||
const userStore = useUserStore(pinia);
|
||||
const currentStoreStore = useCurrentStoreStore(pinia);
|
||||
@@ -64,6 +81,11 @@ async function bootstrap(): Promise<void> {
|
||||
});
|
||||
|
||||
app.use(router);
|
||||
await router.isReady();
|
||||
await import("tdesign-mobile-vue");
|
||||
await import("../../timi-web/src/index");
|
||||
await import("timi-tdesign-mobile");
|
||||
mountLibraryOverrideStyle();
|
||||
app.mount("#root");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<template>
|
||||
<div v-if="canUseAi" class="ai-chat-page">
|
||||
<ai-chat-panel
|
||||
:store-name="currentStoreStore.currentStoreName"
|
||||
:session-key="sessionKey"
|
||||
:store-id="aiStoreId"
|
||||
@new-conversation="startNewConversation"
|
||||
/>
|
||||
</div>
|
||||
<t-empty v-else description="当前账号无权使用门店智能助手" />
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { useUserStore } from "timi-web-api/store";
|
||||
import AiChatPanel from "@/pages/ai/components/AiChatPanel.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import { gaoRoleCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
name: "AiChatPage"
|
||||
});
|
||||
|
||||
const userStore = useUserStore();
|
||||
const currentStoreStore = useCurrentStoreStore();
|
||||
const conversationResetToken = ref(0);
|
||||
const sessionKey = computed(() => `${userStore.loginUser.user?.id || userStore.loginUser.id || ""}:${currentStoreStore.currentStoreId}:${conversationResetToken.value}`);
|
||||
const canUseAi = computed(() => userStore.hasRoles(gaoRoleCodes.storeManager));
|
||||
const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalManager));
|
||||
const aiStoreId = computed(() => canUseAi.value && isGlobalManager.value ? currentStoreStore.currentStoreId : undefined);
|
||||
|
||||
function startNewConversation(): void {
|
||||
conversationResetToken.value += 1;
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.ai-chat-page {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.ai-chat-page {
|
||||
background: #10161f;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,141 @@
|
||||
import { ref } from "vue";
|
||||
import { SettingAPI } from "timi-web-api";
|
||||
|
||||
const AI_QUICK_QUESTION_CACHE_KEY = "gao-customer-h5:ai-agent-example";
|
||||
const AI_QUICK_QUESTION_CACHE_TTL = 24 * 60 * 60 * 1000;
|
||||
const AI_QUICK_QUESTION_COUNT = 5;
|
||||
|
||||
interface AiQuickQuestionCache {
|
||||
cachedAt: number;
|
||||
questionList: string[];
|
||||
}
|
||||
|
||||
/** 从快捷问题题库中随机抽取指定数量的问题。 */
|
||||
export function getRandomAiQuickQuestions(count = AI_QUICK_QUESTION_COUNT, questionPool: readonly string[] = []): string[] {
|
||||
const result: string[] = [...questionPool];
|
||||
const targetCount = Math.min(Math.max(Math.floor(count), 0), result.length);
|
||||
|
||||
for (let index = 0; index < targetCount; index += 1) {
|
||||
const randomIndex = index + Math.floor(Math.random() * (result.length - index));
|
||||
[result[index], result[randomIndex]] = [result[randomIndex], result[index]];
|
||||
}
|
||||
|
||||
return result.slice(0, targetCount);
|
||||
}
|
||||
|
||||
/** 清理并去重快捷问题。 */
|
||||
function normalizeAiQuickQuestionList(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [...new Set(value.filter((item): item is string => typeof item === "string").map(item => item.trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
/** 将 Setting 中的题库值解析为有效的快捷问题列表。 */
|
||||
function parseAiQuickQuestionList(value: unknown): string[] {
|
||||
if (typeof value !== "string") {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeAiQuickQuestionList(JSON.parse(value));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取一天内有效的本地题库缓存。 */
|
||||
function readAiQuickQuestionCache(): string[] {
|
||||
try {
|
||||
const cacheValue = localStorage.getItem(AI_QUICK_QUESTION_CACHE_KEY);
|
||||
if (!cacheValue) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const cache: unknown = JSON.parse(cacheValue);
|
||||
if (typeof cache !== "object" || cache === null || !("cachedAt" in cache) || !("questionList" in cache)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const typedCache = cache as AiQuickQuestionCache;
|
||||
if (typeof typedCache.cachedAt !== "number" || !Number.isFinite(typedCache.cachedAt)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const cacheAge = Date.now() - typedCache.cachedAt;
|
||||
if (cacheAge < 0 || AI_QUICK_QUESTION_CACHE_TTL < cacheAge || !Array.isArray(typedCache.questionList)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return normalizeAiQuickQuestionList(typedCache.questionList);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** 将动态题库缓存到本地一天。 */
|
||||
function writeAiQuickQuestionCache(questionList: string[]): void {
|
||||
try {
|
||||
const cache: AiQuickQuestionCache = {
|
||||
cachedAt: Date.now(),
|
||||
questionList
|
||||
};
|
||||
localStorage.setItem(AI_QUICK_QUESTION_CACHE_KEY, JSON.stringify(cache));
|
||||
} catch {
|
||||
// 本地存储不可用时跳过缓存。
|
||||
}
|
||||
}
|
||||
|
||||
/** 从系统设置中获取动态快捷问题题库。 */
|
||||
async function fetchAiQuickQuestionPool(): Promise<string[]> {
|
||||
const settingMap = await SettingAPI.map("GAO_SYSTEM", undefined, ["AI_AGENT_EXAMPLE"]);
|
||||
return parseAiQuickQuestionList(settingMap.AI_AGENT_EXAMPLE?.value);
|
||||
}
|
||||
|
||||
let loadingPromise: Promise<void> | undefined;
|
||||
let currentAiQuickQuestionPool: string[] = [];
|
||||
|
||||
/** 从已加载的题库中重新抽取快捷问题。 */
|
||||
export function refreshAiQuickQuestions(): void {
|
||||
aiQuickQuestionList.value = getRandomAiQuickQuestions(AI_QUICK_QUESTION_COUNT, currentAiQuickQuestionPool);
|
||||
}
|
||||
|
||||
/** 加载动态题库并刷新当前会话展示的问题。 */
|
||||
export async function loadAiQuickQuestions(): Promise<void> {
|
||||
if (loadingPromise) {
|
||||
await loadingPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
loadingPromise = (async () => {
|
||||
const cachedQuestionList = readAiQuickQuestionCache();
|
||||
if (cachedQuestionList.length > 0) {
|
||||
currentAiQuickQuestionPool = cachedQuestionList;
|
||||
refreshAiQuickQuestions();
|
||||
return;
|
||||
}
|
||||
|
||||
currentAiQuickQuestionPool = [];
|
||||
aiQuickQuestionList.value = [];
|
||||
try {
|
||||
const questionList = await fetchAiQuickQuestionPool();
|
||||
if (questionList.length > 0) {
|
||||
currentAiQuickQuestionPool = questionList;
|
||||
writeAiQuickQuestionCache(questionList);
|
||||
refreshAiQuickQuestions();
|
||||
}
|
||||
} catch {
|
||||
// 接口异常时保持为空。
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
await loadingPromise;
|
||||
} finally {
|
||||
loadingPromise = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** 当前会话欢迎页展示的快捷问题。 */
|
||||
export const aiQuickQuestionList = ref<string[]>([]);
|
||||
@@ -0,0 +1,433 @@
|
||||
<template>
|
||||
<shared-ai-chat-panel
|
||||
ref="messageList"
|
||||
class="shared-panel"
|
||||
:messages="messages"
|
||||
:is-generating="isGenerating"
|
||||
:is-loading="isLoadingConversation"
|
||||
:active-tool-status="activeToolStatus"
|
||||
:last-error="lastError"
|
||||
:can-retry="canRetry"
|
||||
:aria-label="`${props.storeName || '当前会话'}经营助手`"
|
||||
:role-names="{ assistant: 'AI 小糕', user: '店长' }"
|
||||
:placeholder="'问问小糕怎么个事…'"
|
||||
:format-message-status="formatMessageStatus"
|
||||
@send="submitMessage"
|
||||
@stop="stopGeneration"
|
||||
@retry="retryLastMessage"
|
||||
@new-conversation="emit('new-conversation')"
|
||||
>
|
||||
<template #welcome>
|
||||
<div class="welcome">
|
||||
<div class="welcome-icon" v-entrance-transition>
|
||||
<t-icon name="robot-2" size="2rem" />
|
||||
</div>
|
||||
<h3 v-entrance-transition="70">今天想了解什么?</h3>
|
||||
<p v-entrance-transition="140">我会根据当前门店的实时业务数据回答经营问题。</p>
|
||||
<div class="quick-list" v-entrance-transition="210">
|
||||
<t-button
|
||||
class="quick-question bg-white"
|
||||
v-for="question in aiQuickQuestionList"
|
||||
:key="question"
|
||||
size="small"
|
||||
@click="submitMessage(question)"
|
||||
>
|
||||
<span v-text="question" />
|
||||
</t-button>
|
||||
</div>
|
||||
<t-button
|
||||
v-if="aiQuickQuestionList.length"
|
||||
class="refresh-button"
|
||||
variant="text"
|
||||
size="small"
|
||||
:disabled="isRefreshingQuestions"
|
||||
@click="refreshQuickQuestions"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="refresh" class="refresh-icon" :class="{ refreshing: isRefreshingQuestions }" />
|
||||
</template>
|
||||
<span>换一批</span>
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
<template #citation="{ citation }">
|
||||
<div class="citation">
|
||||
<span class="citation-label">数据来源</span>
|
||||
<span v-text="formatCitation(citation)" />
|
||||
<span v-if="citation.generatedAt" class="citation-time">
|
||||
<span v-text="`生成时间:${citation.generatedAt}`" />
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
</shared-ai-chat-panel>
|
||||
<ai-conversation-list
|
||||
v-model:visible="conversationVisible"
|
||||
:active-conversation-id="conversationId"
|
||||
:disabled="isBusy"
|
||||
:session-key="props.sessionKey"
|
||||
@select="selectConversation"
|
||||
@delete="handleConversationDelete"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
AiChatHttpError,
|
||||
AiChatPanel as SharedAiChatPanel,
|
||||
AiChatStreamError,
|
||||
parseAssistantResponse,
|
||||
useAiChat,
|
||||
type AiChatCitationFormatter,
|
||||
type AiChatMessage,
|
||||
type AiChatMessageStatusFormatter
|
||||
} from "timi-tdesign-mobile";
|
||||
import type { GaoAiConversation, GaoAiConversationMessage, GaoAiConversationReadResponse } from "@/api/GaoAiAPI";
|
||||
import {
|
||||
chat,
|
||||
readConversation as readConversationApi
|
||||
} from "@/api/GaoAiAPI";
|
||||
import AiConversationList from "@/pages/ai/components/AiConversationList.vue";
|
||||
import { aiQuickQuestionList, loadAiQuickQuestions, refreshAiQuickQuestions } from "@/pages/ai/aiChatQuestions";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { useUserStore } from "timi-web-api/store";
|
||||
|
||||
defineOptions({
|
||||
name: "AiChatPanel"
|
||||
});
|
||||
|
||||
interface Props {
|
||||
storeName: string;
|
||||
sessionKey: string;
|
||||
storeId?: string;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
const emit = defineEmits<{
|
||||
"new-conversation": [];
|
||||
}>();
|
||||
const userStore = useUserStore();
|
||||
const navBarStore = useNavBarStore();
|
||||
type MessageListExpose = {
|
||||
scrollToBottom: () => Promise<void>;
|
||||
};
|
||||
|
||||
const messageListRef = useTemplateRef<MessageListExpose>("messageList");
|
||||
const conversationVisible = ref(false);
|
||||
const isRefreshingQuestions = ref(false);
|
||||
const {
|
||||
messages,
|
||||
conversationId,
|
||||
isGenerating,
|
||||
isLoadingConversation,
|
||||
activeToolStatus,
|
||||
lastError,
|
||||
canRetry,
|
||||
sendMessage,
|
||||
loadConversation,
|
||||
stopGeneration,
|
||||
retryLastMessage,
|
||||
resetConversation
|
||||
} = useAiChat<GaoAiConversationReadResponse, { storeId?: string }>({
|
||||
sessionKey: () => props.sessionKey,
|
||||
context: () => ({ storeId: props.storeId }),
|
||||
request: async ({ message, conversationId: activeConversationId, context, signal }) => await chat({
|
||||
message,
|
||||
...(activeConversationId ? { conversationId: activeConversationId } : {}),
|
||||
...(context?.storeId ? { storeId: context.storeId } : {})
|
||||
}, userStore.token, signal),
|
||||
readConversation: async conversationIdValue => await readConversationHistory(conversationIdValue),
|
||||
mapConversationMessages,
|
||||
scrollToBottom,
|
||||
isConversationExpired,
|
||||
getErrorMessage: error => getAiErrorMessage(error)
|
||||
});
|
||||
const isBusy = computed(() => isGenerating.value || isLoadingConversation.value);
|
||||
const formatCitation: AiChatCitationFormatter = citation => [
|
||||
citation.dataDomain ? `数据域:${citation.dataDomain}` : "",
|
||||
citation.timeRange ? `统计范围:${citation.timeRange}` : "",
|
||||
citation.caliber ? `统计口径:${citation.caliber}` : "",
|
||||
citation.source ? `来源:${citation.source}` : ""
|
||||
].filter(Boolean).join(" · ");
|
||||
const formatMessageStatus: AiChatMessageStatusFormatter = message => {
|
||||
if (message.statusText) {
|
||||
return message.statusText;
|
||||
}
|
||||
const timeText = `生成时间:${new Date(message.createdAt).toLocaleString("zh-CN", { hour12: false })}`;
|
||||
if (message.duration !== undefined) {
|
||||
const durationText = message.duration < 1000
|
||||
? `${message.duration} 毫秒`
|
||||
: `${(message.duration / 1000).toFixed(1)} 秒`;
|
||||
return `${timeText} · 查询耗时:${durationText}`;
|
||||
}
|
||||
return timeText;
|
||||
};
|
||||
|
||||
async function submitMessage(message: string): Promise<void> {
|
||||
await sendMessage(message);
|
||||
}
|
||||
|
||||
function openConversationList(): void {
|
||||
if (!isBusy.value) {
|
||||
conversationVisible.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function selectConversation(conversation: GaoAiConversation): Promise<void> {
|
||||
if (isBusy.value || !conversation.id) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await loadConversation(conversation.id);
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "历史会话读取失败"));
|
||||
}
|
||||
}
|
||||
|
||||
function handleConversationDelete(deletedConversationId: string): void {
|
||||
if (deletedConversationId === conversationId.value) {
|
||||
resetConversation();
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshQuickQuestions(): Promise<void> {
|
||||
if (isRefreshingQuestions.value) {
|
||||
return;
|
||||
}
|
||||
isRefreshingQuestions.value = true;
|
||||
refreshAiQuickQuestions();
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 300));
|
||||
isRefreshingQuestions.value = false;
|
||||
}
|
||||
|
||||
async function scrollToBottom(): Promise<void> {
|
||||
await messageListRef.value?.scrollToBottom();
|
||||
}
|
||||
|
||||
async function readConversationHistory(id: string): Promise<GaoAiConversationReadResponse> {
|
||||
const messageList: GaoAiConversationMessage[] = [];
|
||||
let firstId: string | undefined;
|
||||
let result: GaoAiConversationReadResponse = {};
|
||||
|
||||
while (true) {
|
||||
result = await readConversationApi({
|
||||
conversationId: id,
|
||||
firstId,
|
||||
limit: 100
|
||||
});
|
||||
const currentList = Array.isArray(result.data) ? result.data : [];
|
||||
messageList.push(...currentList);
|
||||
if (result["has_more"] !== true || !currentList.length) {
|
||||
break;
|
||||
}
|
||||
const nextFirstId = currentList[0]?.id;
|
||||
if (!nextFirstId || nextFirstId === firstId) {
|
||||
break;
|
||||
}
|
||||
firstId = nextFirstId;
|
||||
}
|
||||
|
||||
return {
|
||||
...result,
|
||||
data: messageList
|
||||
};
|
||||
}
|
||||
|
||||
function mapConversationMessages(response: GaoAiConversationReadResponse): AiChatMessage[] {
|
||||
const sourceList = Array.isArray(response.data) ? response.data : [];
|
||||
return sourceList
|
||||
.map((item, index) => ({
|
||||
item,
|
||||
index,
|
||||
timestamp: getTimestamp(item["created_at"])
|
||||
}))
|
||||
.sort((left, right) => left.timestamp - right.timestamp || left.index - right.index)
|
||||
.flatMap(({ item, index }) => {
|
||||
const messageList: AiChatMessage[] = [];
|
||||
const createdAt = getTimestamp(item["created_at"]);
|
||||
const query = getRawString(item.query);
|
||||
const answer = getRawString(item.answer);
|
||||
if (query) {
|
||||
messageList.push(createHistoryMessage(index * 2 + 1, "user", query, createdAt));
|
||||
}
|
||||
if (answer || isFailedConversationMessage(item)) {
|
||||
const parsedAnswer = parseAssistantResponse(answer);
|
||||
messageList.push({
|
||||
...createHistoryMessage(index * 2 + 2, "assistant", parsedAnswer.answer, createdAt),
|
||||
thinkingList: parsedAnswer.thinkingList.map((content, index) => ({
|
||||
id: index + 1,
|
||||
content
|
||||
})),
|
||||
statusText: isFailedConversationMessage(item) ? "本次回答生成失败" : undefined
|
||||
});
|
||||
}
|
||||
return messageList;
|
||||
});
|
||||
}
|
||||
|
||||
function createHistoryMessage(
|
||||
id: number,
|
||||
role: AiChatMessage["role"],
|
||||
content: string,
|
||||
createdAt: number
|
||||
): AiChatMessage {
|
||||
return {
|
||||
id,
|
||||
role,
|
||||
content,
|
||||
thinkingList: [],
|
||||
citationList: [],
|
||||
createdAt
|
||||
};
|
||||
}
|
||||
|
||||
function isConversationExpired(error: unknown): boolean {
|
||||
if (error instanceof AiChatHttpError || error instanceof AiChatStreamError) {
|
||||
return error.message.includes("AI 会话不存在或已过期")
|
||||
|| error.code?.toLowerCase().includes("session") === true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getAiErrorMessage(error: unknown): string {
|
||||
if (error instanceof AiChatHttpError) {
|
||||
if (error.status === 401) {
|
||||
return error.message.includes("会话") ? error.message : "登录已过期,请重新登录";
|
||||
}
|
||||
if (error.status === 403) {
|
||||
return "当前账号无权使用门店智能助手";
|
||||
}
|
||||
if (error.status === 429) {
|
||||
return "请求过于频繁,请稍后再试";
|
||||
}
|
||||
return error.message;
|
||||
}
|
||||
if (error instanceof AiChatStreamError) {
|
||||
if (error.code === "DIFY_TIMEOUT") {
|
||||
return "数据查询超时,请缩小时间范围后重试";
|
||||
}
|
||||
return error.message;
|
||||
}
|
||||
return getErrorMessage(error, "智能助手暂时不可用,请稍后重试");
|
||||
}
|
||||
|
||||
function getTimestamp(value: number | string | undefined): number {
|
||||
const timestamp = typeof value === "number" ? value : Number(value);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) {
|
||||
return Date.now();
|
||||
}
|
||||
return timestamp < 100000000000 ? timestamp * 1000 : timestamp;
|
||||
}
|
||||
|
||||
function getRawString(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function isFailedConversationMessage(message: GaoAiConversationMessage): boolean {
|
||||
const status = typeof message.status === "string" ? message.status.toLowerCase() : "";
|
||||
return status === "error" || status === "failed" || status === "failure";
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.clearRight();
|
||||
navBarStore.setRightText("历史", "var(--td-brand-color)", openConversationList);
|
||||
await loadAiQuickQuestions();
|
||||
});
|
||||
|
||||
watch(isBusy, value => navBarStore.setRightDisabled(value));
|
||||
|
||||
onUnmounted(() => navBarStore.clearRight());
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.shared-panel {
|
||||
--ai-msg-padding-top: calc(var(--app-nav-height) + 1rem);
|
||||
|
||||
:deep(.welcome) {
|
||||
margin: auto 0;
|
||||
text-align: center;
|
||||
|
||||
.welcome-icon {
|
||||
color: #0f766e;
|
||||
width: 4rem;
|
||||
height: 4rem;
|
||||
margin: 0 auto 1rem;
|
||||
border-radius: 1.25rem;
|
||||
display: flex;
|
||||
background: #ccfbf1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
p {
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: .5rem auto 1rem;
|
||||
font-size: .8125rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.quick-list {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
|
||||
.quick-question {
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
|
||||
:deep(.t-button__content) {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.refresh-button {
|
||||
margin-top: .75rem;
|
||||
|
||||
.refresh-icon.refreshing {
|
||||
animation: refresh-once .3s var(--td-animation-easing-standard);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.citation) {
|
||||
color: var(--td-text-color-secondary);
|
||||
display: flex;
|
||||
font-size: .6875rem;
|
||||
line-height: 1.4;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
:deep(.citation-label) {
|
||||
color: #0f766e;
|
||||
margin-right: .25rem;
|
||||
}
|
||||
|
||||
:deep(.citation-time) {
|
||||
width: 100%;
|
||||
margin-top: .125rem;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes refresh-once {
|
||||
from {
|
||||
transform: rotate(0);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,362 @@
|
||||
<template>
|
||||
<t-popup
|
||||
v-model="popupVisible"
|
||||
placement="right"
|
||||
destroy-on-close
|
||||
:z-index="popupZIndex"
|
||||
:overlay-props="{ zIndex: popupZIndex - 1 }"
|
||||
>
|
||||
<section class="ai-conversation-list" @scroll="handleScroll">
|
||||
<header class="header glass-header">
|
||||
<h3>历史会话</h3>
|
||||
<t-button
|
||||
theme="danger"
|
||||
shape="circle"
|
||||
variant="text"
|
||||
@click="popupVisible = false"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="close" />
|
||||
</template>
|
||||
</t-button>
|
||||
</header>
|
||||
<t-cell-group v-if="conversationList.length" class="items fix-last-cell-line">
|
||||
<t-swipe-cell
|
||||
v-for="(item, index) in conversationList"
|
||||
:key="item.id"
|
||||
class="item"
|
||||
v-entrance-transition="index * 30"
|
||||
>
|
||||
<t-cell
|
||||
class="cell"
|
||||
:class="{ active: item.id === props.activeConversationId }"
|
||||
:disabled="props.disabled"
|
||||
@click="selectConversation(item)"
|
||||
>
|
||||
<template #leftIcon>
|
||||
<div class="icon">
|
||||
<t-icon name="chat" size="1.25rem" />
|
||||
</div>
|
||||
</template>
|
||||
<template #title>
|
||||
<span class="title" v-text="getConversationName(item)" />
|
||||
</template>
|
||||
<template #description>
|
||||
<pass-time-label :timestamp="formatConversationTime(item)" underline />
|
||||
</template>
|
||||
</t-cell>
|
||||
<template #right>
|
||||
<t-button
|
||||
class="swipe-cell-button"
|
||||
theme="danger"
|
||||
:loading="deletingId === item.id"
|
||||
:disabled="props.disabled"
|
||||
@click.stop="confirmDelete(item)"
|
||||
>
|
||||
删除
|
||||
</t-button>
|
||||
</template>
|
||||
</t-swipe-cell>
|
||||
</t-cell-group>
|
||||
<t-empty v-else-if="!isLoading" class="center-tips" description="暂无历史会话" />
|
||||
<t-loading
|
||||
v-if="isLoading && !conversationList.length"
|
||||
class="center-tips"
|
||||
size="1.5rem"
|
||||
text="正在加载会话"
|
||||
/>
|
||||
<div class="footer glass-bottom">
|
||||
<span class="llm gray">Deepseek v4.1-flash</span>
|
||||
<t-button
|
||||
class="agreement-button"
|
||||
variant="text"
|
||||
size="small"
|
||||
type="button"
|
||||
content="服务协议"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { DialogPlugin } from "tdesign-mobile-vue";
|
||||
import { deleteConversation as removeConversation, type GaoAiConversation, listConversations } from "@/api/GaoAiAPI";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { PassTimeLabel } from "timi-web";
|
||||
|
||||
defineOptions({
|
||||
name: "AiConversationList"
|
||||
});
|
||||
|
||||
interface Props {
|
||||
visible: boolean;
|
||||
activeConversationId: string;
|
||||
disabled: boolean;
|
||||
sessionKey: string;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
const emit = defineEmits<{
|
||||
"update:visible": [value: boolean];
|
||||
select: [conversation: GaoAiConversation];
|
||||
delete: [conversationId: string];
|
||||
}>();
|
||||
|
||||
const popupZIndex = 4000;
|
||||
const deleteDialogZIndex = 12000;
|
||||
const pageSize = 20;
|
||||
const popupVisible = computed({
|
||||
get() {
|
||||
return props.visible;
|
||||
},
|
||||
set(value: boolean) {
|
||||
emit("update:visible", value);
|
||||
}
|
||||
});
|
||||
const conversationList = ref<GaoAiConversation[]>([]);
|
||||
const isLoading = ref(false);
|
||||
const isNoMore = ref(false);
|
||||
const lastId = ref("");
|
||||
const deletingId = ref("");
|
||||
let requestToken = 0;
|
||||
let loadingPromise: Promise<void> | undefined;
|
||||
|
||||
async function loadMore(): Promise<void> {
|
||||
if (loadingPromise) {
|
||||
await loadingPromise;
|
||||
return;
|
||||
}
|
||||
if (isNoMore.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentToken = requestToken;
|
||||
const request = (async () => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const result = await listConversations({
|
||||
lastId: lastId.value || undefined,
|
||||
limit: pageSize,
|
||||
sortBy: "-updated_at"
|
||||
});
|
||||
if (currentToken !== requestToken) {
|
||||
return;
|
||||
}
|
||||
const nextList = (result.data || []).filter(item => item.id);
|
||||
const idSet = new Set(conversationList.value.map(item => item.id));
|
||||
conversationList.value = conversationList.value.concat(nextList.filter(item => !idSet.has(item.id)));
|
||||
lastId.value = nextList[nextList.length - 1]?.id || lastId.value;
|
||||
isNoMore.value = result["has_more"] !== true || !nextList.length;
|
||||
} catch (error) {
|
||||
if (currentToken === requestToken) {
|
||||
Message.error(getErrorMessage(error, "历史会话加载失败"));
|
||||
}
|
||||
} finally {
|
||||
if (currentToken === requestToken) {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
})();
|
||||
loadingPromise = request;
|
||||
try {
|
||||
await request;
|
||||
} finally {
|
||||
if (loadingPromise === request) {
|
||||
loadingPromise = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadList(): Promise<void> {
|
||||
const currentToken = requestToken + 1;
|
||||
requestToken = currentToken;
|
||||
conversationList.value = [];
|
||||
lastId.value = "";
|
||||
isNoMore.value = false;
|
||||
if (loadingPromise) {
|
||||
await loadingPromise;
|
||||
}
|
||||
if (currentToken === requestToken) {
|
||||
await loadMore();
|
||||
}
|
||||
}
|
||||
|
||||
async function handleScroll(event: Event): Promise<void> {
|
||||
const target = event.currentTarget;
|
||||
if (!(target instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
if (target.scrollHeight - target.scrollTop - target.clientHeight < 40) {
|
||||
await loadMore();
|
||||
}
|
||||
}
|
||||
|
||||
function selectConversation(conversation: GaoAiConversation): void {
|
||||
if (props.disabled || !conversation.id) {
|
||||
return;
|
||||
}
|
||||
emit("select", conversation);
|
||||
emit("update:visible", false);
|
||||
}
|
||||
|
||||
async function confirmDelete(conversation: GaoAiConversation): Promise<void> {
|
||||
if (props.disabled || deletingId.value || !conversation.id) {
|
||||
return;
|
||||
}
|
||||
const conversationId = conversation.id;
|
||||
const dialog = DialogPlugin.confirm({
|
||||
title: "删除历史会话",
|
||||
content: "确定删除这段历史会话吗?删除后无法恢复。",
|
||||
cancelBtn: "取消",
|
||||
confirmBtn: "删除",
|
||||
zIndex: deleteDialogZIndex,
|
||||
overlayProps: { zIndex: deleteDialogZIndex },
|
||||
onCancel() {
|
||||
dialog.destroy();
|
||||
},
|
||||
async onConfirm() {
|
||||
dialog.destroy();
|
||||
await deleteItem(conversationId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteItem(conversationId: string): Promise<void> {
|
||||
deletingId.value = conversationId;
|
||||
try {
|
||||
await removeConversation(conversationId);
|
||||
emit("delete", conversationId);
|
||||
await reloadList();
|
||||
Message.success("历史会话已删除");
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "历史会话删除失败"));
|
||||
} finally {
|
||||
deletingId.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
function getConversationName(conversation: GaoAiConversation): string {
|
||||
return conversation.name?.trim() || conversation.introduction?.trim() || "未命名会话";
|
||||
}
|
||||
|
||||
function formatConversationTime(conversation: GaoAiConversation): number {
|
||||
const value = conversation["updated_at"] || conversation["created_at"];
|
||||
const timestamp = typeof value === "number" ? value : Number(value);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) {
|
||||
return -1;
|
||||
}
|
||||
return timestamp < 100000000000 ? timestamp * 1000 : timestamp;
|
||||
}
|
||||
|
||||
watch(() => props.visible, async visible => {
|
||||
if (visible) {
|
||||
await reloadList();
|
||||
}
|
||||
});
|
||||
|
||||
watch(() => props.sessionKey, async () => {
|
||||
requestToken += 1;
|
||||
conversationList.value = [];
|
||||
lastId.value = "";
|
||||
isNoMore.value = false;
|
||||
if (props.visible) {
|
||||
await reloadList();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.ai-conversation-list {
|
||||
width: min(70vw, 24rem);
|
||||
height: 100vh;
|
||||
padding: calc(var(--app-nav-height) + .5rem) 0 calc(1rem + env(safe-area-inset-bottom, 0px));
|
||||
display: flex;
|
||||
overflow: auto;
|
||||
position: relative;
|
||||
flex-direction: column;
|
||||
|
||||
.header {
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
position: sticky;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
h3 {
|
||||
margin: .5rem 0 .5rem 1rem;
|
||||
}
|
||||
|
||||
.t-button {
|
||||
gap: .25rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.items {
|
||||
flex: 1;
|
||||
|
||||
.item {
|
||||
|
||||
.cell {
|
||||
&.active {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
:deep(.t-cell__title) {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: #0f766e;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border-radius: .625rem;
|
||||
display: flex;
|
||||
background: #ccfbf1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.title {
|
||||
overflow: hidden;
|
||||
display: block;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
.delete {
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.footer {
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
padding: 0 .5rem;
|
||||
position: sticky;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
.llm {
|
||||
font-size: .875rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.conversation-drawer {
|
||||
background: #0f172a;
|
||||
|
||||
.icon {
|
||||
color: #5eead4;
|
||||
background: rgba(20, 184, 166, .15);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.stat.read" class="customer-data-charts-page">
|
||||
<div class="header bg-white">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="customerCode"
|
||||
class="customer-search"
|
||||
@@ -272,12 +272,11 @@ function getDateEnd(date: Date): Date {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.header {
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
z-index: 10;
|
||||
padding: .5rem 1rem;
|
||||
position: sticky;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
|
||||
.customer-search {
|
||||
--td-button-border-radius: .875rem;
|
||||
@@ -285,7 +284,6 @@ function getDateEnd(date: Date): Date {
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
background: var(--td-bg-color-container);
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
@@ -34,14 +34,15 @@
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<card-container v-entrance-transition="140">
|
||||
<photo-scroller
|
||||
class="photo-scroller"
|
||||
<media-selector
|
||||
class="media-selector"
|
||||
:model-value="photoList"
|
||||
:photo-items="photoItemList"
|
||||
:show-viewer-actions="canUpdateCustomer"
|
||||
:show-add="false"
|
||||
:show-remove="false"
|
||||
:submit="submitPhotoItems"
|
||||
show-type-label
|
||||
title="照片列表"
|
||||
/>
|
||||
</card-container>
|
||||
@@ -98,6 +99,9 @@
|
||||
<t-cell-group theme="card">
|
||||
<t-cell title="邀请客户" :note="inviteeCountText" arrow @click="toInviteeList" />
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="canReadFollowUpReminder" title="客户跟进" theme="card">
|
||||
<t-cell title="跟进提醒" note="查看客户提醒" arrow @click="toFollowUpReminderList" />
|
||||
</t-cell-group>
|
||||
<t-button
|
||||
v-can="permissionCodes.customer.delete"
|
||||
class="delete-action"
|
||||
@@ -142,7 +146,7 @@ import TagAPI from "@/api/TagAPI";
|
||||
import BodyAreaSelector from "@/components/BodyAreaSelector.vue";
|
||||
import CustomerRemoveDialog from "@/pages/customer/component/CustomerRemoveDialog.vue";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import TagSelector from "@/components/TagSelector.vue";
|
||||
import CustomerTagCard from "@/pages/customer/component/CustomerTagCard.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
@@ -177,6 +181,7 @@ const canReadSalesOrder = computed(() => userStore.hasPermissions(permissionCode
|
||||
const canReadTag = computed(() => userStore.hasPermissions(corePermissionCodes.tag.read));
|
||||
const canApplyTag = computed(() => userStore.hasPermissions(corePermissionCodes.tag.apply));
|
||||
const canUpdateCustomer = computed(() => userStore.hasPermissions(permissionCodes.customer.update));
|
||||
const canReadFollowUpReminder = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.read));
|
||||
|
||||
// ---------- 资料 ----------
|
||||
|
||||
@@ -389,6 +394,16 @@ async function toInviteeList(): Promise<void> {
|
||||
await router.push(`/management/customers/${customer.value.id}/invitees`);
|
||||
}
|
||||
|
||||
async function toFollowUpReminderList(): Promise<void> {
|
||||
if (!customer.value?.id || !canReadFollowUpReminder.value) {
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "CustomerFollowUpReminderList",
|
||||
query: { customerId: customer.value.id }
|
||||
});
|
||||
}
|
||||
|
||||
async function toEventRecordList(): Promise<void> {
|
||||
if (!canReadEventRecord.value || !customer.value?.id) {
|
||||
return;
|
||||
@@ -531,7 +546,7 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.photo-scroller) {
|
||||
:deep(.media-selector) {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<div class="photo">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
v-model="photoList"
|
||||
v-model:photo-items="photoItemList"
|
||||
:edit-mode="true"
|
||||
@@ -80,9 +80,11 @@
|
||||
:show-viewer-actions="!isCustomerBound"
|
||||
:add-actions="photoAddActions"
|
||||
:loading="isPhotoUploading"
|
||||
@add-photo="openPhotoPicker('PHOTO')"
|
||||
@add-point-card="openPhotoPicker('POINT_CARD')"
|
||||
@add-other="openPhotoPicker('OTHER')"
|
||||
show-type-label
|
||||
@add="openPhotoPicker('OTHER')"
|
||||
@action="handlePhotoAction"
|
||||
@capture-photo="capturePhoto"
|
||||
@capture-video="captureVideo"
|
||||
/>
|
||||
<div class="tips orange" v-if="!hasCustomerDeletePermission">当前账户权限编辑客户需要上传照片和积分卡</div>
|
||||
</div>
|
||||
@@ -98,7 +100,6 @@
|
||||
<t-input v-model.trim="formData.telephone" type="tel" placeholder="手机号" borderless :disabled="isCustomerBound" />
|
||||
</t-form-item>
|
||||
<t-form-item label="介绍人">
|
||||
<div class="referrer">
|
||||
<div class="selector">
|
||||
<t-input
|
||||
:value="formData.introducerCustomer?.name"
|
||||
@@ -108,6 +109,14 @@
|
||||
:disabled="isCustomerBound"
|
||||
/>
|
||||
<div class="actions">
|
||||
<t-button
|
||||
v-if="introducerCustomerId"
|
||||
variant="text"
|
||||
theme="danger"
|
||||
size="extra-small"
|
||||
:disabled="isCustomerBound"
|
||||
@click="clearIntroducer"
|
||||
>清除</t-button>
|
||||
<t-button
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
@@ -117,12 +126,12 @@
|
||||
>选择客户</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="formData.introducerCustomer" label-width="0">
|
||||
<customer-profile-card
|
||||
v-if="formData.introducerCustomer"
|
||||
class="profile"
|
||||
class="introducer-profile"
|
||||
:customer="formData.introducerCustomer"
|
||||
/>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="调理部位" :arrow="!isCustomerBound" @click="openBodyAreaPicker">
|
||||
<div class="picker-text" v-text="selectedAreaText" />
|
||||
@@ -169,7 +178,23 @@
|
||||
ref="photoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="*/*"
|
||||
@change="handlePhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="photoCameraInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
@change="handlePhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="videoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="video/*"
|
||||
capture="environment"
|
||||
@change="handlePhotoSelected"
|
||||
>
|
||||
<customer-selector
|
||||
@@ -206,7 +231,8 @@ import BodyAreaSelector from "@/components/BodyAreaSelector.vue";
|
||||
import CodeScanner from "@/components/CodeScanner.vue";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import type { MediaSelectorAddAction } from "@/components/mediaSelector/types";
|
||||
import TagSelector from "@/components/TagSelector.vue";
|
||||
import CustomerTagCard from "@/pages/customer/component/CustomerTagCard.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
@@ -219,6 +245,7 @@ import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { normalizeBodyAreaValue } from "@/utils/customer";
|
||||
import { corePermissionCodes, gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
import { compressUploadImage } from "@/utils/imageCompression";
|
||||
import { saveCapturedFilesFromInput } from "@/utils/twaBridge";
|
||||
|
||||
defineOptions({
|
||||
name: "CustomerEdit"
|
||||
@@ -332,6 +359,15 @@ async function handleIntroducerChange(id: string): Promise<void> {
|
||||
formData.introducerCustomer = customer;
|
||||
}
|
||||
|
||||
function clearIntroducer(): void {
|
||||
if (isCustomerBound.value) {
|
||||
return;
|
||||
}
|
||||
introducerCustomerId.value = "";
|
||||
formData.introducerCustomerId = "";
|
||||
formData.introducerCustomer = undefined;
|
||||
}
|
||||
|
||||
// ---------- 表单 ----------
|
||||
|
||||
const formData = reactive<Customer>({
|
||||
@@ -426,6 +462,40 @@ function openPhotoPicker(target: CustomerAttachmentType): void {
|
||||
photoInputRef.value?.click();
|
||||
}
|
||||
|
||||
function capturePhoto(): void {
|
||||
if (isCustomerBound.value) {
|
||||
return;
|
||||
}
|
||||
photoPickerTarget.value = "PHOTO";
|
||||
photoCameraInputRef.value?.click();
|
||||
}
|
||||
|
||||
function capturePointCard(): void {
|
||||
if (isCustomerBound.value) {
|
||||
return;
|
||||
}
|
||||
photoPickerTarget.value = "POINT_CARD";
|
||||
photoCameraInputRef.value?.click();
|
||||
}
|
||||
|
||||
function captureVideo(): void {
|
||||
if (isCustomerBound.value) {
|
||||
return;
|
||||
}
|
||||
photoPickerTarget.value = "OTHER";
|
||||
videoInputRef.value?.click();
|
||||
}
|
||||
|
||||
function handlePhotoAction(action: MediaSelectorAddAction): void {
|
||||
if (action.emit === "add-point-card") {
|
||||
capturePointCard();
|
||||
return;
|
||||
}
|
||||
if (action.emit === "add-other") {
|
||||
openPhotoPicker("OTHER");
|
||||
}
|
||||
}
|
||||
|
||||
watch(isCustomerBound, (value) => {
|
||||
navBarStore.setRightDisabled(value);
|
||||
if (!value) {
|
||||
@@ -469,6 +539,7 @@ async function loadDetail() {
|
||||
.map(item => ({
|
||||
attachment: item,
|
||||
attachType: normalizeAttachmentType(item.attachType),
|
||||
mimeType: item.mimeType,
|
||||
previewUrl: getAttachmentReadURL(item.id || ""),
|
||||
url: getAttachmentReadURL(item.id || "", 90)
|
||||
}));
|
||||
@@ -515,24 +586,14 @@ watch(() => formData.birthdate, (value) => {
|
||||
// ---------- 照片 ----------
|
||||
|
||||
const photoInputRef = ref<HTMLInputElement>();
|
||||
const photoCameraInputRef = ref<HTMLInputElement>();
|
||||
const videoInputRef = ref<HTMLInputElement>();
|
||||
const photoAddActions = [
|
||||
{
|
||||
icon: "user-avatar",
|
||||
text: "拍照片",
|
||||
emit: "add-photo",
|
||||
theme: "primary"
|
||||
},
|
||||
{
|
||||
icon: "cardmembership",
|
||||
text: "拍积分卡",
|
||||
emit: "add-point-card",
|
||||
theme: "primary"
|
||||
},
|
||||
{
|
||||
icon: "file-attachment",
|
||||
text: "其他文件",
|
||||
emit: "add-other",
|
||||
theme: "default"
|
||||
}
|
||||
] as const;
|
||||
const photoPickerTarget = ref<CustomerAttachmentType>("PHOTO");
|
||||
@@ -579,6 +640,7 @@ async function handlePhotoSelected(event: Event): Promise<void> {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
saveCapturedFilesFromInput(input, [file]);
|
||||
isPhotoUploading.value = true;
|
||||
try {
|
||||
const compressedFile = await compressUploadImage(file);
|
||||
@@ -586,6 +648,7 @@ async function handlePhotoSelected(event: Event): Promise<void> {
|
||||
if (tempFile?.id) {
|
||||
photoItemList.value.push({
|
||||
attachType: photoPickerTarget.value,
|
||||
mimeType: file.type,
|
||||
tempFileId: tempFile.id,
|
||||
url: AttachmentAPI.getTempReadURL(tempFile.id)
|
||||
});
|
||||
@@ -743,15 +806,9 @@ function buildAttachmentList(): Attachment[] {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.referrer {
|
||||
gap: .75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.selector {
|
||||
gap: .75rem;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.actions {
|
||||
gap: .5rem;
|
||||
@@ -760,6 +817,10 @@ function buildAttachmentList(): Attachment[] {
|
||||
}
|
||||
}
|
||||
|
||||
.introducer-profile {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sex {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
<template>
|
||||
<div
|
||||
v-can="permissionCodes.customer.read"
|
||||
class="customer-invite-rank"
|
||||
>
|
||||
<div v-can="permissionCodes.customer.read" class="customer-invite-rank">
|
||||
<t-pull-down-refresh
|
||||
class="list-wrapper"
|
||||
v-model="isRefreshing"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.customer.read" class="customer-list">
|
||||
<div class="filter bg-white">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="search"
|
||||
@@ -21,19 +21,19 @@
|
||||
</t-button>
|
||||
</template>
|
||||
</t-input>
|
||||
<t-button
|
||||
<t-dropdown-menu ref="filterMenu" class="menus">
|
||||
<t-dropdown-item
|
||||
v-model="dateFilterType"
|
||||
:label="dateFilterLabel"
|
||||
:options="dateOptions"
|
||||
@change="selectDateFilter"
|
||||
/>
|
||||
<t-dropdown-item
|
||||
v-if="canReadTag"
|
||||
class="tag-filter"
|
||||
size="small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
@click="tagSelectorVisible = true"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="tag" />
|
||||
</template>
|
||||
<span v-text="tagFilterText" />
|
||||
</t-button>
|
||||
:label="tagFilterText"
|
||||
@open="handleTagFilterOpen"
|
||||
/>
|
||||
</t-dropdown-menu>
|
||||
</div>
|
||||
<div v-if="scannerVisible" class="scanner-wrapper">
|
||||
<code-scanner
|
||||
@@ -55,12 +55,32 @@
|
||||
<t-button size="extra-small" variant="text" @click="clearTagFilter">清空</t-button>
|
||||
</div>
|
||||
<t-pull-down-refresh
|
||||
class="list-wrapper fix-last-cell-line"
|
||||
class="fix-last-cell-line"
|
||||
v-model="isRefreshing"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="refresh"
|
||||
@scrolltolower="fetch"
|
||||
>
|
||||
<div class="list-wrap">
|
||||
<t-cell-group class="summary" theme="card">
|
||||
<t-cell
|
||||
v-if="dateFilterType !== 'all'"
|
||||
title="开始时间"
|
||||
:note="dateRange[0] || '-'"
|
||||
arrow
|
||||
@click="openStartTime"
|
||||
/>
|
||||
<t-cell
|
||||
v-if="dateFilterType !== 'all'"
|
||||
title="结束时间"
|
||||
:note="dateRange[1] || '-'"
|
||||
arrow
|
||||
@click="openEndTime"
|
||||
/>
|
||||
<t-cell v-if="keyword" title="关键词" :note="keyword" />
|
||||
<t-cell v-if="selectedTagList.length" title="标签" :note="tagFilterText" />
|
||||
<t-cell title="数据量" :note="`共 ${pageResult.total} 位客户`" />
|
||||
</t-cell-group>
|
||||
<t-cell-group class="items" theme="card">
|
||||
<t-swipe-cell
|
||||
v-entrance-transition="index * 30"
|
||||
@@ -92,6 +112,7 @@
|
||||
</t-cell-group>
|
||||
<div v-if="!pageResult.list.length" class="center-tips" v-text="isLoading ? '正在加载客户' : '暂无客户数据'" />
|
||||
<div v-if="pageResult.list.length" class="center-tips" v-text="isLoading ? '正在加载更多' : isNoMore ? '已经到底了' : '上拉加载更多'" />
|
||||
</div>
|
||||
</t-pull-down-refresh>
|
||||
<tag-selector
|
||||
v-model="selectedTagIdList"
|
||||
@@ -106,9 +127,34 @@
|
||||
/>
|
||||
</div>
|
||||
<nav-bar-action-menu v-if="canShowActionMenu" :actions="actionList" />
|
||||
<t-popup v-model="startVisible" placement="bottom">
|
||||
<t-date-time-picker
|
||||
v-if="startVisible"
|
||||
v-model="startDraft"
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
:mode="['date', 'minute']"
|
||||
title="开始时间"
|
||||
:default-value="startDraft"
|
||||
@cancel="cancelStartTime"
|
||||
@confirm="confirmStartTime"
|
||||
/>
|
||||
</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="结束时间"
|
||||
:default-value="endDraft"
|
||||
@cancel="cancelEndTime"
|
||||
@confirm="confirmEndTime"
|
||||
/>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { DropdownValue } from "tdesign-mobile-vue";
|
||||
import { Message } from "@/utils/message";
|
||||
import { Time, Toolkit, WebToolkit } from "timi-web";
|
||||
import { type Page, type PageResult, useUserStore } from "timi-web-api";
|
||||
@@ -122,12 +168,15 @@ import { useSettingStore } from "@/store/settingStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { NavBarAction } from "@/types/NavBarAction";
|
||||
import type { Tag } from "@/types/Tag";
|
||||
import { buildPresetDateRange, parseDateTime } from "@/utils/date";
|
||||
import { corePermissionCodes, gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
name: "CustomerList"
|
||||
});
|
||||
|
||||
type DateFilterType = "today" | "yesterday" | "thisWeek" | "thisMonth" | "lastMonth" | "all" | "custom";
|
||||
|
||||
const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
const currentStoreStore = useCurrentStoreStore();
|
||||
@@ -148,6 +197,23 @@ const canShowActionMenu = computed(() => canCreateCustomer.value || canExportCus
|
||||
const scannerVisible = ref(false);
|
||||
const scanStatus = ref("点击扫码开始识别");
|
||||
let latestDecodedText = "";
|
||||
const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
{ label: "全部", value: "all" },
|
||||
{ label: "今天", value: "today" },
|
||||
{ label: "昨天", value: "yesterday" },
|
||||
{ label: "本周", value: "thisWeek" },
|
||||
{ label: "本月", value: "thisMonth" },
|
||||
{ label: "上个月", value: "lastMonth" },
|
||||
{ label: "自定义范围", value: "custom" }
|
||||
];
|
||||
const dateFilterType = ref<DateFilterType>("all");
|
||||
const dateRange = ref<[string, string]>(buildPresetDateRange("all"));
|
||||
const startDraft = ref("");
|
||||
const endDraft = ref("");
|
||||
const startVisible = ref(false);
|
||||
const endVisible = ref(false);
|
||||
const filterMenu = ref<{ toggle?: (index?: number) => void }>();
|
||||
const dateFilterLabel = computed(() => `录入时间:${dateOptions.find(item => item.value === dateFilterType.value)?.label || "全部"}`);
|
||||
|
||||
async function toggleScanner(): Promise<void> {
|
||||
scannerVisible.value = !scannerVisible.value;
|
||||
@@ -205,6 +271,65 @@ const actionList = computed<NavBarAction[]>(() => {
|
||||
return list;
|
||||
});
|
||||
|
||||
// ---------- 录入时间筛选 ----------
|
||||
|
||||
async function selectDateFilter(value: DropdownValue): Promise<void> {
|
||||
if (Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
dateFilterType.value = String(value) as DateFilterType;
|
||||
if (dateFilterType.value !== "custom") {
|
||||
dateRange.value = buildPresetDateRange(dateFilterType.value);
|
||||
await refresh();
|
||||
}
|
||||
}
|
||||
|
||||
function openStartTime(): void {
|
||||
startDraft.value = dateRange.value[0] || `${Time.formatDate(new Date())} 00:00`;
|
||||
startVisible.value = true;
|
||||
}
|
||||
|
||||
function openEndTime(): void {
|
||||
endDraft.value = dateRange.value[1] || `${Time.formatDate(new Date())} 23:59`;
|
||||
endVisible.value = true;
|
||||
}
|
||||
|
||||
function cancelStartTime(): void {
|
||||
startVisible.value = false;
|
||||
startDraft.value = dateRange.value[0];
|
||||
}
|
||||
|
||||
function cancelEndTime(): void {
|
||||
endVisible.value = false;
|
||||
endDraft.value = dateRange.value[1];
|
||||
}
|
||||
|
||||
async function confirmStartTime(value?: string | number): Promise<void> {
|
||||
startVisible.value = false;
|
||||
dateRange.value = [String(value || startDraft.value), dateRange.value[1]];
|
||||
await confirmCustomRange();
|
||||
}
|
||||
|
||||
async function confirmEndTime(value?: string | number): Promise<void> {
|
||||
endVisible.value = false;
|
||||
dateRange.value = [dateRange.value[0], String(value || endDraft.value)];
|
||||
await confirmCustomRange();
|
||||
}
|
||||
|
||||
async function confirmCustomRange(): Promise<void> {
|
||||
if (dateRange.value[0] && dateRange.value[1] && dateRange.value[1] < dateRange.value[0]) {
|
||||
dateRange.value = [dateRange.value[1], dateRange.value[0]];
|
||||
}
|
||||
dateFilterType.value = "custom";
|
||||
await refresh();
|
||||
}
|
||||
|
||||
function handleTagFilterOpen(): void {
|
||||
tagSelectorVisible.value = true;
|
||||
filterMenu.value?.toggle?.();
|
||||
}
|
||||
|
||||
// ---------- 标签筛选 ----------
|
||||
|
||||
const selectedTagList = ref<Tag[]>([]);
|
||||
@@ -244,11 +369,14 @@ const page = reactive<Page<Customer>>({
|
||||
});
|
||||
|
||||
const fetch = Toolkit.debounce(async () => {
|
||||
const [beginCreatedAt, endCreatedAt] = buildCreatedAtRange();
|
||||
const result = await CustomerAPI.list({
|
||||
...page,
|
||||
keyword: keyword.value,
|
||||
storeId: currentStoreStore.currentStoreId,
|
||||
tagIdList: selectedTagIdList.value
|
||||
tagIdList: selectedTagIdList.value,
|
||||
beginCreatedAt,
|
||||
endCreatedAt
|
||||
});
|
||||
pageResult.total = result.total;
|
||||
pageResult.list = pageResult.list.concat(result.list);
|
||||
@@ -360,40 +488,53 @@ async function doExport(): Promise<void> {
|
||||
isExporting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function buildCreatedAtRange(): [number | undefined, number | undefined] {
|
||||
if (dateFilterType.value === "all") {
|
||||
return [undefined, undefined];
|
||||
}
|
||||
|
||||
return [
|
||||
dateRange.value[0] ? Time.toTimestamp(parseDateTime(dateRange.value[0], false)) : undefined,
|
||||
dateRange.value[1] ? Time.toTimestamp(parseDateTime(dateRange.value[1], true)) : undefined
|
||||
];
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.customer-list {
|
||||
padding: var(--app-nav-height) 0 1rem 0;
|
||||
|
||||
.filter {
|
||||
gap: .5rem;
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
padding: .5rem;
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
|
||||
.search {
|
||||
--td-button-border-radius: .875rem;
|
||||
--td-button-border-radius: .75rem;
|
||||
--td-input-vertical-padding: .25rem 1rem;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 2;
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
.tag-filter {
|
||||
--td-button-border-radius: 1rem;
|
||||
.menus {
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
flex: 0 0 auto;
|
||||
height: auto;
|
||||
align-self: stretch;
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
overflow: hidden;
|
||||
margin-top: -1rem;
|
||||
padding-top: .8rem;
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,8 +557,27 @@ async function doExport(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
.list-wrapper {
|
||||
padding: 1rem 0;
|
||||
.list-wrap {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.summary {
|
||||
overflow: hidden;
|
||||
|
||||
:deep(.t-cell__title) {
|
||||
flex: 0 0 4.5rem;
|
||||
}
|
||||
|
||||
:deep(.t-cell__note) {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-align: right;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.delete {
|
||||
height: 100%;
|
||||
@@ -431,14 +591,25 @@ async function doExport(): Promise<void> {
|
||||
:global(html.theme-dark) {
|
||||
.customer-list {
|
||||
|
||||
.filter-bar {
|
||||
.filter {
|
||||
background: #10161f;
|
||||
|
||||
.text-input {
|
||||
.search {
|
||||
color: #e2e8f0;
|
||||
background: rgba(15, 23, 42, .72);
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
|
||||
.menus {
|
||||
background: #172033;
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
}
|
||||
|
||||
.summary {
|
||||
color: #e2e8f0;
|
||||
background: rgba(30, 41, 59, .9);
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
|
||||
.items {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
@refresh="refresh"
|
||||
@scrolltolower="fetch"
|
||||
>
|
||||
<t-cell-group theme="card">
|
||||
<t-cell-group class="fix-last-cell-line" theme="card">
|
||||
<t-swipe-cell
|
||||
v-entrance-transition="index * 30"
|
||||
v-for="(item, index) in visibleEventList"
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
核销登记记录
|
||||
</t-button>
|
||||
<div v-if="record" class="photo-wrapper" v-entrance-transition="350">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
:model-value="recordPhotoList"
|
||||
:photo-items="recordPhotoItemList"
|
||||
:show-viewer-actions="canUpdateRecord"
|
||||
@@ -105,7 +105,7 @@ import CardContainer from "@/components/CardContainer.vue";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import EventOptionSelector from "@/components/EventOptionSelector.vue";
|
||||
import EventRecordVerifyDialog from "@/components/EventRecordVerifyDialog.vue";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { EventRecord } from "@/types/EventRecord";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
|
||||
@@ -110,14 +110,16 @@
|
||||
</t-form-item>
|
||||
|
||||
<div class="photo-part">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
title="登记事件照片"
|
||||
:required="selectedRequiredPhotoEventList.length > 0"
|
||||
v-model="photoList"
|
||||
v-model:photo-items="photoItemList"
|
||||
:edit-mode="true"
|
||||
:loading="isPhotoUploading"
|
||||
@add="capturePhoto"
|
||||
@add="selectPhotoFile"
|
||||
@capture-photo="capturePhoto"
|
||||
@capture-video="captureVideo"
|
||||
/>
|
||||
</div>
|
||||
</t-form>
|
||||
@@ -170,10 +172,26 @@
|
||||
ref="recordPhotoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept="*/*"
|
||||
multiple
|
||||
@change="handleRecordPhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="recordPhotoCameraInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
@change="handleRecordPhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="videoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="video/*"
|
||||
capture="environment"
|
||||
@change="handleRecordPhotoSelected"
|
||||
>
|
||||
</div>
|
||||
<t-popup v-model="registeredAtPickerVisible" placement="bottom">
|
||||
<t-date-time-picker
|
||||
@@ -201,7 +219,7 @@ import CustomerList from "@/components/CustomerList.vue";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import EventOptionSelector from "@/components/EventOptionSelector.vue";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import EventSelector from "@/components/EventSelector.vue";
|
||||
import { useEventRecordPhoto } from "@/pages/event/component/useEventRecordPhoto";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
@@ -476,10 +494,14 @@ function validateNumberValueList(): boolean {
|
||||
|
||||
const {
|
||||
recordPhotoInputRef,
|
||||
recordPhotoCameraInputRef,
|
||||
videoInputRef,
|
||||
photoItemList,
|
||||
isPhotoUploading,
|
||||
photoList,
|
||||
capturePhoto,
|
||||
selectPhotoFile,
|
||||
captureVideo,
|
||||
handleRecordPhotoSelected,
|
||||
setExistingPhotoList,
|
||||
buildTempFileIdList,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.eventRecord.read" class="registration-record-list">
|
||||
<div class="search-bar">
|
||||
<div class="search-status">
|
||||
<div class="filters glass">
|
||||
<div class="search-date">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="search-input"
|
||||
@@ -73,7 +73,8 @@
|
||||
/>
|
||||
<t-cell title="事件" :note="eventFilterLabel" />
|
||||
<t-cell v-if="optionFilterLabel !== '全部选项'" title="选项" :note="optionFilterLabel" />
|
||||
<t-cell title="数据量" :note="`共 ${pageResult.total} 条记录`" />
|
||||
<t-cell title="记录数" :note="Text.display(pageResult.total)" />
|
||||
<t-cell title="客户数" :note="Text.display(pageResult.customerCount)" />
|
||||
<t-cell v-if="summaryNumberValueText" title="数值合计" :note="summaryNumberValueText" />
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="hasSelectedOption && optionStatList.length" title="选项统计" class="option-stat" theme="card">
|
||||
@@ -136,7 +137,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { DropdownValue } from "tdesign-mobile-vue";
|
||||
import { Time, WebToolkit } from "timi-web";
|
||||
import { Time, Text, WebToolkit } from "timi-web";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import EventAPI from "@/api/EventAPI";
|
||||
import EventRecordAPI from "@/api/EventRecordAPI";
|
||||
@@ -148,10 +149,11 @@ import type { EventOptionStat, EventRecordPage, EventRecordPageResult, Verificat
|
||||
import type { NavBarAction } from "@/types/NavBarAction";
|
||||
import { isRetiredEvent } from "@/utils/event";
|
||||
import { formatEventNumberValue } from "@/utils/eventValue";
|
||||
import { buildPresetDateRange, parseDateFilterType, parseDateTime } from "@/utils/date";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { Message } from "@/utils/message.ts";
|
||||
|
||||
type DateFilterType = "today" | "yesterday" | "lastWeek" | "thisMonth" | "lastMonth" | "all" | "custom";
|
||||
type DateFilterType = "today" | "yesterday" | "thisWeek" | "thisMonth" | "lastMonth" | "all" | "custom";
|
||||
type VerificationFilter = "ALL" | VerificationStatus;
|
||||
|
||||
defineOptions({
|
||||
@@ -166,7 +168,7 @@ const userStore = useUserStore();
|
||||
const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
{ label: "今天", value: "today" },
|
||||
{ label: "昨天", value: "yesterday" },
|
||||
{ label: "上周", value: "lastWeek" },
|
||||
{ label: "本周", value: "thisWeek" },
|
||||
{ label: "本月", value: "thisMonth" },
|
||||
{ label: "上个月", value: "lastMonth" },
|
||||
{ label: "全部", value: "all" },
|
||||
@@ -178,7 +180,7 @@ const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
const keyword = ref(getInitialKeyword());
|
||||
const customerId = ref(getQueryText("customerId"));
|
||||
const customerSelectorVisible = ref(false);
|
||||
const dateFilterType = ref<DateFilterType>(parseDateFilterType(route.query.dateType));
|
||||
const dateFilterType = ref<DateFilterType>(parseDateFilterType(route.query.dateType, dateOptions, "today"));
|
||||
const dateRange = ref(parseDateRange(dateFilterType.value));
|
||||
const startDraft = ref("");
|
||||
const endDraft = ref("");
|
||||
@@ -364,7 +366,8 @@ const page = reactive<EventRecordPage>({
|
||||
const pageResult = reactive<EventRecordPageResult>({
|
||||
total: 0,
|
||||
list: [],
|
||||
numberValueTotal: null
|
||||
numberValueTotal: null,
|
||||
customerCount: 0
|
||||
});
|
||||
const optionStatList = ref<EventOptionStat[]>([]);
|
||||
let loadToken = 0;
|
||||
@@ -389,6 +392,7 @@ async function reloadRecords(): Promise<void> {
|
||||
pageResult.total = 0;
|
||||
pageResult.list = [];
|
||||
pageResult.numberValueTotal = null;
|
||||
pageResult.customerCount = 0;
|
||||
optionStatList.value = [];
|
||||
isNoMore.value = false;
|
||||
await Promise.all([loadRecords(), loadOptionStats()]);
|
||||
@@ -420,6 +424,7 @@ async function loadRecords(): Promise<void> {
|
||||
pageResult.list = pageResult.list.concat(result.list || []);
|
||||
pageResult.total = result.total || 0;
|
||||
pageResult.numberValueTotal = result.numberValueTotal ?? null;
|
||||
pageResult.customerCount = result.customerCount ?? 0;
|
||||
page.index += 1;
|
||||
isNoMore.value = pageResult.list.length >= pageResult.total || (result.list || []).length < page.size;
|
||||
} finally {
|
||||
@@ -471,7 +476,7 @@ async function selectDateFilter(type: DropdownValue): Promise<void> {
|
||||
|
||||
dateFilterType.value = String(type) as DateFilterType;
|
||||
if (dateFilterType.value !== "custom") {
|
||||
dateRange.value = buildPresetRange(dateFilterType.value);
|
||||
dateRange.value = buildPresetDateRange(dateFilterType.value);
|
||||
await replaceFilterQuery();
|
||||
await reloadRecords();
|
||||
} else {
|
||||
@@ -586,14 +591,9 @@ function getQueryText(key: string): string {
|
||||
return Array.isArray(value) ? String(value[0] || "") : String(value || "");
|
||||
}
|
||||
|
||||
function parseDateFilterType(value: unknown): DateFilterType {
|
||||
const text = Array.isArray(value) ? String(value[0] || "") : String(value || "");
|
||||
return dateOptions.some(item => item.value === text) ? text as DateFilterType : "today";
|
||||
}
|
||||
|
||||
function parseDateRange(type: DateFilterType): [string, string] {
|
||||
if (type !== "custom") {
|
||||
return buildPresetRange(type);
|
||||
return buildPresetDateRange(type);
|
||||
}
|
||||
|
||||
const beginAt = getQueryText("beginAt");
|
||||
@@ -657,45 +657,6 @@ async function replaceFilterQuery(): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
function buildPresetRange(type: Exclude<DateFilterType, "custom">): [string, string] {
|
||||
if (type === "all") {
|
||||
return ["", ""];
|
||||
}
|
||||
if (type === "lastWeek") {
|
||||
const current = new Date();
|
||||
current.setHours(0, 0, 0, 0);
|
||||
const day = current.getDay() || 7;
|
||||
const thisWeekMonday = new Date(current);
|
||||
thisWeekMonday.setDate(current.getDate() - day + 1);
|
||||
const lastWeekMonday = new Date(thisWeekMonday);
|
||||
lastWeekMonday.setDate(thisWeekMonday.getDate() - 7);
|
||||
const lastWeekSunday = new Date(thisWeekMonday);
|
||||
lastWeekSunday.setDate(thisWeekMonday.getDate() - 1);
|
||||
return [`${Time.formatDate(lastWeekMonday)} 00:00`, `${Time.formatDate(lastWeekSunday)} 23:59`];
|
||||
}
|
||||
if (type === "thisMonth") {
|
||||
const current = new Date();
|
||||
const begin = new Date(current.getFullYear(), current.getMonth(), 1);
|
||||
return [`${Time.formatDate(begin)} 00:00`, `${Time.formatDate(current)} 23:59`];
|
||||
}
|
||||
if (type === "lastMonth") {
|
||||
const current = new Date();
|
||||
const begin = new Date(current.getFullYear(), current.getMonth() - 1, 1);
|
||||
const end = new Date(current.getFullYear(), current.getMonth(), 0);
|
||||
return [`${Time.formatDate(begin)} 00:00`, `${Time.formatDate(end)} 23:59`];
|
||||
}
|
||||
|
||||
const offsetMap: Record<Exclude<DateFilterType, "all" | "custom" | "lastWeek" | "thisMonth" | "lastMonth">, number> = {
|
||||
today: 0,
|
||||
yesterday: 1
|
||||
};
|
||||
const date = new Date();
|
||||
date.setHours(0, 0, 0, 0);
|
||||
date.setDate(date.getDate() - offsetMap[type]);
|
||||
const value = `${Time.formatDate(date)} 00:00`;
|
||||
return [value, `${Time.formatDate(date)} 23:59`];
|
||||
}
|
||||
|
||||
function buildUnixRange(): [number, number] {
|
||||
if (dateFilterType.value === "all") {
|
||||
return [0, Time.toTimestamp(new Date())];
|
||||
@@ -707,16 +668,6 @@ function buildUnixRange(): [number, number] {
|
||||
];
|
||||
}
|
||||
|
||||
function parseDateTime(value: string, isEnd: boolean): Date {
|
||||
if (!value) {
|
||||
return isEnd ? new Date() : new Date(0);
|
||||
}
|
||||
const [dateText, timeText = isEnd ? "23:59" : "00:00"] = value.split(" ");
|
||||
const [year, month, day] = dateText.split("-").map(Number);
|
||||
const [hour, minute] = timeText.split(":").map(Number);
|
||||
return new Date(year, month - 1, day, hour || 0, minute || 0, isEnd ? 59 : 0, 0);
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.clearRight();
|
||||
navBarStore.setCustomRightVisible(canShowActionMenu.value);
|
||||
@@ -733,12 +684,11 @@ onUnmounted(() => {
|
||||
|
||||
<style scoped lang="less">
|
||||
.registration-record-list {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding: calc(var(--app-nav-height)) 0 6rem 0;
|
||||
padding: var(--app-nav-height) 0 6rem 0;
|
||||
flex-direction: column;
|
||||
|
||||
.search-bar {
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
left: 0;
|
||||
right: 0;
|
||||
@@ -746,11 +696,9 @@ onUnmounted(() => {
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: #F5F5F8;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
flex-direction: column;
|
||||
|
||||
.search-status {
|
||||
.search-date {
|
||||
display: flex;
|
||||
|
||||
.search-input {
|
||||
@@ -758,9 +706,8 @@ onUnmounted(() => {
|
||||
--td-input-vertical-padding: .25rem 1rem;
|
||||
|
||||
flex: 1;
|
||||
border: 1px solid rgba(148, 163, 184, .28);
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 2;
|
||||
background: #f8fbff;
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
@@ -769,7 +716,7 @@ onUnmounted(() => {
|
||||
--td-spacer: 4px;
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 1;
|
||||
margin-left: -2.5rem;
|
||||
padding-left: 3rem;
|
||||
@@ -786,11 +733,10 @@ onUnmounted(() => {
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
overflow: hidden;
|
||||
margin-top: -1rem;
|
||||
padding-top: .8rem;
|
||||
background: #fff;
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
border-top: none;
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
|
||||
|
||||
@@ -132,12 +132,13 @@ import EventAPI from "@/api/EventAPI";
|
||||
import EventRecordAPI from "@/api/EventRecordAPI";
|
||||
import type { CustomerEventRankView, EventRecordRankPage, EventRecordRankType } from "@/types/EventRecord";
|
||||
import type { EventItem } from "@/types/EventItem";
|
||||
import { buildPresetDateRange, parseDateFilterType, parseDateTime } from "@/utils/date";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { formatEventNumberValue } from "@/utils/eventValue";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { Message } from "@/utils/message.ts";
|
||||
|
||||
type DateFilterType = "all" | "today" | "yesterday" | "lastWeek" | "thisMonth" | "custom";
|
||||
type DateFilterType = "all" | "today" | "yesterday" | "thisWeek" | "thisMonth" | "custom";
|
||||
|
||||
defineOptions({
|
||||
name: "EventRecordRank"
|
||||
@@ -156,7 +157,7 @@ const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
{ label: "全部时间", value: "all" },
|
||||
{ label: "今天", value: "today" },
|
||||
{ label: "昨天", value: "yesterday" },
|
||||
{ label: "上周", value: "lastWeek" },
|
||||
{ label: "本周", value: "thisWeek" },
|
||||
{ label: "本月", value: "thisMonth" },
|
||||
{ label: "自定义范围", value: "custom" }
|
||||
];
|
||||
@@ -164,7 +165,7 @@ const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
// ---------- 筛选 ----------
|
||||
|
||||
const rankType = ref<EventRecordRankType>(parseRankType(route.query.rankType));
|
||||
const dateFilterType = ref<DateFilterType>(parseDateFilterType(route.query.dateType));
|
||||
const dateFilterType = ref<DateFilterType>(parseDateFilterType(route.query.dateType, dateOptions, "all"));
|
||||
const dateRange = ref(parseDateRange(dateFilterType.value));
|
||||
const eventFilter = ref<string[]>([]);
|
||||
const eventList = ref<EventItem[]>([]);
|
||||
@@ -341,9 +342,9 @@ async function selectDateFilter(value: DropdownValue): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
dateFilterType.value = parseDateFilterType(value);
|
||||
dateFilterType.value = parseDateFilterType(value, dateOptions, "all");
|
||||
if (dateFilterType.value !== "custom") {
|
||||
dateRange.value = buildPresetRange(dateFilterType.value);
|
||||
dateRange.value = buildPresetDateRange(dateFilterType.value);
|
||||
await replaceFilterQuery();
|
||||
await reloadRanks();
|
||||
return;
|
||||
@@ -388,14 +389,9 @@ function parseRankType(value: unknown): EventRecordRankType {
|
||||
return rankTypeOptions.some(item => item.value === text) ? text as EventRecordRankType : "TOTAL_DAYS";
|
||||
}
|
||||
|
||||
function parseDateFilterType(value: unknown): DateFilterType {
|
||||
const text = Array.isArray(value) ? String(value[0] || "") : String(value || "");
|
||||
return dateOptions.some(item => item.value === text) ? text as DateFilterType : "all";
|
||||
}
|
||||
|
||||
function parseDateRange(type: DateFilterType): [string, string] {
|
||||
if (type !== "custom") {
|
||||
return buildPresetRange(type);
|
||||
return buildPresetDateRange(type);
|
||||
}
|
||||
|
||||
return [getQueryText("beginAt"), getQueryText("endAt")];
|
||||
@@ -436,38 +432,6 @@ async function replaceFilterQuery(): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
function buildPresetRange(type: Exclude<DateFilterType, "custom">): [string, string] {
|
||||
if (type === "all") {
|
||||
return ["", ""];
|
||||
}
|
||||
if (type === "lastWeek") {
|
||||
const current = new Date();
|
||||
current.setHours(0, 0, 0, 0);
|
||||
const day = current.getDay() || 7;
|
||||
const thisWeekMonday = new Date(current);
|
||||
thisWeekMonday.setDate(current.getDate() - day + 1);
|
||||
const lastWeekMonday = new Date(thisWeekMonday);
|
||||
lastWeekMonday.setDate(thisWeekMonday.getDate() - 7);
|
||||
const lastWeekSunday = new Date(thisWeekMonday);
|
||||
lastWeekSunday.setDate(thisWeekMonday.getDate() - 1);
|
||||
return [`${Time.formatDate(lastWeekMonday)} 00:00`, `${Time.formatDate(lastWeekSunday)} 23:59`];
|
||||
}
|
||||
if (type === "thisMonth") {
|
||||
const current = new Date();
|
||||
const begin = new Date(current.getFullYear(), current.getMonth(), 1);
|
||||
return [`${Time.formatDate(begin)} 00:00`, `${Time.formatDate(current)} 23:59`];
|
||||
}
|
||||
|
||||
const offsetMap: Record<Exclude<DateFilterType, "all" | "custom" | "lastWeek" | "thisMonth">, number> = {
|
||||
today: 0,
|
||||
yesterday: 1
|
||||
};
|
||||
const date = new Date();
|
||||
date.setHours(0, 0, 0, 0);
|
||||
date.setDate(date.getDate() - offsetMap[type]);
|
||||
return [`${Time.formatDate(date)} 00:00`, `${Time.formatDate(date)} 23:59`];
|
||||
}
|
||||
|
||||
function buildUnixRange(): [number | undefined, number | undefined] {
|
||||
if (dateFilterType.value === "all") {
|
||||
return [undefined, undefined];
|
||||
@@ -478,16 +442,6 @@ function buildUnixRange(): [number | undefined, number | undefined] {
|
||||
];
|
||||
}
|
||||
|
||||
function parseDateTime(value: string, isEnd: boolean): Date {
|
||||
if (!value) {
|
||||
return isEnd ? new Date() : new Date(0);
|
||||
}
|
||||
const [dateText, timeText = isEnd ? "23:59" : "00:00"] = value.split(" ");
|
||||
const [year, month, day] = dateText.split("-").map(Number);
|
||||
const [hour, minute] = timeText.split(":").map(Number);
|
||||
return new Date(year, month - 1, day, hour || 0, minute || 0, isEnd ? 59 : 0, 0);
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadEvents();
|
||||
initialized = true;
|
||||
|
||||
@@ -3,9 +3,12 @@ import { AttachmentAPI, type Attachment } from "timi-web-api";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { compressUploadImageList } from "@/utils/imageCompression";
|
||||
import { saveCapturedFilesFromInput } from "@/utils/twaBridge";
|
||||
|
||||
export function useEventRecordPhoto() {
|
||||
const recordPhotoInputRef = ref<HTMLInputElement>();
|
||||
const recordPhotoCameraInputRef = ref<HTMLInputElement>();
|
||||
const videoInputRef = ref<HTMLInputElement>();
|
||||
const photoItemList = ref<PhotoItem[]>([]);
|
||||
const isPhotoUploading = ref(false);
|
||||
const photoList = computed<string[]>({
|
||||
@@ -19,24 +22,34 @@ export function useEventRecordPhoto() {
|
||||
});
|
||||
|
||||
function capturePhoto(): void {
|
||||
recordPhotoCameraInputRef.value?.click();
|
||||
}
|
||||
|
||||
function selectPhotoFile(): void {
|
||||
recordPhotoInputRef.value?.click();
|
||||
}
|
||||
|
||||
function captureVideo(): void {
|
||||
videoInputRef.value?.click();
|
||||
}
|
||||
|
||||
async function handleRecordPhotoSelected(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const fileList = Array.from(input.files || []);
|
||||
if (!fileList.length) {
|
||||
return;
|
||||
}
|
||||
saveCapturedFilesFromInput(input, fileList);
|
||||
isPhotoUploading.value = true;
|
||||
try {
|
||||
const compressedFileList = await compressUploadImageList(fileList);
|
||||
const tempFileList = await AttachmentAPI.upload(compressedFileList);
|
||||
for (const item of tempFileList) {
|
||||
for (const [index, item] of tempFileList.entries()) {
|
||||
if (!item.id) {
|
||||
continue;
|
||||
}
|
||||
photoItemList.value.push({
|
||||
mimeType: fileList[index]?.type,
|
||||
tempFileId: item.id,
|
||||
url: AttachmentAPI.getTempReadURL(item.id)
|
||||
});
|
||||
@@ -53,6 +66,7 @@ export function useEventRecordPhoto() {
|
||||
.filter(item => !!item.id)
|
||||
.map(item => ({
|
||||
attachment: item,
|
||||
mimeType: item.mimeType,
|
||||
previewUrl: getAttachmentReadURL(item.id || ""),
|
||||
url: getAttachmentReadURL(item.id || "", 90)
|
||||
}));
|
||||
@@ -80,10 +94,14 @@ export function useEventRecordPhoto() {
|
||||
|
||||
return {
|
||||
recordPhotoInputRef,
|
||||
recordPhotoCameraInputRef,
|
||||
videoInputRef,
|
||||
photoItemList,
|
||||
isPhotoUploading,
|
||||
photoList,
|
||||
capturePhoto,
|
||||
selectPhotoFile,
|
||||
captureVideo,
|
||||
handleRecordPhotoSelected,
|
||||
setExistingPhotoList,
|
||||
buildTempFileIdList,
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.customerFollowUpReminder.read" class="follow-up-reminder-detail">
|
||||
<t-empty v-if="!detail" :description="isLoading ? '正在加载跟进提醒' : '跟进提醒不存在'" />
|
||||
<template v-else>
|
||||
<customer-profile-card
|
||||
class="customer"
|
||||
:customer="detail.customer"
|
||||
v-entrance-transition
|
||||
@click="toCustomer"
|
||||
/>
|
||||
<t-cell-group title="提醒信息" theme="card" v-entrance-transition="70">
|
||||
<t-cell title="业务状态">
|
||||
<template #note>
|
||||
<t-tag size="small" :theme="getStatusTheme(detail.status)" :content="getStatusText(detail.status)" />
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell title="负责人" :note="getResponsibleName(detail)" />
|
||||
<t-cell title="提醒时间" :note="detail.remindAt ? Time.toDateTime(detail.remindAt) : '-'" />
|
||||
<t-cell title="创建时间">
|
||||
<template #note>
|
||||
<pass-time-label :timestamp="detail.createdAt" underline />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<t-cell-group title="跟进内容" theme="card" v-entrance-transition="140">
|
||||
<div class="content bg-white" v-text="detail.content || '未填写跟进内容'" />
|
||||
<div class="media-wrap bg-white">
|
||||
<media-selector
|
||||
:model-value="attachmentUrlList"
|
||||
:photo-items="attachmentItemList"
|
||||
:show-add="false"
|
||||
:show-remove="false"
|
||||
:show-viewer-actions="false"
|
||||
empty-text="暂无附件"
|
||||
title="附件"
|
||||
/>
|
||||
</div>
|
||||
</t-cell-group>
|
||||
<t-cell-group title="通知方式" theme="card" v-entrance-transition="210">
|
||||
<t-cell v-if="hasChannel('INTERNAL')" title="站内通知">
|
||||
<template #note>
|
||||
<t-tag
|
||||
size="small"
|
||||
variant="outline"
|
||||
:theme="internalNotifyStatus ? getNotifyStatusTheme(internalNotifyStatus.status) : 'primary'"
|
||||
:content="internalNotifyStatus ? getNotifyStatusText(internalNotifyStatus.status) : '已配置'"
|
||||
/>
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell v-if="hasChannel('SMS')" title="短信通知">
|
||||
<template #note>
|
||||
<t-tag
|
||||
size="small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
:content="detail.smsNotifyDetailId ? '已进入当天批次' : '等待当天 08:00 批次'"
|
||||
/>
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell v-if="!detail.notifyChannelList?.length" title="通知方式" note="不发送通知" />
|
||||
<div class="tips gray bg-white" v-text="'站内通知在提醒时间后生效;短信按提醒日期在 08:00 聚合发送。通知状态仅作辅助展示,不代表跟进提醒业务状态。'" />
|
||||
</t-cell-group>
|
||||
<div class="actions" v-entrance-transition="350">
|
||||
<t-button
|
||||
v-if="canComplete && detail.status === 'PENDING'"
|
||||
theme="primary"
|
||||
:disabled="isOperating"
|
||||
:loading="isCompleting"
|
||||
@click="confirmComplete"
|
||||
>完成跟进</t-button>
|
||||
<t-button
|
||||
v-if="canDelete"
|
||||
theme="danger"
|
||||
:loading="isDeleting"
|
||||
:disabled="isOperating"
|
||||
@click="confirmDelete"
|
||||
>删除提醒</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { DialogPlugin } from "tdesign-mobile-vue";
|
||||
import { NotifyAPI, type NotifyDetail, useUserStore } from "timi-web-api";
|
||||
import { PassTimeLabel, Time } from "timi-web";
|
||||
import { Message } from "@/utils/message";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import FollowUpReminderAPI from "@/api/FollowUpReminderAPI";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { FollowUpReminder, FollowUpReminderNotifyChannel, FollowUpReminderStatus } from "@/types/FollowUpReminder";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { corePermissionCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
type NotifyTagTheme = "default" | "success" | "warning" | "primary" | "danger";
|
||||
|
||||
defineOptions({
|
||||
name: "FollowUpReminderDetail"
|
||||
});
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const navBarStore = useNavBarStore();
|
||||
const userStore = useUserStore();
|
||||
|
||||
const detail = ref<FollowUpReminder>();
|
||||
const isLoading = ref(false);
|
||||
const isCompleting = ref(false);
|
||||
const isDeleting = ref(false);
|
||||
const internalNotifyStatus = ref<NotifyDetail>();
|
||||
let loadToken = 0;
|
||||
|
||||
const canUpdate = computed(() => detail.value?.status === "PENDING"
|
||||
&& userStore.hasPermissions(permissionCodes.customerFollowUpReminder.update));
|
||||
const canComplete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.complete));
|
||||
const canDelete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.delete));
|
||||
const isOperating = computed(() => isCompleting.value || isDeleting.value);
|
||||
const attachmentItemList = computed<PhotoItem[]>(() => (detail.value?.attachmentList || [])
|
||||
.filter(item => !!item.id)
|
||||
.map(item => ({
|
||||
attachment: item,
|
||||
attachType: item.attachType || "PHOTO",
|
||||
mimeType: item.mimeType,
|
||||
previewUrl: getAttachmentReadURL(item.id || ""),
|
||||
url: getAttachmentReadURL(item.id || "", 90)
|
||||
})));
|
||||
const attachmentUrlList = computed(() => attachmentItemList.value.map(item => item.url));
|
||||
|
||||
function hasChannel(channel: FollowUpReminderNotifyChannel): boolean {
|
||||
const item = detail.value;
|
||||
if (!item) {
|
||||
return false;
|
||||
}
|
||||
return item.notifyChannelList?.includes(channel)
|
||||
|| (channel === "INTERNAL" && item.internalNotifyEnabled === true)
|
||||
|| (channel === "SMS" && item.smsNotifyEnabled === true)
|
||||
|| false;
|
||||
}
|
||||
|
||||
function getResponsibleName(item: FollowUpReminder): string {
|
||||
return item.responsibleUser?.nick || item.responsibleUser?.name || item.responsibleUserId || "未命名负责人";
|
||||
}
|
||||
|
||||
function getStatusText(status?: FollowUpReminderStatus): string {
|
||||
return status === "COMPLETED" ? "已完成" : "待完成";
|
||||
}
|
||||
|
||||
function getStatusTheme(status?: FollowUpReminderStatus): "success" | "warning" {
|
||||
return status === "COMPLETED" ? "success" : "warning";
|
||||
}
|
||||
|
||||
function getNotifyStatusText(status?: NotifyDetail["status"]): string {
|
||||
const map: Record<NonNullable<NotifyDetail["status"]>, string> = {
|
||||
WAITING: "等待生效",
|
||||
REMINDED: "已生效",
|
||||
TIMEOUT: "已超时",
|
||||
CANCEL: "已取消",
|
||||
FAIL: "发送失败"
|
||||
};
|
||||
return status ? map[status] : "状态未知";
|
||||
}
|
||||
|
||||
function getNotifyStatusTheme(status?: NotifyDetail["status"]): NotifyTagTheme {
|
||||
if (status === "REMINDED") {
|
||||
return "success";
|
||||
}
|
||||
if (status === "FAIL" || status === "TIMEOUT") {
|
||||
return "danger";
|
||||
}
|
||||
if (status === "WAITING") {
|
||||
return "warning";
|
||||
}
|
||||
return "primary";
|
||||
}
|
||||
|
||||
async function loadDetail(): Promise<void> {
|
||||
const token = loadToken + 1;
|
||||
loadToken = token;
|
||||
detail.value = undefined;
|
||||
internalNotifyStatus.value = undefined;
|
||||
navBarStore.clearRight();
|
||||
const id = String(route.params.id || "");
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const result = await FollowUpReminderAPI.detail(id);
|
||||
if (token !== loadToken) {
|
||||
return;
|
||||
}
|
||||
detail.value = result;
|
||||
setEditAction();
|
||||
await loadInternalNotifyStatus(result, token);
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "跟进提醒详情加载失败"));
|
||||
} finally {
|
||||
if (token === loadToken) {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setEditAction(): void {
|
||||
if (canUpdate.value) {
|
||||
navBarStore.setRightText("编辑", "var(--td-brand-color)", toEdit);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadInternalNotifyStatus(item: FollowUpReminder, token: number): Promise<void> {
|
||||
if (!item.internalNotifyDetailId || !userStore.hasPermissions(corePermissionCodes.notify.read)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await NotifyAPI.internalDetail(item.internalNotifyDetailId);
|
||||
if (token === loadToken) {
|
||||
internalNotifyStatus.value = result;
|
||||
}
|
||||
} catch {
|
||||
// 站内通知详情只对当前接收用户开放,无法读取时不影响提醒详情。
|
||||
}
|
||||
}
|
||||
|
||||
async function toCustomer(): Promise<void> {
|
||||
if (detail.value?.customerId) {
|
||||
await router.push({
|
||||
name: "CustomerDetail",
|
||||
params: { id: detail.value.customerId },
|
||||
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentRouteDepth(): number {
|
||||
const transitionDepth = Array.isArray(route.query.transitionDepth)
|
||||
? route.query.transitionDepth[0]
|
||||
: route.query.transitionDepth;
|
||||
const depth = Number(transitionDepth);
|
||||
if (transitionDepth && Number.isInteger(depth) && 0 <= depth && depth <= 20) {
|
||||
return depth;
|
||||
}
|
||||
return Number(route.meta.depth ?? 0);
|
||||
}
|
||||
|
||||
async function toEdit(): Promise<void> {
|
||||
if (detail.value?.id && canUpdate.value) {
|
||||
await router.push({ name: "CustomerFollowUpReminderEdit", params: { id: detail.value.id } });
|
||||
}
|
||||
}
|
||||
|
||||
function confirmComplete(): void {
|
||||
if (!detail.value?.id || !canComplete.value || detail.value.status !== "PENDING" || isOperating.value) {
|
||||
return;
|
||||
}
|
||||
const dialog = DialogPlugin.confirm({
|
||||
title: "完成跟进提醒",
|
||||
content: "完成后不能重新打开,确定完成此跟进提醒吗?",
|
||||
cancelBtn: "取消",
|
||||
confirmBtn: "完成",
|
||||
onCancel() {
|
||||
dialog.destroy();
|
||||
},
|
||||
onConfirm: async () => {
|
||||
dialog.destroy();
|
||||
await complete(detail.value?.id || "");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function complete(id: string): Promise<void> {
|
||||
isCompleting.value = true;
|
||||
try {
|
||||
await FollowUpReminderAPI.complete(id);
|
||||
Message.success("跟进提醒已完成");
|
||||
await loadDetail();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "跟进提醒完成失败"));
|
||||
} finally {
|
||||
isCompleting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDelete(): void {
|
||||
if (!detail.value?.id || !canDelete.value || isOperating.value) {
|
||||
return;
|
||||
}
|
||||
const dialog = DialogPlugin.confirm({
|
||||
title: "删除跟进提醒",
|
||||
content: "删除后列表中将不再显示,确定删除这条跟进提醒吗?",
|
||||
cancelBtn: "取消",
|
||||
confirmBtn: "删除",
|
||||
onCancel() {
|
||||
dialog.destroy();
|
||||
},
|
||||
onConfirm: async () => {
|
||||
dialog.destroy();
|
||||
await remove(detail.value?.id || "");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function remove(id: string): Promise<void> {
|
||||
isDeleting.value = true;
|
||||
navBarStore.clearRight();
|
||||
try {
|
||||
await FollowUpReminderAPI.remove(id);
|
||||
Message.success("跟进提醒已删除");
|
||||
await router.replace({ name: "CustomerFollowUpReminderList" });
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "跟进提醒删除失败"));
|
||||
setEditAction();
|
||||
} finally {
|
||||
isDeleting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => route.params.id, async () => {
|
||||
await loadDetail();
|
||||
}, { immediate: true });
|
||||
|
||||
onUnmounted(() => navBarStore.clearRight());
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.follow-up-reminder-detail {
|
||||
gap: 1rem;
|
||||
padding: calc(var(--app-nav-height) + 1rem) 0 2rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.customer {
|
||||
margin: 0 1rem;
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 1rem;
|
||||
line-height: 1.7;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.media-wrap {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.tips {
|
||||
padding: 1rem;
|
||||
font-size: .875rem;
|
||||
}
|
||||
|
||||
.actions {
|
||||
--td-button-border-radius: 1rem;
|
||||
|
||||
gap: .5rem;
|
||||
padding: 0 1rem;
|
||||
display: flex;
|
||||
|
||||
.t-button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.follow-up-reminder-detail {
|
||||
.content,
|
||||
.attachment-wrapper {
|
||||
background: rgba(30, 41, 59, .9);
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,645 @@
|
||||
<template>
|
||||
<div v-can="pageAccess" class="follow-up-reminder-edit">
|
||||
<t-form class="form" label-width="6rem">
|
||||
<t-form-item label="客户" content-align="right" required-mark>
|
||||
<div class="customer-picker">
|
||||
<span v-if="!selectedCustomer" class="picker-text" v-text="'请选择客户'" />
|
||||
<t-button
|
||||
theme="primary"
|
||||
size="extra-small"
|
||||
content="选择"
|
||||
@click="customerSelectorVisible = true"
|
||||
/>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="selectedCustomer" label-width="0">
|
||||
<customer-profile-card class="customer-profile" :customer="selectedCustomer" />
|
||||
</t-form-item>
|
||||
<t-form-item
|
||||
label="负责人"
|
||||
content-align="right"
|
||||
required-mark
|
||||
arrow
|
||||
@click="responsibleSelectorVisible = true"
|
||||
>
|
||||
<span v-text="selectedResponsibleName" />
|
||||
</t-form-item>
|
||||
<t-form-item label="跟进内容" required-mark>
|
||||
<t-textarea
|
||||
v-model="formModel.content"
|
||||
class="textarea"
|
||||
:autosize="{ minRows: 1, maxRows: 8 }"
|
||||
maxlength="1000"
|
||||
borderless
|
||||
placeholder="请输入跟进内容"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<media-selector
|
||||
:model-value="photoUrlList"
|
||||
v-model:photo-items="photoItems"
|
||||
:upload="uploadReminderPhotoList"
|
||||
:edit-mode="true"
|
||||
:loading="isSaving || isUploading"
|
||||
add-text="选择照片"
|
||||
:show-type-label="false"
|
||||
title="附件照片"
|
||||
/>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
<t-form class="form">
|
||||
<t-form-item class="remind-at" label="提醒时间" content-align="right" required-mark>
|
||||
<span class="picker-text" v-text="formModel.remindAtText || '请选择提醒时间'" />
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0" content-align="right">
|
||||
<t-radio-group
|
||||
v-model="selectedRemindAtPreset"
|
||||
@change="handleRemindAtPresetChange"
|
||||
>
|
||||
<t-radio :block="false" borderless value="tomorrow">明天</t-radio>
|
||||
<t-radio :block="false" borderless value="afterTomorrow">后天</t-radio>
|
||||
<t-radio :block="false" borderless value="custom">指定时间</t-radio>
|
||||
</t-radio-group>
|
||||
</t-form-item>
|
||||
<t-form-item label="站内通知" content-align="right">
|
||||
<t-switch
|
||||
size="small"
|
||||
:model-value="hasChannel('INTERNAL')"
|
||||
borderless
|
||||
@change="value => setChannel('INTERNAL', value === true)"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="短信通知" content-align="right">
|
||||
<t-switch
|
||||
size="small"
|
||||
:model-value="hasChannel('SMS')"
|
||||
:disabled="!canSelectSms"
|
||||
borderless
|
||||
@change="value => setChannel('SMS', value === true)"
|
||||
/>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
<div class="tips red"
|
||||
v-text="'提醒时间精确到分钟,不能早于当前时间。短信会在提醒日期 08:00 聚合发送,不会在你选择的精确时间发送。'" />
|
||||
<customer-selector
|
||||
v-model="formModel.customerId"
|
||||
v-model:visible="customerSelectorVisible"
|
||||
:store-id="customerPickerStoreId"
|
||||
@change="handleCustomerChange"
|
||||
/>
|
||||
<managed-user-selector
|
||||
v-model="formModel.responsibleUserId"
|
||||
v-model:visible="responsibleSelectorVisible"
|
||||
:store-id="responsiblePickerStoreId"
|
||||
@change="handleResponsibleChange"
|
||||
/>
|
||||
<t-popup v-model="remindAtPickerVisible" placement="bottom">
|
||||
<t-date-time-picker
|
||||
v-if="remindAtPickerVisible"
|
||||
v-model="remindAtDraftText"
|
||||
:start="minimumDateTimeText"
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
:mode="['date', 'minute']"
|
||||
title="提醒时间"
|
||||
@cancel="cancelRemindAtPicker"
|
||||
@confirm="confirmRemindAt"
|
||||
/>
|
||||
</t-popup>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Time } from "timi-web";
|
||||
import { AttachmentAPI, type User, useUserStore } from "timi-web-api";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import { Message } from "@/utils/message";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import FollowUpReminderAPI from "@/api/FollowUpReminderAPI";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import ManagedUserSelector from "@/pages/followUpReminder/component/ManagedUserSelector.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { ManagedUser } from "@/types/ManagedUser";
|
||||
import type {
|
||||
FollowUpReminder,
|
||||
FollowUpReminderAttachment,
|
||||
FollowUpReminderNotifyChannel,
|
||||
FollowUpReminderPayload
|
||||
} from "@/types/FollowUpReminder";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import { compressUploadImageList } from "@/utils/imageCompression";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { parseDateTime } from "@/utils/date";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
name: "FollowUpReminderEdit"
|
||||
});
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
const currentStoreStore = useCurrentStoreStore();
|
||||
const navBarStore = useNavBarStore();
|
||||
|
||||
const routeId = computed(() => String(route.params.id || ""));
|
||||
const isEditMode = computed(() => !!routeId.value);
|
||||
const pageAccess = computed(() => isEditMode.value
|
||||
? permissionCodes.customerFollowUpReminder.update
|
||||
: permissionCodes.customerFollowUpReminder.create);
|
||||
|
||||
// ---------- 表单 ----------
|
||||
|
||||
const isSaving = ref(false);
|
||||
const formModel = reactive({
|
||||
id: "",
|
||||
storeId: "",
|
||||
customerId: "",
|
||||
responsibleUserId: "",
|
||||
content: "",
|
||||
remindAtText: "",
|
||||
notifyChannelList: [] as FollowUpReminderNotifyChannel[]
|
||||
});
|
||||
const selectedCustomer = ref<Customer>();
|
||||
const selectedResponsible = ref<ManagedUser>();
|
||||
const photoItems = ref<PhotoItem[]>([]);
|
||||
const photoUrlList = computed(() => photoItems.value.map(item => item.previewUrl || item.url));
|
||||
const customerSelectorVisible = ref(false);
|
||||
const responsibleSelectorVisible = ref(false);
|
||||
const customerPickerStoreId = computed(() => formModel.storeId || currentStoreStore.currentStoreId);
|
||||
const responsiblePickerStoreId = computed(() => selectedCustomer.value?.storeId || customerPickerStoreId.value);
|
||||
const currentUserId = computed(() => userStore.loginUser.user?.id || userStore.loginUser.id || "");
|
||||
const selectedResponsibleName = computed(() => {
|
||||
if (!selectedResponsible.value) {
|
||||
return "请选择负责人";
|
||||
}
|
||||
if (selectedResponsible.value.userId === currentUserId.value) {
|
||||
return "本人";
|
||||
}
|
||||
return getResponsibleName(selectedResponsible.value);
|
||||
});
|
||||
|
||||
// ---------- 通知方式 ----------
|
||||
|
||||
const hasSmsChannel = computed(() => hasChannel("SMS"));
|
||||
const isTodayReminder = computed(() => {
|
||||
const remindAt = parseRemindAt();
|
||||
if (!remindAt) {
|
||||
return false;
|
||||
}
|
||||
return Time.formatDate(new Date(remindAt)) === Time.formatDate(new Date(Time.now()));
|
||||
});
|
||||
const isBeforeSmsCutoff = computed(() => {
|
||||
const now = new Date(Time.now());
|
||||
return now.getHours() < 8;
|
||||
});
|
||||
const canSelectSms = computed(() => isResponsiblePhoneValid(selectedResponsible.value)
|
||||
&& (!isTodayReminder.value || isBeforeSmsCutoff.value));
|
||||
const smsRuleText = computed(() => {
|
||||
if (!selectedResponsible.value) {
|
||||
return "短信通知要求负责人有有效的已验证手机号。";
|
||||
}
|
||||
if (!isResponsiblePhoneValid(selectedResponsible.value)) {
|
||||
return "当前负责人没有有效的已验证手机号,短信通知不可用。";
|
||||
}
|
||||
if (isTodayReminder.value && !isBeforeSmsCutoff.value) {
|
||||
return "今天 08:00 后创建今天的提醒不能选择短信通知。";
|
||||
}
|
||||
return "短信将在提醒日期 08:00 聚合发送,允许与站内通知同时选择。";
|
||||
});
|
||||
|
||||
function hasChannel(channel: FollowUpReminderNotifyChannel): boolean {
|
||||
return formModel.notifyChannelList.includes(channel);
|
||||
}
|
||||
|
||||
function setChannel(channel: FollowUpReminderNotifyChannel, checked: boolean): void {
|
||||
if (channel === "SMS" && checked && !canSelectSms.value) {
|
||||
Message.warning(smsRuleText.value);
|
||||
return;
|
||||
}
|
||||
const channelSet = new Set(formModel.notifyChannelList);
|
||||
if (checked) {
|
||||
channelSet.add(channel);
|
||||
} else {
|
||||
channelSet.delete(channel);
|
||||
}
|
||||
formModel.notifyChannelList = Array.from(channelSet);
|
||||
}
|
||||
|
||||
function isResponsiblePhoneValid(item?: ManagedUser): boolean {
|
||||
const phone = item?.user?.phoneNo;
|
||||
return Boolean(phone && item?.user?.phoneNoVerified && /^1\d{10}$/.test(phone));
|
||||
}
|
||||
|
||||
function getResponsibleName(item: ManagedUser): string {
|
||||
return item.user?.nick || item.user?.name || item.userId || "未命名负责人";
|
||||
}
|
||||
|
||||
// ---------- 客户和负责人 ----------
|
||||
|
||||
async function handleCustomerChange(customerId: string): Promise<void> {
|
||||
formModel.customerId = customerId;
|
||||
selectedCustomer.value = customerId ? await loadCustomer(customerId) : undefined;
|
||||
formModel.storeId = selectedCustomer.value?.storeId || currentStoreStore.currentStoreId;
|
||||
if (selectedResponsible.value && selectedResponsible.value.storeId !== formModel.storeId) {
|
||||
formModel.responsibleUserId = "";
|
||||
selectedResponsible.value = undefined;
|
||||
setChannel("SMS", false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleResponsibleChange(item: ManagedUser): void {
|
||||
selectedResponsible.value = item;
|
||||
formModel.responsibleUserId = item.userId || "";
|
||||
if (isResponsiblePhoneValid(item) && canSelectSms.value) {
|
||||
setChannel("SMS", true);
|
||||
}
|
||||
}
|
||||
|
||||
function selectCurrentUser(): void {
|
||||
if (!currentUserId.value) {
|
||||
Message.warning("当前登录用户信息不可用");
|
||||
return;
|
||||
}
|
||||
handleResponsibleChange({
|
||||
storeId: responsiblePickerStoreId.value,
|
||||
userId: currentUserId.value,
|
||||
enabled: true,
|
||||
user: userStore.loginUser.user as Partial<User> | undefined
|
||||
});
|
||||
}
|
||||
|
||||
async function loadCustomer(customerId: string): Promise<Customer | undefined> {
|
||||
try {
|
||||
return await CustomerAPI.detail(customerId);
|
||||
} catch {
|
||||
Message.warning("客户详情加载失败");
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 时间 ----------
|
||||
|
||||
type RemindAtPreset = "tomorrow" | "afterTomorrow" | "custom";
|
||||
|
||||
const selectedRemindAtPreset = ref<RemindAtPreset>("tomorrow");
|
||||
const remindAtPickerVisible = ref(false);
|
||||
const remindAtDraftText = ref("");
|
||||
const minimumDateTimeText = computed(() => {
|
||||
const date = new Date(Time.now());
|
||||
date.setSeconds(0, 0);
|
||||
date.setMinutes(date.getMinutes() + 1);
|
||||
return Time.formatDateTime(date);
|
||||
});
|
||||
|
||||
function getQuickRemindAt(dayOffset: number): string {
|
||||
const date = new Date(Time.now());
|
||||
date.setSeconds(0, 0);
|
||||
date.setDate(date.getDate() + dayOffset);
|
||||
return Time.formatDateTime(date);
|
||||
}
|
||||
|
||||
function getQuickRemindDate(dayOffset: number): string {
|
||||
const date = new Date(Time.now());
|
||||
date.setDate(date.getDate() + dayOffset);
|
||||
return Time.formatDate(date);
|
||||
}
|
||||
|
||||
function getRemindAtPreset(value: string): RemindAtPreset {
|
||||
const remindAt = Time.toTimestamp(parseDateTime(value, false));
|
||||
if (!remindAt) {
|
||||
return "tomorrow";
|
||||
}
|
||||
const remindDate = Time.formatDate(new Date(remindAt));
|
||||
if (remindDate === getQuickRemindDate(1)) {
|
||||
return "tomorrow";
|
||||
}
|
||||
if (remindDate === getQuickRemindDate(2)) {
|
||||
return "afterTomorrow";
|
||||
}
|
||||
return "custom";
|
||||
}
|
||||
|
||||
function selectRemindAtPreset(preset: RemindAtPreset): void {
|
||||
selectedRemindAtPreset.value = preset;
|
||||
if (preset === "custom") {
|
||||
openRemindAtPicker();
|
||||
return;
|
||||
}
|
||||
formModel.remindAtText = getQuickRemindAt(preset === "tomorrow" ? 1 : 2);
|
||||
}
|
||||
|
||||
function handleRemindAtPresetChange(value: string | number | boolean): void {
|
||||
if (value !== "tomorrow" && value !== "afterTomorrow" && value !== "custom") {
|
||||
return;
|
||||
}
|
||||
selectRemindAtPreset(value);
|
||||
}
|
||||
|
||||
function openRemindAtPicker(): void {
|
||||
remindAtDraftText.value = formModel.remindAtText || minimumDateTimeText.value;
|
||||
remindAtPickerVisible.value = true;
|
||||
}
|
||||
|
||||
function cancelRemindAtPicker(): void {
|
||||
remindAtPickerVisible.value = false;
|
||||
selectedRemindAtPreset.value = getRemindAtPreset(formModel.remindAtText);
|
||||
}
|
||||
|
||||
function confirmRemindAt(value?: string | number): void {
|
||||
formModel.remindAtText = String(value || remindAtDraftText.value);
|
||||
selectedRemindAtPreset.value = "custom";
|
||||
remindAtPickerVisible.value = false;
|
||||
}
|
||||
|
||||
function parseRemindAt(): number | undefined {
|
||||
if (!formModel.remindAtText) {
|
||||
return undefined;
|
||||
}
|
||||
return Time.toTimestamp(parseDateTime(formModel.remindAtText, false));
|
||||
}
|
||||
|
||||
// ---------- 附件 ----------
|
||||
|
||||
const isUploading = ref(false);
|
||||
|
||||
async function uploadReminderPhotoList(fileList: File[]): Promise<PhotoItem[]> {
|
||||
isUploading.value = true;
|
||||
try {
|
||||
const tempFileList = await AttachmentAPI.upload(await compressUploadImageList(fileList));
|
||||
return tempFileList.flatMap((item, index) => {
|
||||
if (!item.id) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
attachment: {
|
||||
tempFileId: item.id,
|
||||
mimeType: fileList[index]?.type,
|
||||
name: fileList[index]?.name,
|
||||
title: fileList[index] ? getFileTitle(fileList[index].name) : undefined
|
||||
},
|
||||
tempFileId: item.id,
|
||||
attachType: "PHOTO",
|
||||
mimeType: fileList[index]?.type,
|
||||
url: AttachmentAPI.getTempReadURL(item.id || "")
|
||||
}
|
||||
];
|
||||
});
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "附件上传失败"));
|
||||
return [];
|
||||
} finally {
|
||||
isUploading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function getFileTitle(name: string): string {
|
||||
return name.replace(/\.[^.]+$/, "");
|
||||
}
|
||||
|
||||
function getAttachmentURL(item: FollowUpReminderAttachment): string {
|
||||
if (item.id) {
|
||||
return getAttachmentReadURL(item.id);
|
||||
}
|
||||
if (item.tempFileId) {
|
||||
return AttachmentAPI.getTempReadURL(item.tempFileId);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function toPhotoItems(items: readonly FollowUpReminderAttachment[]): PhotoItem[] {
|
||||
const result: PhotoItem[] = [];
|
||||
for (const item of items) {
|
||||
const url = getAttachmentURL(item);
|
||||
if (!url) {
|
||||
continue;
|
||||
}
|
||||
result.push({
|
||||
attachment: item,
|
||||
tempFileId: item.tempFileId,
|
||||
attachType: item.attachType || "PHOTO",
|
||||
url
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function toAttachmentList(items: readonly PhotoItem[]): FollowUpReminderAttachment[] {
|
||||
return items.map(item => ({
|
||||
...(item.attachment || {}),
|
||||
tempFileId: item.tempFileId || item.attachment?.tempFileId,
|
||||
attachType: item.attachType || item.attachment?.attachType || "PHOTO"
|
||||
})).filter(item => !!item.id || !!item.tempFileId);
|
||||
}
|
||||
|
||||
// ---------- 加载和保存 ----------
|
||||
|
||||
async function loadStoreScope(): Promise<void> {
|
||||
if (userStore.hasRoles(gaoRoleCodes.globalManager)) {
|
||||
await currentStoreStore.loadStoreList();
|
||||
formModel.storeId = currentStoreStore.currentStoreId;
|
||||
return;
|
||||
}
|
||||
const store = await currentStoreStore.loadLoginStore();
|
||||
formModel.storeId = store?.id || "";
|
||||
}
|
||||
|
||||
async function loadForm(): Promise<void> {
|
||||
await loadStoreScope();
|
||||
if (!routeId.value) {
|
||||
formModel.notifyChannelList = ["INTERNAL"];
|
||||
const queryCustomerId = String(route.query.customerId || "");
|
||||
if (queryCustomerId) {
|
||||
await handleCustomerChange(queryCustomerId);
|
||||
}
|
||||
selectCurrentUser();
|
||||
formModel.remindAtText = getQuickRemindAt(1);
|
||||
selectedRemindAtPreset.value = "tomorrow";
|
||||
return;
|
||||
}
|
||||
|
||||
const current = await FollowUpReminderAPI.detail(routeId.value);
|
||||
if (current.status !== "PENDING") {
|
||||
Message.warning("已完成的跟进提醒不能修改");
|
||||
await router.replace({ name: "CustomerFollowUpReminderDetail", params: { id: routeId.value } });
|
||||
return;
|
||||
}
|
||||
applyReminder(current);
|
||||
}
|
||||
|
||||
function applyReminder(current: FollowUpReminder): void {
|
||||
Object.assign(formModel, {
|
||||
id: current.id || "",
|
||||
storeId: current.storeId || "",
|
||||
customerId: current.customerId || "",
|
||||
responsibleUserId: current.responsibleUserId || "",
|
||||
content: current.content || "",
|
||||
remindAtText: current.remindAt ? Time.formatDateTime(new Date(current.remindAt)) : minimumDateTimeText.value,
|
||||
notifyChannelList: current.notifyChannelList || buildChannelList(current)
|
||||
});
|
||||
selectedCustomer.value = current.customer;
|
||||
selectedResponsible.value = current.responsibleUserId
|
||||
? {
|
||||
storeId: current.storeId,
|
||||
userId: current.responsibleUserId,
|
||||
enabled: true,
|
||||
user: current.responsibleUser as Partial<User> | undefined
|
||||
}
|
||||
: undefined;
|
||||
photoItems.value = toPhotoItems(current.attachmentList || []);
|
||||
selectedRemindAtPreset.value = getRemindAtPreset(formModel.remindAtText);
|
||||
}
|
||||
|
||||
function buildChannelList(item: FollowUpReminder): FollowUpReminderNotifyChannel[] {
|
||||
const result: FollowUpReminderNotifyChannel[] = [];
|
||||
if (item.internalNotifyEnabled) {
|
||||
result.push("INTERNAL");
|
||||
}
|
||||
if (item.smsNotifyEnabled) {
|
||||
result.push("SMS");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function validateForm(remindAt?: number): boolean {
|
||||
if (!formModel.customerId || !selectedCustomer.value?.id) {
|
||||
Message.warning("请选择客户");
|
||||
return false;
|
||||
}
|
||||
if (!formModel.responsibleUserId || !selectedResponsible.value?.userId) {
|
||||
Message.warning("请选择负责人");
|
||||
return false;
|
||||
}
|
||||
if (!formModel.content.trim()) {
|
||||
Message.warning("请填写跟进内容");
|
||||
return false;
|
||||
}
|
||||
if (!remindAt || !(0 === remindAt % 60000) || !(Time.now() < remindAt)) {
|
||||
Message.warning("请选择晚于当前时间的分钟提醒时间");
|
||||
return false;
|
||||
}
|
||||
if (hasSmsChannel.value && !canSelectSms.value) {
|
||||
Message.warning(smsRuleText.value);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
if (isSaving.value || isUploading.value) {
|
||||
return;
|
||||
}
|
||||
const remindAt = parseRemindAt();
|
||||
if (!validateForm(remindAt)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: FollowUpReminderPayload = {
|
||||
id: formModel.id || undefined,
|
||||
storeId: formModel.storeId || undefined,
|
||||
customerId: formModel.customerId,
|
||||
responsibleUserId: formModel.responsibleUserId,
|
||||
content: formModel.content.trim(),
|
||||
remindAt: remindAt as number,
|
||||
notifyChannelList: [...formModel.notifyChannelList],
|
||||
attachmentList: toAttachmentList(photoItems.value)
|
||||
};
|
||||
|
||||
isSaving.value = true;
|
||||
try {
|
||||
let id = formModel.id;
|
||||
if (isEditMode.value) {
|
||||
await FollowUpReminderAPI.update(payload);
|
||||
} else {
|
||||
id = await FollowUpReminderAPI.create(payload);
|
||||
}
|
||||
Message.success("跟进提醒已保存");
|
||||
await router.replace({ name: "CustomerFollowUpReminderDetail", params: { id } });
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "跟进提醒保存失败"));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.setRightText(isEditMode.value ? "保存" : "提交", "var(--td-brand-color)", save);
|
||||
try {
|
||||
await loadForm();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "跟进提醒加载失败"));
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => navBarStore.clearRight());
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.follow-up-reminder-edit {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding: calc(var(--app-nav-height) + 1rem) 0 4rem;
|
||||
flex-direction: column;
|
||||
|
||||
.form {
|
||||
border-radius: 1rem;
|
||||
|
||||
.customer-picker {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.customer-profile {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.responsible-picker {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.remind-at {
|
||||
|
||||
&:after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.warning {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.tips {
|
||||
margin: 0 2rem;
|
||||
font-size: .875rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.follow-up-reminder-edit {
|
||||
.form {
|
||||
.picker-text {
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
.textarea {
|
||||
background: rgba(15, 23, 42, .72);
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,836 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.customerFollowUpReminder.read" class="follow-up-reminder-list">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="customerSearchKeyword"
|
||||
class="customer"
|
||||
type="search"
|
||||
borderless
|
||||
placeholder="输入客户编码、姓名或拼音"
|
||||
@enter="applyCustomerSearch"
|
||||
@clear="clearCustomer"
|
||||
>
|
||||
<template #suffix-icon>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
content="选择客户"
|
||||
@click.stop="customerSelectorVisible = true"
|
||||
/>
|
||||
</template>
|
||||
</t-input>
|
||||
<t-dropdown-menu ref="dropdownMenuRef" class="menus">
|
||||
<t-dropdown-item
|
||||
v-model="dateFilterType"
|
||||
:label="dateFilterLabel"
|
||||
:options="dateOptions"
|
||||
@change="handleDateFilterChange"
|
||||
/>
|
||||
<t-dropdown-item
|
||||
v-model="statusFilter"
|
||||
:label="statusFilterLabel"
|
||||
:options="statusOptions"
|
||||
@change="handleStatusChange"
|
||||
/>
|
||||
<t-dropdown-item
|
||||
:label="selectedResponsibleName"
|
||||
:options="[]"
|
||||
@open="openResponsibleSelector"
|
||||
/>
|
||||
</t-dropdown-menu>
|
||||
</div>
|
||||
<t-pull-down-refresh
|
||||
v-model="isRefreshing"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="refresh"
|
||||
@scrolltolower="fetch"
|
||||
>
|
||||
<div class="list-wrap">
|
||||
<customer-profile-card class="customer" :customer="selectedCustomer" />
|
||||
<t-cell-group class="summary" theme="card">
|
||||
<t-cell title="提醒数量" :note="`共 ${pageResult.total} 条`" />
|
||||
<t-cell v-if="dateFilterType !== 'all'" title="提醒时间" :note="dateFilterLabel" />
|
||||
<t-cell v-if="selectedResponsibleId" title="负责人" :note="selectedResponsibleName" />
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="pageResult.list.length" class="items fix-last-cell-line empty-cell-title-margin" theme="card">
|
||||
<t-swipe-cell
|
||||
v-for="(item, index) in pageResult.list"
|
||||
:key="item.id || index"
|
||||
class="item"
|
||||
>
|
||||
<t-cell
|
||||
v-entrance-transition="index * 30"
|
||||
class="cell"
|
||||
arrow
|
||||
@click="toDetail(item)"
|
||||
>
|
||||
<template #leftIcon>
|
||||
<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>
|
||||
<div class="center-tips" v-text="isLoading ? '正在加载提醒' : pageResult.list.length ? (isNoMore ? '已经到底了' : '上拉加载更多') : '暂无跟进提醒'" />
|
||||
</div>
|
||||
</t-pull-down-refresh>
|
||||
<customer-selector
|
||||
v-model="selectedCustomerId"
|
||||
v-model:visible="customerSelectorVisible"
|
||||
:initial-keyword="customerSearchKeyword"
|
||||
:store-id="currentStoreStore.currentStoreId"
|
||||
:enable-scan="true"
|
||||
@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"
|
||||
/>
|
||||
</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>
|
||||
<nav-bar-action-menu v-if="canCreate" :actions="actionList" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { DialogPlugin, type DropdownValue } from "tdesign-mobile-vue";
|
||||
import { Time } from "timi-web";
|
||||
import { type PageResult, useUserStore } from "timi-web-api";
|
||||
import { Message } from "@/utils/message";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import FollowUpReminderAPI from "@/api/FollowUpReminderAPI";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import ManagedUserSelector from "@/pages/followUpReminder/component/ManagedUserSelector.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { ManagedUser } from "@/types/ManagedUser";
|
||||
import type { FollowUpReminder, FollowUpReminderPage, FollowUpReminderStatus } from "@/types/FollowUpReminder";
|
||||
import { getCustomerPhotoURL } from "@/utils/customer";
|
||||
import { parseDateTime } from "@/utils/date";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
type DateFilterType = "all" | "today" | "next7" | "custom";
|
||||
|
||||
defineOptions({
|
||||
name: "FollowUpReminderList"
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const userStore = useUserStore();
|
||||
const currentStoreStore = useCurrentStoreStore();
|
||||
const navBarStore = useNavBarStore();
|
||||
|
||||
const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalManager));
|
||||
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.create));
|
||||
const canComplete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.complete));
|
||||
const canDelete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.delete));
|
||||
|
||||
// ---------- 筛选 ----------
|
||||
|
||||
const statusFilter = ref<"" | FollowUpReminderStatus>("");
|
||||
const statusOptions = [
|
||||
{ label: "全部状态", value: "" },
|
||||
{ label: "待完成", value: "PENDING" },
|
||||
{ label: "已完成", value: "COMPLETED" }
|
||||
];
|
||||
const statusFilterLabel = computed(() => statusOptions.find(item => item.value === statusFilter.value)?.label || "全部状态");
|
||||
const dateFilterType = ref<DateFilterType>("all");
|
||||
const dateRange = ref<[string, string]>(["", ""]);
|
||||
const dateOptions = [
|
||||
{ label: "全部时间", value: "all" },
|
||||
{ label: "今天", value: "today" },
|
||||
{ label: "未来 7 天", value: "next7" },
|
||||
{ label: "自定义范围", value: "custom" }
|
||||
];
|
||||
const dateFilterLabel = computed(() => {
|
||||
if (dateFilterType.value === "custom" && dateRange.value[0]) {
|
||||
return `${dateRange.value[0]} 至 ${dateRange.value[1]}`;
|
||||
}
|
||||
return dateOptions.find(item => item.value === dateFilterType.value)?.label || "全部时间";
|
||||
});
|
||||
const selectedCustomerId = ref("");
|
||||
const selectedCustomer = ref<Customer>();
|
||||
const customerSearchKeyword = ref("");
|
||||
const customerSelectorVisible = ref(false);
|
||||
const selectedResponsibleId = ref("");
|
||||
const selectedResponsible = ref<ManagedUser>();
|
||||
const responsibleSelectorVisible = ref(false);
|
||||
const dropdownMenuRef = ref<{ collapseMenu: () => void }>();
|
||||
const selectedResponsibleName = computed(() => selectedResponsible.value
|
||||
? getManagedUserName(selectedResponsible.value)
|
||||
: "全部负责人");
|
||||
const startVisible = ref(false);
|
||||
const endVisible = ref(false);
|
||||
const startDraft = ref("");
|
||||
const endDraft = ref("");
|
||||
|
||||
const actionList = computed(() => [{
|
||||
action: toCreate,
|
||||
icon: "add",
|
||||
key: "create",
|
||||
text: "新增跟进提醒",
|
||||
theme: "primary" as const
|
||||
}]);
|
||||
|
||||
async function handleStatusChange(value: DropdownValue): Promise<void> {
|
||||
if (Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
statusFilter.value = String(value) as "" | FollowUpReminderStatus;
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function handleDateFilterChange(value: DropdownValue): Promise<void> {
|
||||
if (Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
dateFilterType.value = String(value) as DateFilterType;
|
||||
if (dateFilterType.value === "custom") {
|
||||
openStartDate();
|
||||
return;
|
||||
}
|
||||
dateRange.value = buildPresetDateRange(dateFilterType.value);
|
||||
await refresh();
|
||||
}
|
||||
|
||||
function openStartDate(): void {
|
||||
startDraft.value = dateRange.value[0] || `${Time.formatDate(new Date())} 00:00`;
|
||||
startVisible.value = true;
|
||||
}
|
||||
|
||||
function openEndDate(): void {
|
||||
endDraft.value = dateRange.value[1] || `${Time.formatDate(new Date())} 23:59`;
|
||||
endVisible.value = true;
|
||||
}
|
||||
|
||||
function confirmStart(value?: string | number): void {
|
||||
startVisible.value = false;
|
||||
dateRange.value = [String(value || startDraft.value), dateRange.value[1]];
|
||||
openEndDate();
|
||||
}
|
||||
|
||||
async function confirmEnd(value?: string | number): Promise<void> {
|
||||
endVisible.value = false;
|
||||
dateRange.value = [dateRange.value[0], String(value || endDraft.value)];
|
||||
if (dateRange.value[1] < dateRange.value[0]) {
|
||||
dateRange.value = [dateRange.value[1], dateRange.value[0]];
|
||||
}
|
||||
await refresh();
|
||||
}
|
||||
|
||||
function buildPresetDateRange(type: DateFilterType): [string, string] {
|
||||
const begin = new Date();
|
||||
begin.setHours(0, 0, 0, 0);
|
||||
const end = new Date(begin);
|
||||
if (type === "next7") {
|
||||
end.setDate(end.getDate() + 6);
|
||||
}
|
||||
end.setHours(23, 59, 0, 0);
|
||||
return type === "all" ? ["", ""] : [Time.formatDateTime(begin), Time.formatDateTime(end)];
|
||||
}
|
||||
|
||||
async function handleCustomerSelected(id: string): Promise<void> {
|
||||
selectedCustomerId.value = id;
|
||||
selectedCustomer.value = id ? await loadCustomer(id) : undefined;
|
||||
customerSearchKeyword.value = getCustomerSearchKeyword(selectedCustomer.value);
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function applyCustomerSearch(): Promise<void> {
|
||||
const keyword = customerSearchKeyword.value.trim();
|
||||
if (!keyword) {
|
||||
await clearCustomer();
|
||||
return;
|
||||
}
|
||||
if (keyword === getCustomerSearchKeyword(selectedCustomer.value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await CustomerAPI.list({
|
||||
index: 0,
|
||||
size: 20,
|
||||
storeId: currentStoreStore.currentStoreId || undefined,
|
||||
keyword
|
||||
});
|
||||
const customer = result.list?.[0];
|
||||
if (!customer?.id) {
|
||||
Message.warning("未找到匹配客户");
|
||||
return;
|
||||
}
|
||||
if (1 < (result.total || 0)) {
|
||||
Message.warning("匹配到多个客户,请点击选择客户");
|
||||
customerSelectorVisible.value = true;
|
||||
return;
|
||||
}
|
||||
selectedCustomerId.value = customer.id;
|
||||
selectedCustomer.value = customer;
|
||||
customerSearchKeyword.value = getCustomerSearchKeyword(customer);
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "客户信息加载失败"));
|
||||
}
|
||||
}
|
||||
|
||||
function getCustomerSearchKeyword(customer?: Customer): string {
|
||||
return customer?.name?.trim() || customer?.code?.trim() || "";
|
||||
}
|
||||
|
||||
async function clearCustomer(): Promise<void> {
|
||||
selectedCustomerId.value = "";
|
||||
selectedCustomer.value = undefined;
|
||||
customerSearchKeyword.value = "";
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function handleResponsibleSelected(item: ManagedUser): Promise<void> {
|
||||
selectedResponsible.value = item;
|
||||
await refresh();
|
||||
}
|
||||
|
||||
function openResponsibleSelector(): void {
|
||||
dropdownMenuRef.value?.collapseMenu();
|
||||
responsibleSelectorVisible.value = true;
|
||||
}
|
||||
|
||||
// ---------- 列表 ----------
|
||||
|
||||
const isRefreshing = ref(false);
|
||||
const isLoading = ref(false);
|
||||
const isNoMore = ref(false);
|
||||
const pageResult = reactive<PageResult<FollowUpReminder>>({
|
||||
total: 0,
|
||||
list: []
|
||||
});
|
||||
const page = reactive<FollowUpReminderPage>({
|
||||
index: 0,
|
||||
size: 16
|
||||
});
|
||||
let fetchTask: Promise<void> | undefined;
|
||||
|
||||
async function fetch(): Promise<void> {
|
||||
if (isNoMore.value) {
|
||||
return;
|
||||
}
|
||||
if (fetchTask) {
|
||||
await fetchTask;
|
||||
return;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const [beginRemindAt, endRemindAt] = buildDateTimestampRange();
|
||||
const result = await FollowUpReminderAPI.list({
|
||||
...page,
|
||||
storeId: currentStoreStore.currentStoreId || undefined,
|
||||
customerId: selectedCustomerId.value || undefined,
|
||||
responsibleUserId: selectedResponsibleId.value || undefined,
|
||||
status: statusFilter.value || undefined,
|
||||
beginRemindAt,
|
||||
endRemindAt
|
||||
});
|
||||
const list = result.list || [];
|
||||
pageResult.total = result.total || 0;
|
||||
pageResult.list = pageResult.list.concat(list);
|
||||
page.index += 1;
|
||||
isNoMore.value = list.length < page.size || pageResult.list.length >= pageResult.total;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
})();
|
||||
fetchTask = task;
|
||||
try {
|
||||
await task;
|
||||
} finally {
|
||||
if (fetchTask === task) {
|
||||
fetchTask = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
if (fetchTask) {
|
||||
await fetchTask;
|
||||
}
|
||||
isRefreshing.value = true;
|
||||
try {
|
||||
page.index = 0;
|
||||
pageResult.total = 0;
|
||||
pageResult.list = [];
|
||||
isNoMore.value = false;
|
||||
await fetch();
|
||||
} finally {
|
||||
isRefreshing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function buildDateTimestampRange(): [number | undefined, number | undefined] {
|
||||
return [
|
||||
dateRange.value[0] ? Time.toTimestamp(parseDateTime(dateRange.value[0], false)) : undefined,
|
||||
dateRange.value[1] ? Time.toTimestamp(parseDateTime(dateRange.value[1], true)) : undefined
|
||||
];
|
||||
}
|
||||
|
||||
async function loadCustomer(id: string): Promise<Customer | undefined> {
|
||||
try {
|
||||
return await CustomerAPI.detail(id);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStoreScope(): Promise<void> {
|
||||
if (isGlobalManager.value) {
|
||||
await currentStoreStore.loadStoreList();
|
||||
return;
|
||||
}
|
||||
await currentStoreStore.loadLoginStore();
|
||||
}
|
||||
|
||||
// ---------- 展示 ----------
|
||||
|
||||
function getCustomerName(item: FollowUpReminder): string {
|
||||
return item.customer?.name || item.customer?.code || item.customerId || "未命名客户";
|
||||
}
|
||||
|
||||
function getManagedUserName(item: ManagedUser): string {
|
||||
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("");
|
||||
const operatingType = ref<"complete" | "delete">();
|
||||
|
||||
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> {
|
||||
await router.push({
|
||||
name: "CustomerFollowUpReminderCreate",
|
||||
query: selectedCustomerId.value ? { customerId: selectedCustomerId.value } : undefined
|
||||
});
|
||||
}
|
||||
|
||||
async function toDetail(item: FollowUpReminder): Promise<void> {
|
||||
if (item.id) {
|
||||
await router.push({ name: "CustomerFollowUpReminderDetail", params: { id: item.id } });
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.setCustomRightVisible(canCreate.value);
|
||||
try {
|
||||
await loadStoreScope();
|
||||
const queryCustomerId = String(route.query.customerId || "");
|
||||
if (queryCustomerId) {
|
||||
selectedCustomerId.value = queryCustomerId;
|
||||
selectedCustomer.value = await loadCustomer(queryCustomerId);
|
||||
customerSearchKeyword.value = getCustomerSearchKeyword(selectedCustomer.value);
|
||||
}
|
||||
await fetch();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "跟进提醒列表加载失败"));
|
||||
}
|
||||
});
|
||||
|
||||
watch(() => route.query.customerId, async value => {
|
||||
const id = String(value || "");
|
||||
if (id === selectedCustomerId.value) {
|
||||
return;
|
||||
}
|
||||
selectedCustomerId.value = id;
|
||||
selectedCustomer.value = id ? await loadCustomer(id) : undefined;
|
||||
customerSearchKeyword.value = getCustomerSearchKeyword(selectedCustomer.value);
|
||||
await refresh();
|
||||
});
|
||||
|
||||
onUnmounted(() => navBarStore.clearRight());
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.follow-up-reminder-list {
|
||||
padding: var(--app-nav-height) 0 1rem;
|
||||
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
flex-direction: column;
|
||||
|
||||
.customer {
|
||||
--td-button-border-radius: .75rem;
|
||||
--td-input-vertical-padding: .25rem 1rem;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 1;
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
.menus {
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
overflow: hidden;
|
||||
margin-top: -1rem;
|
||||
background: #FFF;
|
||||
border-top: none;
|
||||
padding-top: .8rem;
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.selected-filter {
|
||||
gap: .5rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
overflow: auto;
|
||||
align-items: center;
|
||||
|
||||
:deep(.t-tag) {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.t-button {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
}
|
||||
|
||||
.list-wrap {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.customer {
|
||||
margin: 0 1rem;
|
||||
}
|
||||
|
||||
.items {
|
||||
|
||||
.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) {
|
||||
.follow-up-reminder-list {
|
||||
.filter {
|
||||
background: #10161f;
|
||||
}
|
||||
|
||||
.filter .menus {
|
||||
background: #172033;
|
||||
}
|
||||
|
||||
.summary,
|
||||
.items .item,
|
||||
.items .cell {
|
||||
color: #e2e8f0;
|
||||
background: rgba(30, 41, 59, .9);
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
|
||||
.description .content {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,221 @@
|
||||
<template>
|
||||
<bottom-popup
|
||||
v-model="popupVisible"
|
||||
:title="title"
|
||||
height="80vh"
|
||||
left-button-text="关闭"
|
||||
right-button-text=""
|
||||
@left-button-click="close"
|
||||
>
|
||||
<div class="managed-user-selector">
|
||||
<div class="search-wrap">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="search"
|
||||
borderless
|
||||
clearable
|
||||
placeholder="搜索姓名、昵称或手机号"
|
||||
/>
|
||||
</div>
|
||||
<t-cell-group v-if="filteredUserList.length" class="list">
|
||||
<t-cell
|
||||
v-for="item in filteredUserList"
|
||||
:key="item.id || item.userId"
|
||||
class="item"
|
||||
:class="{ selected: item.userId === modelValue }"
|
||||
:title="getUserName(item)"
|
||||
:description="getUserDescription(item)"
|
||||
@click="select(item)"
|
||||
>
|
||||
<template #leftIcon>
|
||||
<t-image
|
||||
:src="buildUserAvatar(item)"
|
||||
:alt="getUserName(item)"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
/>
|
||||
</template>
|
||||
<template #rightIcon>
|
||||
<t-icon v-if="item.userId === modelValue" name="check" class="selected-icon" />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<div v-else class="center-tips" v-text="loading ? '正在加载负责人' : '暂无可选负责人'" />
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { UserAPI } from "timi-web-api";
|
||||
import ManagedUserAPI from "@/api/ManagedUserAPI";
|
||||
import { buildFallbackAvatar } from "@/utils/avatar";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import type { ManagedUser } from "@/types/ManagedUser";
|
||||
|
||||
interface Props {
|
||||
modelValue: string;
|
||||
visible: boolean;
|
||||
storeId?: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
storeId: "",
|
||||
title: "选择负责人"
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: string];
|
||||
"update:visible": [value: boolean];
|
||||
change: [value: ManagedUser];
|
||||
}>();
|
||||
|
||||
const popupVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: value => emit("update:visible", value)
|
||||
});
|
||||
const keyword = ref("");
|
||||
const loading = ref(false);
|
||||
const userList = ref<ManagedUser[]>([]);
|
||||
|
||||
const filteredUserList = computed(() => {
|
||||
const normalizedKeyword = keyword.value.toLowerCase();
|
||||
return userList.value.filter(item => {
|
||||
const user = item.user;
|
||||
return !normalizedKeyword || [item.userId, user?.name, user?.nick, user?.phoneNo]
|
||||
.some(value => Boolean(value?.toLowerCase().includes(normalizedKeyword)));
|
||||
});
|
||||
});
|
||||
|
||||
function getUserName(item: ManagedUser): string {
|
||||
return item.user?.nick || item.user?.name || item.userId || "未命名用户";
|
||||
}
|
||||
|
||||
function getUserDescription(item: ManagedUser): string {
|
||||
const phone = item.user?.phoneNo || "未填写手机号";
|
||||
const verified = item.user?.phoneNoVerified ? "已验证" : "未验证";
|
||||
return `${phone} · ${verified}`;
|
||||
}
|
||||
|
||||
function buildUserAvatar(item: ManagedUser): string {
|
||||
return UserAPI.getAvatarURL(item.user) || buildFallbackAvatar(getUserName(item), "#0f766e");
|
||||
}
|
||||
|
||||
async function loadUsers(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await ManagedUserAPI.list({
|
||||
index: 0,
|
||||
size: 1000,
|
||||
equalsExample: {
|
||||
storeId: props.storeId || undefined,
|
||||
enabled: true
|
||||
}
|
||||
}, {
|
||||
storeId: props.storeId || undefined
|
||||
});
|
||||
userList.value = result.list || [];
|
||||
} catch (error) {
|
||||
userList.value = [];
|
||||
Message.error(getErrorMessage(error, "负责人列表加载失败"));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function select(item: ManagedUser): void {
|
||||
if (!item.userId) {
|
||||
return;
|
||||
}
|
||||
emit("update:modelValue", item.userId);
|
||||
emit("change", item);
|
||||
emit("update:visible", false);
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit("update:visible", false);
|
||||
}
|
||||
|
||||
watch(() => props.visible, async value => {
|
||||
if (!value) {
|
||||
keyword.value = "";
|
||||
return;
|
||||
}
|
||||
await loadUsers();
|
||||
});
|
||||
|
||||
watch(() => props.storeId, async () => {
|
||||
if (props.visible) {
|
||||
await loadUsers();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.managed-user-selector {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
background: var(--td-bg-color-page, #f5f5f8);
|
||||
|
||||
.search-wrap {
|
||||
padding: .75rem 1rem;
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
}
|
||||
|
||||
.search {
|
||||
--td-input-vertical-padding: 8px 14px;
|
||||
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: .75rem;
|
||||
}
|
||||
|
||||
.item {
|
||||
padding: .25rem 1rem;
|
||||
|
||||
&.selected {
|
||||
background: color-mix(in srgb, var(--td-brand-color) 8%, var(--td-bg-color-container, #fff));
|
||||
}
|
||||
|
||||
.avatar {
|
||||
flex: none;
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
overflow: hidden;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.selected-icon {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.avatar .t-image__img) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.managed-user-selector {
|
||||
background: #10161f;
|
||||
|
||||
.search-wrap,
|
||||
.item {
|
||||
background: rgba(30, 41, 59, .9);
|
||||
}
|
||||
|
||||
.item.selected {
|
||||
background: rgba(37, 99, 235, .2);
|
||||
}
|
||||
|
||||
.search {
|
||||
background: rgba(15, 23, 42, .72);
|
||||
border-color: rgba(148, 163, 184, .16);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -25,30 +25,29 @@
|
||||
<div class="main">
|
||||
<div class="title">
|
||||
<div class="heading">
|
||||
<strong v-text="item.productNameSnapshot || '未命名产品'" />
|
||||
<t-tag v-if="item.gifted" size="small" theme="success" content="赠送" />
|
||||
<span v-text="getItemDescription(item)" />
|
||||
<div class="name-gift">
|
||||
<strong v-text="item.productNameSnapshot || '未命名产品'"/>
|
||||
<t-tag
|
||||
v-if="item.gifted"
|
||||
size="small"
|
||||
theme="primary"
|
||||
content="赠送"
|
||||
/>
|
||||
</div>
|
||||
<span class="can-fulfill" v-text="getItemDescription(item)" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="input">
|
||||
<div
|
||||
v-if="item.skuCodeSnapshot || item.skuSpecSnapshot?.length || item.skuNameSnapshot || item.specSummarySnapshot || item.unitSnapshot"
|
||||
class="sku-tags"
|
||||
>
|
||||
<t-tag
|
||||
v-if="item.skuCodeSnapshot"
|
||||
size="small"
|
||||
theme="primary"
|
||||
variant="light"
|
||||
:content="item.skuCodeSnapshot"
|
||||
/>
|
||||
<product-sku-snapshot-tags
|
||||
<product-sku-tags
|
||||
:product-name="item.productNameSnapshot"
|
||||
:snapshot="item.skuSpecSnapshot"
|
||||
:fallback="item.specSummarySnapshot || item.skuNameSnapshot"
|
||||
:unit="item.unitSnapshot"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="input">
|
||||
<t-input
|
||||
v-model.trim="quantityMap[item.id || '']"
|
||||
class="quantity"
|
||||
@@ -57,6 +56,7 @@
|
||||
align="right"
|
||||
:disabled="!getFulfillmentUnit(item)"
|
||||
placeholder="请输入履约数量"
|
||||
@change="refreshStockPreview"
|
||||
>
|
||||
<template #suffix-icon>
|
||||
<t-button
|
||||
@@ -70,7 +70,7 @@
|
||||
<t-button
|
||||
size="extra-small"
|
||||
variant="outline"
|
||||
:disabled="getAvailableBaseQuantity(item) === '0'"
|
||||
:disabled="getAvailableBaseQuantity(item) === '0' || (directVerify && isStockChecking)"
|
||||
@click.stop="fillAllQuantity(item)"
|
||||
>全部履约</t-button>
|
||||
</div>
|
||||
@@ -79,21 +79,40 @@
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
<div v-else class="empty" v-text="'暂无可履约明细,请返回订单详情检查'" />
|
||||
<t-form class="form" label-align="left" label-width="6rem">
|
||||
<t-form class="form" label-width="7rem">
|
||||
<t-form-item label="履约时间" content-align="right">
|
||||
<div class="time-actions">
|
||||
<t-button
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
size="extra-small"
|
||||
:content="deliveredAtText || '此刻'"
|
||||
@click="pickerVisible = true"
|
||||
@click="openDeliveredAtPicker"
|
||||
/>
|
||||
<t-button
|
||||
v-if="deliveredAtText"
|
||||
theme="primary"
|
||||
variant="text"
|
||||
size="extra-small"
|
||||
content="此刻"
|
||||
@click="resetDeliveredAt"
|
||||
/>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="canDirectVerify" label="直接核销履约" content-align="right">
|
||||
<t-switch v-model="directVerify" size="small" :disabled="isSaving || isStockChecking" />
|
||||
</t-form-item>
|
||||
<t-form-item v-if="directVerify || stockPreviewList.length" label-width="0">
|
||||
<div class="stock-tips">
|
||||
<span v-if="directVerify" class="tips red">直接核销会立即扣减实物库存</span>
|
||||
<product-stock-preview v-if="stockPreviewList.length" :items="stockPreviewList" />
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="备注">
|
||||
<t-textarea v-model="remark" borderless autosize maxlength="500" />
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
v-if="order"
|
||||
:model-value="photoUrlList"
|
||||
v-model:photo-items="photoItems"
|
||||
@@ -105,7 +124,15 @@
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
<t-popup v-model="pickerVisible" placement="bottom">
|
||||
<t-date-time-picker v-model="draftTime" format="YYYY-MM-DD HH:mm" :mode="['date', 'minute']" title="履约时间" @cancel="pickerVisible = false" @confirm="confirmTime" />
|
||||
<t-date-time-picker
|
||||
v-if="pickerVisible"
|
||||
v-model="draftTime"
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
:mode="['date', 'minute']"
|
||||
title="履约时间"
|
||||
@cancel="pickerVisible = false"
|
||||
@confirm="confirmTime"
|
||||
/>
|
||||
</t-popup>
|
||||
<t-popup v-model="unitPickerVisible" placement="bottom">
|
||||
<t-picker v-model="unitPickerDraft" :columns="unitPickerOptions" title="选择实际履约单位" @cancel="unitPickerVisible = false" @confirm="confirmUnitPicker" />
|
||||
@@ -117,19 +144,35 @@
|
||||
import SalesOrderAPI from "@/api/SalesOrderAPI";
|
||||
import FulfillmentAPI from "@/api/FulfillmentAPI";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import ProductSkuSnapshotTags from "@/components/ProductSkuSnapshotTags.vue";
|
||||
import { Time } from "timi-web";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import ProductSkuTags from "@/components/ProductSkuTags.vue";
|
||||
import ProductStockPreview from "@/components/ProductStockPreview.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { Attachment } from "timi-web-api";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import type { GaoOrderFulfillmentItemRequest } from "@/types/Fulfillment";
|
||||
import type { GaoSalesOrderItem, SalesOrder } from "@/types/SalesOrder";
|
||||
import type { ProductSku, ProductSkuUnit } from "@/types/Product";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import type { Attachment } from "timi-web-api";
|
||||
import { comparePackageQuantity, convertPackageQuantity, createPackageRequestNo, getPackageQuantityText, normalizePackageQuantity, toPackageBaseQuantity } from "@/utils/package";
|
||||
import {
|
||||
comparePackageQuantity,
|
||||
convertPackageQuantity,
|
||||
createPackageRequestNo,
|
||||
getPackageQuantityText,
|
||||
normalizePackageQuantity,
|
||||
toPackageBaseQuantity
|
||||
} from "@/utils/package";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||||
import { Message } from "@/utils/message";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
import type { ProductStockPreviewItem } from "@/utils/productStock";
|
||||
import {
|
||||
buildProductStockPreview,
|
||||
getProductStockShortageMessage,
|
||||
mergeProductStockRequirements
|
||||
} from "@/utils/productStock";
|
||||
import { uploadPhotoList } from "@/utils/photo";
|
||||
import { getProductPhotoURL } from "@/utils/product";
|
||||
|
||||
@@ -152,6 +195,10 @@ const photoItems = ref<PhotoItem[]>([]);
|
||||
const unitPickerVisible = ref(false);
|
||||
const unitPickerSourceItemId = ref("");
|
||||
const unitPickerDraft = ref<Array<string | number>>([]);
|
||||
const directVerify = ref(false);
|
||||
const isStockChecking = ref(false);
|
||||
const stockPreviewList = ref<ProductStockPreviewItem[]>([]);
|
||||
let stockCheckToken = 0;
|
||||
const photoUrlList = computed(() => photoItems.value.map(item => item.url));
|
||||
const isPackage = computed(() => order.value?.orderType === "PACKAGE");
|
||||
const expectedItemType = computed(() => isPackage.value ? "PACKAGE_ENTITLEMENT" : "DIRECT_PRODUCT");
|
||||
@@ -159,9 +206,32 @@ const sourceItems = computed<GaoSalesOrderItem[]>(() => (order.value?.itemList |
|
||||
&& 0 < comparePackageQuantity(item.availableBaseQuantity ?? "0", "0")));
|
||||
const unitPickerOptions = computed(() => {
|
||||
const item = sourceItems.value.find(value => value.id === unitPickerSourceItemId.value);
|
||||
return item ? getSellableUnitList(item).map(unit => ({ label: unit.name, value: unit.id || "" })) : [];
|
||||
return item ? getFulfillmentUnitList(item).map(unit => ({ label: unit.name, value: unit.id || "" })) : [];
|
||||
});
|
||||
const canFulfillByPayment = computed(() => order.value?.paymentStatus === "PAID" || userStore.hasRoles(gaoRoleCodes.storeManager));
|
||||
const canDirectVerify = computed(() => userStore.hasRoles(gaoRoleCodes.storeManager)
|
||||
&& userStore.hasPermissions(permissionCodes.orderFulfillment.create)
|
||||
&& userStore.hasPermissions(permissionCodes.orderFulfillment.verify)
|
||||
&& userStore.hasPermissions(permissionCodes.productStock.read));
|
||||
|
||||
watch(directVerify, async value => {
|
||||
stockCheckToken += 1;
|
||||
const token = stockCheckToken;
|
||||
if (!value) {
|
||||
isStockChecking.value = false;
|
||||
return;
|
||||
}
|
||||
isStockChecking.value = true;
|
||||
try {
|
||||
if (!await validateDirectStock() && token === stockCheckToken && directVerify.value) {
|
||||
directVerify.value = false;
|
||||
}
|
||||
} finally {
|
||||
if (token === stockCheckToken) {
|
||||
isStockChecking.value = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function loadData(): Promise<void> {
|
||||
const salesOrderId = String(route.query.salesOrderId || "");
|
||||
@@ -191,8 +261,8 @@ async function loadFulfillmentSkuList(): Promise<void> {
|
||||
if (!item.id || fulfillmentUnitMap[item.id]) {
|
||||
continue;
|
||||
}
|
||||
const originalUnit = getSellableUnitList(item).find(unit => unit.id === item.skuUnitId);
|
||||
const defaultUnit = getFulfillmentUnitForAvailableQuantity(item, originalUnit || getSellableUnitList(item)[0]);
|
||||
const originalUnit = getFulfillmentUnitList(item).find(unit => unit.id === item.skuUnitId);
|
||||
const defaultUnit = getFulfillmentUnitForAvailableQuantity(item, originalUnit || getFulfillmentUnitList(item)[0]);
|
||||
if (defaultUnit?.id) {
|
||||
fulfillmentUnitMap[item.id] = defaultUnit.id;
|
||||
}
|
||||
@@ -222,7 +292,7 @@ function getBaseUnitName(item: GaoSalesOrderItem): string {
|
||||
}
|
||||
|
||||
function getBaseUnit(item: GaoSalesOrderItem): ProductSkuUnit | undefined {
|
||||
return getSellableUnitList(item).find(unit => unit.isBase);
|
||||
return getFulfillmentUnitList(item).find(unit => unit.isBase);
|
||||
}
|
||||
|
||||
function shouldDowngradeUnit(item: GaoSalesOrderItem, unit?: ProductSkuUnit): boolean {
|
||||
@@ -240,7 +310,7 @@ function getFulfillmentUnitForAvailableQuantity(item: GaoSalesOrderItem, unit?:
|
||||
return getBaseUnit(item) || unit;
|
||||
}
|
||||
|
||||
function fillAllQuantity(item: GaoSalesOrderItem): void {
|
||||
async function fillAllQuantity(item: GaoSalesOrderItem): Promise<void> {
|
||||
const unit = getFulfillmentUnit(item);
|
||||
if (!item.id || !unit) {
|
||||
Message.warning("请先选择实际履约单位");
|
||||
@@ -252,14 +322,28 @@ function fillAllQuantity(item: GaoSalesOrderItem): void {
|
||||
return;
|
||||
}
|
||||
quantityMap[item.id] = quantity;
|
||||
await refreshStockPreview();
|
||||
}
|
||||
|
||||
function getSellableUnitList(item: GaoSalesOrderItem): ProductSkuUnit[] {
|
||||
return (item.skuId ? fulfillmentSkuMap[item.skuId]?.unitList : [])?.filter(unit => unit.allowSale !== false && !!unit.id) || [];
|
||||
function getFulfillmentUnitList(item: GaoSalesOrderItem): ProductSkuUnit[] {
|
||||
const unitList = (item.skuId ? fulfillmentSkuMap[item.skuId]?.unitList : [])?.filter(unit => !!unit.id) || [];
|
||||
if (!item.skuUnitId) {
|
||||
return unitList;
|
||||
}
|
||||
const originalUnit: ProductSkuUnit = {
|
||||
...(unitList.find(unit => unit.id === item.skuUnitId) || {}),
|
||||
id: item.skuUnitId,
|
||||
skuId: item.skuId,
|
||||
name: item.unitSnapshot || "成交单位",
|
||||
baseQuantityPerUnit: item.baseQuantityPerUnitSnapshot ?? "1",
|
||||
allowPurchase: false,
|
||||
allowSale: false
|
||||
};
|
||||
return [originalUnit, ...unitList.filter(unit => unit.id !== item.skuUnitId)];
|
||||
}
|
||||
|
||||
function getFulfillmentUnit(item: GaoSalesOrderItem): ProductSkuUnit | undefined {
|
||||
return getSellableUnitList(item).find(unit => unit.id === fulfillmentUnitMap[item.id || ""]);
|
||||
return getFulfillmentUnitList(item).find(unit => unit.id === fulfillmentUnitMap[item.id || ""]);
|
||||
}
|
||||
|
||||
function setFulfillmentUnit(item: GaoSalesOrderItem, unit: ProductSkuUnit): void {
|
||||
@@ -282,24 +366,25 @@ function openUnitPicker(item: GaoSalesOrderItem): void {
|
||||
if (!item.id) {
|
||||
return;
|
||||
}
|
||||
if (!getSellableUnitList(item).length) {
|
||||
Message.warning("当前 SKU 没有可用于履约的销售单位");
|
||||
if (!getFulfillmentUnitList(item).length) {
|
||||
Message.warning("当前 SKU 没有可用于履约的单位");
|
||||
return;
|
||||
}
|
||||
unitPickerSourceItemId.value = item.id;
|
||||
unitPickerDraft.value = [fulfillmentUnitMap[item.id] || getSellableUnitList(item)[0]?.id || ""];
|
||||
unitPickerDraft.value = [fulfillmentUnitMap[item.id] || getFulfillmentUnitList(item)[0]?.id || ""];
|
||||
unitPickerVisible.value = true;
|
||||
}
|
||||
|
||||
function confirmUnitPicker(value: Array<string | number>): void {
|
||||
async function confirmUnitPicker(value: Array<string | number>): Promise<void> {
|
||||
const skuUnitId = String(value[0] || "");
|
||||
const item = sourceItems.value.find(sourceItem => sourceItem.id === unitPickerSourceItemId.value);
|
||||
const selectedUnit = item ? getSellableUnitList(item).find(unit => unit.id === skuUnitId) : undefined;
|
||||
const selectedUnit = item ? getFulfillmentUnitList(item).find(unit => unit.id === skuUnitId) : undefined;
|
||||
const fulfillmentUnit = item ? getFulfillmentUnitForAvailableQuantity(item, selectedUnit) : selectedUnit;
|
||||
if (item?.id && fulfillmentUnit?.id) {
|
||||
setFulfillmentUnit(item, fulfillmentUnit);
|
||||
}
|
||||
unitPickerVisible.value = false;
|
||||
await refreshStockPreview();
|
||||
}
|
||||
|
||||
function confirmTime(value: string | number): void {
|
||||
@@ -307,6 +392,16 @@ function confirmTime(value: string | number): void {
|
||||
pickerVisible.value = false;
|
||||
}
|
||||
|
||||
function openDeliveredAtPicker(): void {
|
||||
draftTime.value = deliveredAtText.value || Time.formatDateTime(new Date());
|
||||
pickerVisible.value = true;
|
||||
}
|
||||
|
||||
function resetDeliveredAt(): void {
|
||||
deliveredAtText.value = "";
|
||||
draftTime.value = "";
|
||||
}
|
||||
|
||||
function resolveTimestamp(value: string): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const timestamp = new Date(value.replace(" ", "T")).getTime();
|
||||
@@ -320,6 +415,86 @@ function buildAttachments(): Partial<Attachment>[] {
|
||||
}] : []);
|
||||
}
|
||||
|
||||
async function validateDirectStock(showShortageMessage = true): Promise<boolean> {
|
||||
stockPreviewList.value = [];
|
||||
const selected = sourceItems.value.filter(item => !!item.id && quantityMap[item.id]);
|
||||
const skuMap = new Map<string, ProductSku>();
|
||||
for (const item of selected) {
|
||||
if (!item.skuId) {
|
||||
continue;
|
||||
}
|
||||
let sku = fulfillmentSkuMap[item.skuId];
|
||||
if (!sku) {
|
||||
try {
|
||||
sku = await ProductAPI.skuDetail(item.skuId);
|
||||
} catch {
|
||||
// 统一在下方提示,避免部分 SKU 查询失败时静默跳过库存校验
|
||||
}
|
||||
}
|
||||
if (!sku) {
|
||||
Message.warning(`${item.productNameSnapshot || "产品"} 的库存信息加载失败,请刷新后重试`);
|
||||
return false;
|
||||
}
|
||||
fulfillmentSkuMap[item.skuId] = sku;
|
||||
skuMap.set(item.skuId, sku);
|
||||
}
|
||||
const requirementList = mergeProductStockRequirements(selected.flatMap(item => {
|
||||
const sku = item.skuId ? skuMap.get(item.skuId) : undefined;
|
||||
const unit = getFulfillmentUnit(item);
|
||||
const quantity = normalizePackageQuantity(quantityMap[item.id || ""] || "");
|
||||
const baseQuantity = quantity && unit ? toPackageBaseQuantity(quantity, unit.baseQuantityPerUnit) : undefined;
|
||||
if (!item.skuId || !sku?.stockEnabled || !baseQuantity) {
|
||||
return [];
|
||||
}
|
||||
return [{ skuId: item.skuId, baseQuantity, productName: item.productNameSnapshot || "未命名产品", unitName: "基础单位", stockEnabled: sku.stockEnabled }];
|
||||
}));
|
||||
if (!requirementList.length) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const stockList = await ProductAPI.stockBatchDetail({ skuIdList: requirementList.map(item => item.skuId) });
|
||||
stockPreviewList.value = buildProductStockPreview(stockList, requirementList);
|
||||
const shortageMessage = getProductStockShortageMessage(stockList, requirementList);
|
||||
if (shortageMessage) {
|
||||
if (showShortageMessage) {
|
||||
Message.warning(`${shortageMessage},不能直接核销履约`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
stockPreviewList.value = [];
|
||||
Message.error(getErrorMessage(error, "库存查询失败,暂不能直接核销履约"));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function previewDirectStock(force = false): Promise<void> {
|
||||
if ((!directVerify.value && !force) || isStockChecking.value) {
|
||||
return;
|
||||
}
|
||||
stockCheckToken += 1;
|
||||
const token = stockCheckToken;
|
||||
const showShortageMessage = directVerify.value;
|
||||
isStockChecking.value = true;
|
||||
try {
|
||||
if (!await validateDirectStock(showShortageMessage) && token === stockCheckToken && directVerify.value) {
|
||||
directVerify.value = false;
|
||||
}
|
||||
} finally {
|
||||
if (token === stockCheckToken) {
|
||||
isStockChecking.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshStockPreview(): Promise<void> {
|
||||
if (!directVerify.value && !stockPreviewList.value.length) {
|
||||
return;
|
||||
}
|
||||
await previewDirectStock(!directVerify.value);
|
||||
}
|
||||
|
||||
function validate(): boolean {
|
||||
if (!order.value?.id) {
|
||||
Message.warning("请从订单详情进入履约创建");
|
||||
@@ -363,7 +538,12 @@ function validate(): boolean {
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
if (isSaving.value || !validate()) return;
|
||||
if (isSaving.value) return;
|
||||
if (isStockChecking.value) {
|
||||
Message.warning("库存正在预检,请稍候再提交");
|
||||
return;
|
||||
}
|
||||
if (!validate()) return;
|
||||
if (!requestNo.value) requestNo.value = createPackageRequestNo();
|
||||
isSaving.value = true;
|
||||
try {
|
||||
@@ -374,15 +554,24 @@ async function save(): Promise<void> {
|
||||
skuUnitId: fulfillmentUnitMap[item.id!]!,
|
||||
quantity: normalizePackageQuantity(quantityMap[item.id || ""])!
|
||||
}));
|
||||
const result = await FulfillmentAPI.create({
|
||||
const request = {
|
||||
salesOrderId: order.value!.id!,
|
||||
requestNo: requestNo.value,
|
||||
deliveredAt: resolveTimestamp(deliveredAtText.value),
|
||||
itemList,
|
||||
attachmentList: buildAttachments(),
|
||||
remark: remark.value.trim() || null
|
||||
});
|
||||
Message.success("履约单已提交");
|
||||
};
|
||||
if (directVerify.value && !await validateDirectStock(true)) {
|
||||
directVerify.value = false;
|
||||
return;
|
||||
}
|
||||
const result = directVerify.value
|
||||
? await FulfillmentAPI.createAndVerify(request)
|
||||
: await FulfillmentAPI.create(request);
|
||||
emitListDataChanged(listDataEventKeys.salesOrderChanged, request.salesOrderId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||||
Message.success(directVerify.value ? "履约单创建并核销成功" : "履约单已提交");
|
||||
await router.replace(`/management/order-fulfillments/${result.id}`);
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "履约单创建失败,重试会复用同一请求号"));
|
||||
@@ -414,9 +603,18 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
min-width: 0;
|
||||
|
||||
:deep(.t-form__controls),
|
||||
:deep(.t-form__controls-content) {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
gap: .5rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
|
||||
.photo {
|
||||
@@ -431,12 +629,14 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
|
||||
.title {
|
||||
gap: .375rem;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -447,26 +647,28 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
|
||||
strong {
|
||||
.name-gift {
|
||||
gap: .5rem;
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
align-items: center;
|
||||
justify-content: start;
|
||||
|
||||
strong {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
span {
|
||||
.can-fulfill {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.sku-tags {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.input {
|
||||
@@ -474,6 +676,13 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
display: flex;
|
||||
margin-top: .5rem;
|
||||
|
||||
.sku-tags {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.unit {
|
||||
font-size: .875rem;
|
||||
}
|
||||
@@ -483,10 +692,15 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
}
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: var(--td-text-color-secondary);
|
||||
padding: 2rem 1rem;
|
||||
text-align: center;
|
||||
.time-actions {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.tips {
|
||||
font-size: .875rem;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -14,9 +14,8 @@
|
||||
<t-cell title="处理人" :note="fulfillment.verifier?.name || fulfillment.verifierUserId || '未处理'" />
|
||||
<t-cell v-if="fulfillment.reason" title="原因" :note="fulfillment.reason" />
|
||||
<t-cell v-if="fulfillment.remark" title="备注" :note="fulfillment.remark" />
|
||||
</t-cell-group>
|
||||
<div class="photos" v-entrance-transition="35">
|
||||
<photo-scroller
|
||||
<div class="photo-wrap bg-white">
|
||||
<media-selector
|
||||
:model-value="fulfillmentPhotoURLList"
|
||||
:photo-items="fulfillmentPhotoItems"
|
||||
:show-add="false"
|
||||
@@ -25,25 +24,13 @@
|
||||
title="履约照片"
|
||||
/>
|
||||
</div>
|
||||
</t-cell-group>
|
||||
<t-cell-group class="items" title="履约明细" theme="card" v-entrance-transition="70">
|
||||
<t-cell
|
||||
class="item"
|
||||
v-for="item in fulfillment.itemList || []"
|
||||
:key="item.id"
|
||||
:title="item.productNameSnapshot || '未命名产品'"
|
||||
>
|
||||
<template #description>
|
||||
<div class="item-description">
|
||||
<t-tag v-if="isGiftedFulfillmentItem(item)" size="small" theme="success" content="赠送" />
|
||||
<product-sku-snapshot-tags
|
||||
:product-name="item.productNameSnapshot"
|
||||
:snapshot="item.skuSpecSnapshot"
|
||||
:fallback="item.specSummarySnapshot || item.skuNameSnapshot || '默认 SKU'"
|
||||
:unit="item.unitSnapshot"
|
||||
/>
|
||||
<span v-text="getFulfillmentQuantityText(item)" />
|
||||
</div>
|
||||
</template>
|
||||
<template #leftIcon>
|
||||
<t-image
|
||||
v-if="getProductPhotoURL(item)"
|
||||
@@ -58,11 +45,35 @@
|
||||
v-text="(item.productNameSnapshot || '产').slice(0, 1)"
|
||||
/>
|
||||
</template>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<span class="clip-text" v-text="item.productNameSnapshot || '未命名产品'" />
|
||||
<t-tag v-if="isGiftedFulfillmentItem(item)" size="small" theme="success" content="赠送" />
|
||||
<product-sku-tags
|
||||
class="tags"
|
||||
:product-name="item.productNameSnapshot"
|
||||
:snapshot="item.skuSpecSnapshot"
|
||||
:fallback="item.specSummarySnapshot || item.skuNameSnapshot || '默认 SKU'"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template #note>
|
||||
<span class="keep-text" v-text="getFulfillmentQuantityText(item)" />
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell v-if="!fulfillment.itemList?.length" title="暂无履约明细" />
|
||||
</t-cell-group>
|
||||
<section
|
||||
v-if="(!isOrderCancelled && isWaitingStock && canVerify) || (!isOrderCancelled && isPending && (canVerify || canCreate)) || (isVerified && canRevoke)"
|
||||
v-if="stockPreviewVisible && (stockPreviewLoading || stockPreviewList.length)"
|
||||
class="stock-preview"
|
||||
v-entrance-transition="105"
|
||||
>
|
||||
<div class="title">库存预览</div>
|
||||
<t-loading v-if="stockPreviewLoading" size="1.5rem" text="加载中" />
|
||||
<product-stock-preview v-else-if="stockPreviewList.length" :items="stockPreviewList" />
|
||||
</section>
|
||||
<section
|
||||
v-if="(!isOrderCancelled && isWaitingStock && (canVerify || canCreate)) || (!isOrderCancelled && isPending && (canVerify || canCreate)) || (isVerified && canRevoke)"
|
||||
class="actions"
|
||||
v-entrance-transition="140"
|
||||
>
|
||||
@@ -77,7 +88,7 @@
|
||||
<t-button theme="danger" content="拒绝履约" @click="openReason('reject')" />
|
||||
</div>
|
||||
<t-button
|
||||
v-if="!isOrderCancelled && isPending && canCreate"
|
||||
v-if="!isOrderCancelled && (isWaitingStock || isPending) && canCreate"
|
||||
theme="default"
|
||||
content="撤销履约"
|
||||
@click="openReason('cancel')"
|
||||
@@ -86,7 +97,7 @@
|
||||
v-if="isVerified && canRevoke"
|
||||
theme="danger"
|
||||
content="履约冲正"
|
||||
@click="openRevoke"
|
||||
@click="revokeVisible = true"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -101,61 +112,39 @@
|
||||
>
|
||||
<t-textarea v-model.trim="reason" borderless autosize placeholder="请输入原因" />
|
||||
</t-dialog>
|
||||
<bottom-popup
|
||||
v-model="revokeVisible"
|
||||
title="履约冲正"
|
||||
left-button-text="取消"
|
||||
right-button-text="提交"
|
||||
@left-button-click="revokeVisible = false"
|
||||
@right-button-click="submitRevoke"
|
||||
>
|
||||
<t-form class="revoke-form">
|
||||
<t-form-item label="冲正原因" required-mark>
|
||||
<t-textarea
|
||||
v-model="revokeReason"
|
||||
borderless
|
||||
autosize
|
||||
<order-fulfillment-revoke
|
||||
v-if="fulfillment"
|
||||
v-model:visible="revokeVisible"
|
||||
:fulfillment="fulfillment"
|
||||
@success="loadData"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="库存退回门店" content-align="right">
|
||||
<t-switch v-model="returnedToStore" />
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<photo-scroller
|
||||
:model-value="photoUrlList"
|
||||
v-model:photo-items="photoItems"
|
||||
:upload="uploadPhotoList"
|
||||
:edit-mode="true"
|
||||
required
|
||||
title="冲正凭证照片"
|
||||
/>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</bottom-popup>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { PassTimeLabel } from "timi-web";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import FulfillmentAPI from "@/api/FulfillmentAPI";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import SalesOrderAPI from "@/api/SalesOrderAPI";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import ProductSkuSnapshotTags from "@/components/ProductSkuSnapshotTags.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import ProductSkuTags from "@/components/ProductSkuTags.vue";
|
||||
import ProductStockPreview from "@/components/ProductStockPreview.vue";
|
||||
import OrderFulfillmentRevoke from "@/pages/fulfillment/components/OrderFulfillmentRevoke.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { OrderFulfillment, OrderFulfillmentItem } from "@/types/Fulfillment";
|
||||
import type { GaoSalesOrderItemType, SalesOrder } from "@/types/SalesOrder";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import type { Attachment } from "timi-web-api";
|
||||
import { createPackageRequestNo, getPackageQuantityText } from "@/utils/package";
|
||||
import { addPackageQuantity, getPackageQuantityText } from "@/utils/package";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||||
import { getProductPhotoURL } from "@/utils/product";
|
||||
import { getFulfillmentStatusText, getSalesOrderItemTypeText, getStatusTheme } from "@/utils/salesOrder";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { uploadPhotoList } from "@/utils/photo";
|
||||
import type { ProductStockPreviewItem } from "@/utils/productStock";
|
||||
import { buildProductStockPreview, mergeProductStockRequirements } from "@/utils/productStock";
|
||||
|
||||
type ReasonAction = "reject" | "cancel";
|
||||
defineOptions({ name: "OrderFulfillmentDetail" });
|
||||
@@ -171,11 +160,8 @@ const reasonVisible = ref(false);
|
||||
const reasonAction = ref<ReasonAction>("reject");
|
||||
const reason = ref("");
|
||||
const revokeVisible = ref(false);
|
||||
const revokeReason = ref("");
|
||||
const returnedToStore = ref(true);
|
||||
const revokeRequestNo = ref("");
|
||||
const photoItems = ref<PhotoItem[]>([]);
|
||||
const photoUrlList = computed(() => photoItems.value.map(item => item.url));
|
||||
const stockPreviewList = ref<ProductStockPreviewItem[]>([]);
|
||||
const stockPreviewLoading = ref(false);
|
||||
const fulfillmentPhotoItems = computed<PhotoItem[]>(() => (fulfillment.value?.attachmentList || [])
|
||||
.filter(item => !!item.id)
|
||||
.map(item => ({
|
||||
@@ -192,19 +178,92 @@ const isOrderCancelled = computed(() => order.value?.status === "CANCELLED");
|
||||
const canVerify = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.verify));
|
||||
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.create));
|
||||
const canRevoke = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.revoke));
|
||||
const stockPreviewVisible = computed(() => (isWaitingStock.value || isPending.value)
|
||||
&& userStore.hasPermissions(permissionCodes.product.read)
|
||||
&& userStore.hasPermissions(permissionCodes.productStock.read));
|
||||
const sourceItemType = computed<GaoSalesOrderItemType | undefined>(() => {
|
||||
const sourceOrderItemId = fulfillment.value?.itemList?.[0]?.sourceOrderItemId;
|
||||
return order.value?.itemList?.find(item => item.id === sourceOrderItemId)?.itemType;
|
||||
});
|
||||
|
||||
function getFulfillmentQuantityText(item: OrderFulfillmentItem): string {
|
||||
return `履约数量 ${getPackageQuantityText(item.quantity)} ${item.unitSnapshot || "单位"}`;
|
||||
return `${getPackageQuantityText(item.quantity)} ${item.unitSnapshot || "单位"}`;
|
||||
}
|
||||
|
||||
function isGiftedFulfillmentItem(item: OrderFulfillmentItem): boolean {
|
||||
return Boolean(order.value?.itemList?.find(orderItem => orderItem.id === item.sourceOrderItemId)?.gifted);
|
||||
}
|
||||
|
||||
const stockEnabledCache = new Map<string, Promise<boolean | null>>();
|
||||
|
||||
function loadStockEnabled(skuId: string): Promise<boolean | null> {
|
||||
const cached = stockEnabledCache.get(skuId);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const request = (async () => {
|
||||
try {
|
||||
const sku = await ProductAPI.skuDetail(skuId);
|
||||
return sku.stockEnabled;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
stockEnabledCache.set(skuId, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
async function loadStockPreview(target: OrderFulfillment): Promise<void> {
|
||||
stockPreviewList.value = [];
|
||||
if (!stockPreviewVisible.value) {
|
||||
return;
|
||||
}
|
||||
stockPreviewLoading.value = true;
|
||||
try {
|
||||
const requirementList = mergeProductStockRequirements((await Promise.all((target.itemList || []).map(async item => {
|
||||
if (!item.skuId || item.baseQuantity === undefined || item.baseQuantity === null) {
|
||||
return undefined;
|
||||
}
|
||||
const stockEnabled = await loadStockEnabled(item.skuId);
|
||||
if (stockEnabled === null) {
|
||||
throw new Error(`${item.productNameSnapshot || "产品"} 的库存信息加载失败`);
|
||||
}
|
||||
if (!stockEnabled) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
skuId: item.skuId,
|
||||
baseQuantity: getPackageQuantityText(item.baseQuantity),
|
||||
productName: item.productNameSnapshot || "未命名产品",
|
||||
unitName: "基础单位",
|
||||
stockEnabled
|
||||
};
|
||||
}))).filter((item): item is NonNullable<typeof item> => !!item));
|
||||
if (!requirementList.length) {
|
||||
return;
|
||||
}
|
||||
const stockList = await ProductAPI.stockBatchDetail({ skuIdList: requirementList.map(item => item.skuId) });
|
||||
const ownReservationMap = new Map(requirementList.map(item => [item.skuId, item.baseQuantity]));
|
||||
const previewStockList = target.status === "PENDING"
|
||||
? stockList.map(stock => {
|
||||
const ownReservation = ownReservationMap.get(stock.skuId || "");
|
||||
if (!ownReservation) {
|
||||
return stock;
|
||||
}
|
||||
return {
|
||||
...stock,
|
||||
availableQuantity: addPackageQuantity(stock.availableQuantity ?? "0", ownReservation) || stock.availableQuantity
|
||||
};
|
||||
})
|
||||
: stockList;
|
||||
stockPreviewList.value = buildProductStockPreview(previewStockList, requirementList);
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "库存预览加载失败"));
|
||||
} finally {
|
||||
stockPreviewLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadData(): Promise<void> {
|
||||
const id = String(route.params.id || "");
|
||||
if (!id) return;
|
||||
@@ -215,6 +274,7 @@ async function loadData(): Promise<void> {
|
||||
order.value = result.salesOrderId && userStore.hasPermissions(permissionCodes.salesOrder.read)
|
||||
? await SalesOrderAPI.detail(result.salesOrderId)
|
||||
: undefined;
|
||||
await loadStockPreview(result);
|
||||
}
|
||||
catch (error) { Message.error(getErrorMessage(error, "履约单加载失败")); }
|
||||
finally { loading.value = false; }
|
||||
@@ -243,6 +303,8 @@ async function prepareStock(): Promise<void> {
|
||||
operating.value = true;
|
||||
try {
|
||||
fulfillment.value = await FulfillmentAPI.prepareStock({ fulfillmentId: fulfillment.value.id, reason: "库存已备齐" });
|
||||
emitListDataChanged(listDataEventKeys.salesOrderChanged, fulfillment.value.salesOrderId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||||
Message.success("库存准备已提交");
|
||||
await loadData();
|
||||
} catch (error) { Message.error(getErrorMessage(error, "库存准备失败")); }
|
||||
@@ -254,6 +316,8 @@ async function verify(): Promise<void> {
|
||||
operating.value = true;
|
||||
try {
|
||||
fulfillment.value = await FulfillmentAPI.verify({ fulfillmentId: fulfillment.value.id, reason: "" });
|
||||
emitListDataChanged(listDataEventKeys.salesOrderChanged, fulfillment.value.salesOrderId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||||
Message.success("履约已核销");
|
||||
await loadData();
|
||||
} catch (error) { Message.error(getErrorMessage(error, "履约核销失败")); }
|
||||
@@ -268,35 +332,14 @@ async function submitReason(): Promise<void> {
|
||||
fulfillment.value = reasonAction.value === "reject"
|
||||
? await FulfillmentAPI.reject(payload)
|
||||
: await FulfillmentAPI.cancel(payload);
|
||||
emitListDataChanged(listDataEventKeys.salesOrderChanged, fulfillment.value.salesOrderId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||||
reasonVisible.value = false;
|
||||
Message.success(reasonAction.value === "reject" ? "履约已拒绝" : "履约已撤销");
|
||||
await loadData();
|
||||
} catch (error) { Message.error(getErrorMessage(error, "履约状态操作失败")); }
|
||||
finally { operating.value = false; }
|
||||
}
|
||||
function openRevoke(): void { revokeReason.value = ""; returnedToStore.value = true; revokeRequestNo.value = ""; photoItems.value = []; revokeVisible.value = true; }
|
||||
function buildAttachments(): Partial<Attachment>[] {
|
||||
return photoItems.value.flatMap(item => item.tempFileId ? [{ tempFileId: item.tempFileId, attachType: "PHOTO" }] : []);
|
||||
}
|
||||
async function submitRevoke(): Promise<void> {
|
||||
if (!fulfillment.value?.id || !revokeReason.value || operating.value) return;
|
||||
if (fulfillment.value.stockRecordList?.length && !buildAttachments().length) { Message.warning("实物履约冲正必须上传退回照片"); return; }
|
||||
if (!revokeRequestNo.value) revokeRequestNo.value = createPackageRequestNo();
|
||||
operating.value = true;
|
||||
try {
|
||||
fulfillment.value = await FulfillmentAPI.revoke({
|
||||
fulfillmentId: fulfillment.value.id,
|
||||
requestNo: revokeRequestNo.value,
|
||||
reason: revokeReason.value.trim(),
|
||||
returnedToStore: returnedToStore.value,
|
||||
attachmentList: buildAttachments()
|
||||
});
|
||||
revokeVisible.value = false;
|
||||
Message.success("履约单已冲正");
|
||||
await loadData();
|
||||
} catch (error) { Message.error(getErrorMessage(error, "履约冲正失败,重试会复用同一请求号")); }
|
||||
finally { operating.value = false; }
|
||||
}
|
||||
onMounted(loadData);
|
||||
onUnmounted(() => navBarStore.clearRight());
|
||||
</script>
|
||||
@@ -308,6 +351,59 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.photo-wrap {
|
||||
padding: .75rem 1rem;
|
||||
}
|
||||
|
||||
.items {
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
|
||||
:deep(.t-cell__title) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border-radius: .5rem !important;
|
||||
}
|
||||
|
||||
.title {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
|
||||
.tags {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.stock-preview {
|
||||
margin: 0 1rem;
|
||||
padding: 1rem .5rem .75rem;
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
border-radius: 1.25rem;
|
||||
|
||||
.title {
|
||||
padding: 0 .5rem .5rem;
|
||||
font-size: .875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
:deep(.t-loading) {
|
||||
justify-content: center;
|
||||
padding: 1rem 0;
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
--td-button-border-radius: 1rem;
|
||||
|
||||
@@ -330,36 +426,6 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
|
||||
.t-button { flex: 1 1 auto; }
|
||||
}
|
||||
|
||||
.photos {
|
||||
margin: 0 1rem;
|
||||
padding: 1rem;
|
||||
background: var(--td-bg-color-container, #fff);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
border-radius: 1.25rem;
|
||||
}
|
||||
|
||||
.items {
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
|
||||
.item-description {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.revoke-form {
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.orderFulfillment.read" class="fulfillment-list">
|
||||
<div class="filters">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
class="customer"
|
||||
v-model.trim="customerSearchKeyword"
|
||||
@@ -31,13 +31,18 @@
|
||||
</div>
|
||||
</template>
|
||||
</t-input>
|
||||
<t-dropdown-menu class="menus">
|
||||
<t-dropdown-menu ref="filterMenuRef" class="menus">
|
||||
<t-dropdown-item
|
||||
v-model="dateFilterType"
|
||||
:label="dateFilterLabel"
|
||||
:options="dateOptions"
|
||||
@change="selectDateFilter"
|
||||
/>
|
||||
<t-dropdown-item
|
||||
:label="skuFilterLabel"
|
||||
:options="[]"
|
||||
@open="openSkuFilter"
|
||||
/>
|
||||
<t-dropdown-item
|
||||
v-model="status"
|
||||
label="履约状态"
|
||||
@@ -53,6 +58,35 @@
|
||||
@scrolltolower="loadMore"
|
||||
>
|
||||
<div class="list-wrap">
|
||||
<t-cell-group v-if="salesOrder || selectedSkuOptionList.length" class="filter-info" theme="card">
|
||||
<template v-if="salesOrder">
|
||||
<t-cell title="订单号" :note="salesOrder.orderNo || salesOrder.id || '未知订单'" />
|
||||
<t-cell title="订单类型" :note="getSalesOrderTypeText(salesOrder.orderType)" />
|
||||
<t-cell title="订单状态">
|
||||
<template #note>
|
||||
<t-tag
|
||||
:content="getSalesOrderStatusText(salesOrder.status)"
|
||||
:theme="getStatusTheme(salesOrder.status)"
|
||||
variant="light-outline"
|
||||
/>
|
||||
</template>
|
||||
</t-cell>
|
||||
</template>
|
||||
<t-cell v-if="selectedSkuOptionList.length" class="sku-filter-cell" title="已筛选 SKU">
|
||||
<template #note>
|
||||
<div class="selected-sku-list">
|
||||
<t-tag
|
||||
v-for="sku in selectedSkuOptionList"
|
||||
:key="sku.skuId"
|
||||
size="small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
:content="formatSelectedSkuName(sku.productName, sku.skuName)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="isCustomDate" class="date-summary" theme="card">
|
||||
<t-cell
|
||||
title="开始时间"
|
||||
@@ -83,6 +117,12 @@
|
||||
</t-pull-down-refresh>
|
||||
</div>
|
||||
<nav-bar-action-menu v-if="canCreate" :actions="actions" />
|
||||
<sku-filter-popup
|
||||
v-model="skuFilterVisible"
|
||||
:sku-id-list="selectedSkuIdList"
|
||||
@options-loaded="handleSkuFilterOptionsLoaded"
|
||||
@confirm="confirmSkuFilter"
|
||||
/>
|
||||
<customer-selector
|
||||
v-model="customerId"
|
||||
v-model:visible="customerSelectorVisible"
|
||||
@@ -120,21 +160,27 @@ import { Time } from "timi-web";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import FulfillmentAPI from "@/api/FulfillmentAPI";
|
||||
import SalesOrderAPI from "@/api/SalesOrderAPI";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import NavBarActionMenu from "@/components/NavBarActionMenu.vue";
|
||||
import OrderFulfillmentListCell from "@/pages/fulfillment/components/OrderFulfillmentListCell.vue";
|
||||
import SkuFilterPopup from "@/pages/fulfillment/components/SkuFilterPopup.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { GaoFulfillmentStatus, OrderFulfillment } from "@/types/Fulfillment";
|
||||
import type { NavBarAction } from "@/types/NavBarAction";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { SalesOrder } from "@/types/SalesOrder";
|
||||
import { buildPresetDateRange, parseDateFilterType, parseDateTime } from "@/utils/date";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { getSalesOrderStatusText, getSalesOrderTypeText, getStatusTheme } from "@/utils/salesOrder";
|
||||
|
||||
defineOptions({ name: "OrderFulfillmentList" });
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const filterMenuRef = ref<{ collapseMenu: () => void }>();
|
||||
const navBarStore = useNavBarStore();
|
||||
const userStore = useUserStore();
|
||||
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.create));
|
||||
@@ -154,11 +200,12 @@ const actions = computed<NavBarAction[]>(() => [
|
||||
action: toPackageOrderList
|
||||
}
|
||||
]);
|
||||
type DateFilterType = "today" | "yesterday" | "lastWeek" | "thisMonth" | "lastMonth" | "all" | "custom";
|
||||
type DateFilterType = "today" | "yesterday" | "thisWeek" | "thisMonth" | "lastMonth" | "all" | "custom";
|
||||
type SkuFilterOption = { skuId: string; productName: string; skuName: string };
|
||||
const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
{ label: "今天", value: "today" },
|
||||
{ label: "昨天", value: "yesterday" },
|
||||
{ label: "上周", value: "lastWeek" },
|
||||
{ label: "本周", value: "thisWeek" },
|
||||
{ label: "本月", value: "thisMonth" },
|
||||
{ label: "上个月", value: "lastMonth" },
|
||||
{ label: "全部", value: "all" },
|
||||
@@ -166,10 +213,14 @@ const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
];
|
||||
|
||||
const customerId = ref(getQueryText(route.query.customerId));
|
||||
const selectedSkuIdList = ref(getSkuIdList(route.query.skuIds));
|
||||
const selectedCustomer = ref<Customer>();
|
||||
const salesOrder = ref<SalesOrder>();
|
||||
const skuFilterOptionList = ref<SkuFilterOption[]>([]);
|
||||
const skuFilterVisible = ref(false);
|
||||
const customerSelectorVisible = ref(false);
|
||||
const customerSearchKeyword = ref("");
|
||||
const dateFilterType = ref<DateFilterType>(parseDateFilterType(route.query.dateType));
|
||||
const dateFilterType = ref<DateFilterType>(parseDateFilterType(getQueryText(route.query.dateType), dateOptions, "all"));
|
||||
const dateRange = ref<[string, string]>(parseDateRange(dateFilterType.value));
|
||||
const startDraft = ref("");
|
||||
const endDraft = ref("");
|
||||
@@ -193,12 +244,27 @@ const statusOptions = [
|
||||
{ label: "已冲正", value: "REVOKED" }
|
||||
];
|
||||
const dateFilterLabel = computed(() => dateOptions.find(item => item.value === dateFilterType.value)?.label || "时间范围");
|
||||
const selectedSkuOptionList = computed(() => {
|
||||
const optionMap = new Map(skuFilterOptionList.value.map(option => [option.skuId, option]));
|
||||
return selectedSkuIdList.value
|
||||
.map(skuId => optionMap.get(skuId))
|
||||
.filter((option): option is SkuFilterOption => !!option);
|
||||
});
|
||||
const skuFilterLabel = computed(() => selectedSkuIdList.value.length ? `SKU (${selectedSkuIdList.value.length})` : "产品 SKU");
|
||||
const isCustomDate = computed(() => dateFilterType.value === "custom");
|
||||
|
||||
function getQueryText(value: unknown): string {
|
||||
return Array.isArray(value) ? "" : typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function getSkuIdList(value: unknown): string[] {
|
||||
const queryValueList = Array.isArray(value) ? value : [value];
|
||||
return [...new Set(queryValueList
|
||||
.flatMap(item => typeof item === "string" ? item.split(",") : [])
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean))];
|
||||
}
|
||||
|
||||
function getInitialStatus(value: unknown): "ALL" | GaoFulfillmentStatus {
|
||||
const statusValue = getQueryText(value);
|
||||
if (["WAITING_STOCK", "PENDING", "VERIFIED", "REJECTED", "CANCELLED", "REVOKED"].includes(statusValue)) {
|
||||
@@ -207,14 +273,9 @@ function getInitialStatus(value: unknown): "ALL" | GaoFulfillmentStatus {
|
||||
return "ALL";
|
||||
}
|
||||
|
||||
function parseDateFilterType(value: unknown): DateFilterType {
|
||||
const dateFilter = getQueryText(value);
|
||||
return dateOptions.some(item => item.value === dateFilter) ? dateFilter as DateFilterType : "today";
|
||||
}
|
||||
|
||||
function parseDateRange(type: DateFilterType): [string, string] {
|
||||
if (type !== "custom") {
|
||||
return buildPresetRange(type);
|
||||
return buildPresetDateRange(type);
|
||||
}
|
||||
return [getQueryText(route.query.beginAt), getQueryText(route.query.endAt)];
|
||||
}
|
||||
@@ -237,6 +298,7 @@ async function fetchList(reset: boolean): Promise<void> {
|
||||
size: pageSize,
|
||||
salesOrderId: getQueryText(route.query.salesOrderId) || undefined,
|
||||
customerId: customerId.value || undefined,
|
||||
skuIdList: selectedSkuIdList.value.length ? selectedSkuIdList.value : undefined,
|
||||
beginAt,
|
||||
endAt,
|
||||
status: status.value === "ALL" ? undefined : status.value
|
||||
@@ -284,6 +346,29 @@ async function selectStatus(value: DropdownValue): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function openSkuFilter(): Promise<void> {
|
||||
skuFilterVisible.value = true;
|
||||
await nextTick();
|
||||
filterMenuRef.value?.collapseMenu();
|
||||
}
|
||||
|
||||
function handleSkuFilterOptionsLoaded(optionList: SkuFilterOption[]): void {
|
||||
skuFilterOptionList.value = optionList;
|
||||
}
|
||||
|
||||
async function confirmSkuFilter(skuIdList: string[]): Promise<void> {
|
||||
selectedSkuIdList.value = skuIdList;
|
||||
await replaceFilterQuery();
|
||||
await reloadList();
|
||||
}
|
||||
|
||||
function formatSelectedSkuName(productName: string, skuName: string) {
|
||||
if (productName === skuName) {
|
||||
return productName;
|
||||
}
|
||||
return `${productName}(${skuName})`;
|
||||
}
|
||||
|
||||
async function handleCustomerChange(value: string | string[]): Promise<void> {
|
||||
customerId.value = Array.isArray(value) ? String(value[0] || "") : value;
|
||||
try {
|
||||
@@ -331,13 +416,27 @@ async function clearCustomer(): Promise<void> {
|
||||
await reloadList();
|
||||
}
|
||||
|
||||
async function loadSalesOrder(): Promise<void> {
|
||||
const salesOrderId = getQueryText(route.query.salesOrderId);
|
||||
if (!salesOrderId) {
|
||||
salesOrder.value = undefined;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
salesOrder.value = await SalesOrderAPI.detail(salesOrderId);
|
||||
} catch (error) {
|
||||
salesOrder.value = undefined;
|
||||
Message.error(getErrorMessage(error, "订单信息加载失败"));
|
||||
}
|
||||
}
|
||||
|
||||
async function selectDateFilter(value: DropdownValue): Promise<void> {
|
||||
if (Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
dateFilterType.value = String(value) as DateFilterType;
|
||||
if (dateFilterType.value !== "custom") {
|
||||
dateRange.value = buildPresetRange(dateFilterType.value);
|
||||
dateRange.value = buildPresetDateRange(dateFilterType.value);
|
||||
await replaceFilterQuery();
|
||||
await reloadList();
|
||||
} else {
|
||||
@@ -390,6 +489,7 @@ function buildFilterQuery(transitionDepth = getQueryText(route.query.transitionD
|
||||
const query = {
|
||||
salesOrderId: getQueryText(route.query.salesOrderId),
|
||||
customerId: customerId.value,
|
||||
skuIds: selectedSkuIdList.value.join(","),
|
||||
dateType: dateFilterType.value,
|
||||
beginAt: dateRange.value[0] || "",
|
||||
endAt: dateRange.value[1] || "",
|
||||
@@ -413,45 +513,6 @@ function isValidTransitionDepth(value: string): boolean {
|
||||
return value !== "" && Number.isInteger(depth) && 0 <= depth && depth <= 20;
|
||||
}
|
||||
|
||||
function buildPresetRange(type: Exclude<DateFilterType, "custom">): [string, string] {
|
||||
if (type === "all") {
|
||||
return ["", ""];
|
||||
}
|
||||
if (type === "lastWeek") {
|
||||
const current = new Date();
|
||||
current.setHours(0, 0, 0, 0);
|
||||
const day = current.getDay() || 7;
|
||||
const thisWeekMonday = new Date(current);
|
||||
thisWeekMonday.setDate(current.getDate() - day + 1);
|
||||
const lastWeekMonday = new Date(thisWeekMonday);
|
||||
lastWeekMonday.setDate(thisWeekMonday.getDate() - 7);
|
||||
const lastWeekSunday = new Date(thisWeekMonday);
|
||||
lastWeekSunday.setDate(thisWeekMonday.getDate() - 1);
|
||||
return [`${Time.formatDate(lastWeekMonday)} 00:00`, `${Time.formatDate(lastWeekSunday)} 23:59`];
|
||||
}
|
||||
if (type === "thisMonth") {
|
||||
const current = new Date();
|
||||
const begin = new Date(current.getFullYear(), current.getMonth(), 1);
|
||||
return [`${Time.formatDate(begin)} 00:00`, `${Time.formatDate(current)} 23:59`];
|
||||
}
|
||||
if (type === "lastMonth") {
|
||||
const current = new Date();
|
||||
const begin = new Date(current.getFullYear(), current.getMonth() - 1, 1);
|
||||
const end = new Date(current.getFullYear(), current.getMonth(), 0);
|
||||
return [`${Time.formatDate(begin)} 00:00`, `${Time.formatDate(end)} 23:59`];
|
||||
}
|
||||
|
||||
const offsetMap: Record<Exclude<DateFilterType, "all" | "custom" | "lastWeek" | "thisMonth" | "lastMonth">, number> = {
|
||||
today: 0,
|
||||
yesterday: 1
|
||||
};
|
||||
const date = new Date();
|
||||
date.setHours(0, 0, 0, 0);
|
||||
date.setDate(date.getDate() - offsetMap[type]);
|
||||
const value = `${Time.formatDate(date)} 00:00`;
|
||||
return [value, `${Time.formatDate(date)} 23:59`];
|
||||
}
|
||||
|
||||
function buildUnixRange(): [number | undefined, number | undefined] {
|
||||
if (dateFilterType.value === "all") {
|
||||
return [0, Time.toTimestamp(new Date())];
|
||||
@@ -462,16 +523,6 @@ function buildUnixRange(): [number | undefined, number | undefined] {
|
||||
];
|
||||
}
|
||||
|
||||
function parseDateTime(value: string, isEnd: boolean): Date {
|
||||
if (!value) {
|
||||
return isEnd ? new Date() : new Date(0);
|
||||
}
|
||||
const [dateText, timeText = isEnd ? "23:59" : "00:00"] = value.split(" ");
|
||||
const [year, month, day] = dateText.split("-").map(Number);
|
||||
const [hour, minute] = timeText.split(":").map(Number);
|
||||
return new Date(year, month - 1, day, hour || 0, minute || 0, isEnd ? 59 : 0, 0);
|
||||
}
|
||||
|
||||
async function toDetail(item: OrderFulfillment): Promise<void> {
|
||||
if (item.id) {
|
||||
await router.push({
|
||||
@@ -513,6 +564,7 @@ onMounted(async () => {
|
||||
navBarStore.clearRight();
|
||||
navBarStore.setCustomRightVisible(canCreate.value);
|
||||
try {
|
||||
await loadSalesOrder();
|
||||
if (customerId.value) {
|
||||
selectedCustomer.value = await CustomerAPI.detail(customerId.value);
|
||||
customerSearchKeyword.value = getCustomerSearchKeyword(selectedCustomer.value);
|
||||
@@ -538,8 +590,6 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: #F5F5F8;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
flex-direction: column;
|
||||
|
||||
.customer {
|
||||
@@ -547,7 +597,7 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
background: var(--td-bg-color-container);
|
||||
z-index: 1;
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
|
||||
@@ -564,11 +614,9 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
z-index: -1;
|
||||
border: 1px solid var(--td-component-border);
|
||||
overflow: hidden;
|
||||
margin-top: -1rem;
|
||||
background: #fff;
|
||||
border-top: none;
|
||||
padding-top: .8rem;
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
@@ -579,9 +627,44 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
.list-wrap {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding-top: 1rem;
|
||||
flex-direction: column;
|
||||
|
||||
.filter-info {
|
||||
.selected-sku-list {
|
||||
gap: .4rem;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
justify-content: flex-start;
|
||||
white-space: nowrap;
|
||||
touch-action: pan-x;
|
||||
scrollbar-width: none;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:deep(.t-tag) {
|
||||
flex: none;
|
||||
}
|
||||
}
|
||||
|
||||
.sku-filter-cell {
|
||||
:deep(.t-cell__title) {
|
||||
flex: 0 0 5rem;
|
||||
}
|
||||
|
||||
:deep(.t-cell__note) {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.date-summary {
|
||||
|
||||
:deep(.t-cell__title) {
|
||||
|
||||
@@ -107,7 +107,7 @@ function getUserName(user: OrderFulfillment["operator"], userId: string | undefi
|
||||
function getProductText(item: OrderFulfillmentItem): string {
|
||||
const quantity = getPackageQuantityText(item.quantity);
|
||||
const skuText = getProductSkuSnapshotText(item.productNameSnapshot, item.skuNameSnapshot, item.specSummarySnapshot);
|
||||
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""} × ${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
|
||||
return `${item.productNameSnapshot || "未命名产品"}${skuText ? `(${skuText})` : " "}${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<template>
|
||||
<bottom-popup
|
||||
v-model="visible"
|
||||
title="履约冲正"
|
||||
left-button-text="取消"
|
||||
:right-button-text="operating ? '提交中' : '提交'"
|
||||
:z-index="revokePopupZIndex"
|
||||
:overlay-props="{ zIndex: revokePopupZIndex - 1 }"
|
||||
@left-button-click="visible = false"
|
||||
@right-button-click="submit"
|
||||
>
|
||||
<t-form class="revoke-form" label-width="7rem">
|
||||
<t-form-item label="冲正原因" required-mark>
|
||||
<div class="reason">
|
||||
<t-textarea
|
||||
v-model.trim="reason"
|
||||
borderless
|
||||
autosize
|
||||
maxlength="500"
|
||||
placeholder="请输入或选择冲正原因"
|
||||
/>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
@click="openReasonPicker"
|
||||
>选择</t-button>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="库存退回门店" content-align="right">
|
||||
<t-switch v-model="returnedToStore" />
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<media-selector
|
||||
:model-value="photoUrlList"
|
||||
v-model:photo-items="photoItems"
|
||||
:upload="uploadPhotoList"
|
||||
:edit-mode="true"
|
||||
required
|
||||
title="冲正凭证照片"
|
||||
/>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</bottom-popup>
|
||||
<t-popup
|
||||
v-model="reasonPickerVisible"
|
||||
placement="bottom"
|
||||
:z-index="reasonPickerZIndex"
|
||||
:overlay-props="{ zIndex: reasonPickerZIndex - 1 }"
|
||||
>
|
||||
<t-picker
|
||||
v-model="reasonPickerDraft"
|
||||
:columns="reasonPickerColumns"
|
||||
title="选择冲正原因"
|
||||
@cancel="reasonPickerVisible = false"
|
||||
@confirm="confirmReason"
|
||||
/>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import type { Attachment } from "timi-web-api";
|
||||
import FulfillmentAPI from "@/api/FulfillmentAPI";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import type { OrderFulfillment } from "@/types/Fulfillment";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||||
import { createPackageRequestNo } from "@/utils/package";
|
||||
import { Message } from "@/utils/message";
|
||||
import { uploadPhotoList } from "@/utils/photo";
|
||||
|
||||
defineOptions({ name: "OrderFulfillmentRevoke" });
|
||||
|
||||
const props = defineProps<{
|
||||
fulfillment: OrderFulfillment;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
success: [];
|
||||
}>();
|
||||
const visible = defineModel<boolean>("visible", { default: false });
|
||||
|
||||
const revokePopupZIndex = 12000;
|
||||
const reasonPickerZIndex = revokePopupZIndex + 1;
|
||||
const operating = ref(false);
|
||||
const reason = ref("");
|
||||
const returnedToStore = ref(true);
|
||||
const photoItems = ref<PhotoItem[]>([]);
|
||||
const reasonPickerVisible = ref(false);
|
||||
const reasonPickerDraft = ref<string[]>([]);
|
||||
const requestNo = ref("");
|
||||
const photoUrlList = computed(() => photoItems.value.map(item => item.url));
|
||||
const reasonOptions = [
|
||||
"客户申请撤销履约",
|
||||
"履约数量填写有误",
|
||||
"商品或服务与实际不符",
|
||||
"重复履约",
|
||||
"履约操作有误",
|
||||
"库存扣减有误"
|
||||
];
|
||||
const reasonPickerColumns = reasonOptions.map(item => ({ label: item, value: item }));
|
||||
|
||||
function resetForm(): void {
|
||||
reason.value = "";
|
||||
returnedToStore.value = true;
|
||||
photoItems.value = [];
|
||||
reasonPickerVisible.value = false;
|
||||
reasonPickerDraft.value = [];
|
||||
requestNo.value = "";
|
||||
}
|
||||
|
||||
function openReasonPicker(): void {
|
||||
const currentReason = reasonOptions.includes(reason.value) ? reason.value : reasonOptions[0];
|
||||
reasonPickerDraft.value = [currentReason];
|
||||
reasonPickerVisible.value = true;
|
||||
}
|
||||
|
||||
function confirmReason(value: Array<string | number>): void {
|
||||
reason.value = String(value[0] || reasonPickerDraft.value[0] || "");
|
||||
reasonPickerVisible.value = false;
|
||||
}
|
||||
|
||||
function buildAttachments(): Partial<Attachment>[] {
|
||||
return photoItems.value.flatMap(item => item.tempFileId ? [{
|
||||
tempFileId: item.tempFileId,
|
||||
attachType: "PHOTO"
|
||||
}] : []);
|
||||
}
|
||||
|
||||
async function submit(): Promise<void> {
|
||||
if (operating.value) {
|
||||
return;
|
||||
}
|
||||
if (!reason.value.trim()) {
|
||||
Message.warning("冲正原因不能为空");
|
||||
return;
|
||||
}
|
||||
const attachmentList = buildAttachments();
|
||||
if (props.fulfillment.stockRecordList?.length && !attachmentList.length) {
|
||||
Message.warning("实物履约冲正必须上传退回照片");
|
||||
return;
|
||||
}
|
||||
if (!props.fulfillment.id) {
|
||||
Message.error("履约单编号缺失,无法冲正");
|
||||
return;
|
||||
}
|
||||
if (!requestNo.value) {
|
||||
requestNo.value = createPackageRequestNo();
|
||||
}
|
||||
operating.value = true;
|
||||
try {
|
||||
await FulfillmentAPI.revoke({
|
||||
fulfillmentId: props.fulfillment.id,
|
||||
requestNo: requestNo.value,
|
||||
reason: reason.value.trim(),
|
||||
returnedToStore: returnedToStore.value,
|
||||
attachmentList
|
||||
});
|
||||
visible.value = false;
|
||||
emitListDataChanged(listDataEventKeys.salesOrderChanged, props.fulfillment.salesOrderId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||||
Message.success("履约单已冲正");
|
||||
emit("success");
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "履约冲正失败,重试会复用同一请求号"));
|
||||
} finally {
|
||||
operating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(visible, value => {
|
||||
if (value) {
|
||||
resetForm();
|
||||
} else {
|
||||
reasonPickerVisible.value = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.revoke-form {
|
||||
margin: 0;
|
||||
|
||||
.reason {
|
||||
gap: .5rem;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
|
||||
.t-textarea {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,367 @@
|
||||
<template>
|
||||
<bottom-popup
|
||||
v-model="popupVisible"
|
||||
title="筛选产品 SKU"
|
||||
height="min(80vh, 48rem)"
|
||||
left-button-text="重置"
|
||||
right-button-text="确定"
|
||||
@left-button-click="resetSelection"
|
||||
@right-button-click="confirmSelection"
|
||||
>
|
||||
<div class="sku-filter-popup">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
class="search"
|
||||
v-model="keyword"
|
||||
borderless
|
||||
clearable
|
||||
placeholder="搜索产品名称、拼音、编码或 SKU"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="singleSkuProductList.length" class="single-list">
|
||||
<t-cell-group theme="card">
|
||||
<t-cell
|
||||
class="sku-cell"
|
||||
v-for="product in singleSkuProductList"
|
||||
:key="product.id"
|
||||
@click="toggleSkuSelected(getSkuId(getProductSkuList(product)[0]))"
|
||||
>
|
||||
<template #title>
|
||||
<div @click.stop>
|
||||
<t-checkbox
|
||||
:model-value="draftSkuIdList.includes(getSkuId(getProductSkuList(product)[0]))"
|
||||
icon="line"
|
||||
:block="false"
|
||||
borderless
|
||||
@update:model-value="checked => setSkuSelected(getSkuId(getProductSkuList(product)[0]), checked)"
|
||||
>
|
||||
<span v-text="product.name || '未命名产品'" />
|
||||
</t-checkbox>
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
</div>
|
||||
<t-collapse
|
||||
v-if="multiSkuProductList.length"
|
||||
v-model="expandedProductIdList"
|
||||
class="multi-list"
|
||||
:expand-mutex="false"
|
||||
>
|
||||
<t-collapse-panel
|
||||
v-for="product in multiSkuProductList"
|
||||
:key="product.id"
|
||||
:value="product.id || ''"
|
||||
class="collapse-panel"
|
||||
>
|
||||
<template #header>
|
||||
<div class="header">
|
||||
<div class="group-checkbox" @click.stop>
|
||||
<t-checkbox
|
||||
:model-value="0 < getVisibleSelectedSkuCount(product)"
|
||||
:indeterminate="isProductPartiallySelected(product)"
|
||||
icon="line"
|
||||
:block="false"
|
||||
borderless
|
||||
@update:model-value="toggleProductSkuSelection(product)"
|
||||
/>
|
||||
</div>
|
||||
<span class="clip-text" v-text="product.name || '未命名产品'" />
|
||||
<span
|
||||
v-if="getSelectedSkuCount(product)"
|
||||
class="tips"
|
||||
v-text="`已选 ${getSelectedSkuCount(product)} 个`"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<t-cell-group theme="card" class="sku-choice-list">
|
||||
<t-cell
|
||||
v-for="sku in getVisibleProductSkuList(product)"
|
||||
:key="sku.id"
|
||||
class="sku-cell"
|
||||
@click="toggleSkuSelected(getSkuId(sku))"
|
||||
>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<div @click.stop>
|
||||
<t-checkbox
|
||||
:model-value="draftSkuIdList.includes(getSkuId(sku))"
|
||||
icon="line"
|
||||
:block="false"
|
||||
borderless
|
||||
@update:model-value="checked => setSkuSelected(getSkuId(sku), checked)"
|
||||
/>
|
||||
</div>
|
||||
<span class="clip-text" v-text="getSkuText(sku)" />
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
</t-collapse-panel>
|
||||
</t-collapse>
|
||||
<div
|
||||
v-if="!singleSkuProductList.length && !multiSkuProductList.length"
|
||||
class="center-tips"
|
||||
v-text="loadingProducts ? '正在加载产品 SKU' : keyword ? '没有匹配的产品或 SKU' : '暂无可筛选的产品 SKU'"
|
||||
/>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import type { Product, ProductSku } from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
|
||||
defineOptions({ name: "SkuFilterPopup" });
|
||||
|
||||
type SkuFilterOption = { skuId: string; productName: string; skuName: string };
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean;
|
||||
skuIdList: string[];
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: boolean];
|
||||
"options-loaded": [optionList: SkuFilterOption[]];
|
||||
confirm: [skuIdList: string[]];
|
||||
}>();
|
||||
|
||||
const popupVisible = computed({
|
||||
get: () => props.modelValue,
|
||||
set: value => emit("update:modelValue", value)
|
||||
});
|
||||
const draftSkuIdList = ref<string[]>([...props.skuIdList]);
|
||||
const keyword = ref("");
|
||||
const productList = ref<Product[]>([]);
|
||||
const expandedProductIdList = ref<Array<string | number>>([]);
|
||||
const loadingProducts = ref(false);
|
||||
const normalizedKeyword = computed(() => keyword.value.trim().toLocaleLowerCase());
|
||||
const filterableProductList = computed(() => productList.value.filter(product => !!product.id && 0 < getProductSkuList(product).length));
|
||||
const singleSkuProductList = computed(() => filterableProductList.value.filter(product => getProductSkuList(product).length === 1 && matchesProductSearch(product)));
|
||||
const multiSkuProductList = computed(() => filterableProductList.value.filter(product => 1 < getProductSkuList(product).length && matchesProductSearch(product)));
|
||||
const skuFilterOptionList = computed<SkuFilterOption[]>(() => filterableProductList.value.flatMap(product => getProductSkuList(product).map(sku => ({
|
||||
skuId: getSkuId(sku),
|
||||
productName: product.name || "未命名产品",
|
||||
skuName: getSkuText(sku)
|
||||
}))));
|
||||
|
||||
watch(() => props.modelValue, visible => {
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
draftSkuIdList.value = [...props.skuIdList];
|
||||
expandSelectedProducts();
|
||||
});
|
||||
|
||||
watch(() => props.skuIdList, skuIdList => {
|
||||
if (!props.modelValue) {
|
||||
draftSkuIdList.value = [...skuIdList];
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
watch(normalizedKeyword, value => {
|
||||
if (value) {
|
||||
expandedProductIdList.value = multiSkuProductList.value.map(product => product.id || "");
|
||||
}
|
||||
});
|
||||
|
||||
function getProductSkuList(product: Product): ProductSku[] {
|
||||
return (product.skuList || []).filter((sku): sku is ProductSku & { id: string } => !!sku.id);
|
||||
}
|
||||
|
||||
function getSkuId(sku?: ProductSku): string {
|
||||
return sku?.id || "";
|
||||
}
|
||||
|
||||
function getSkuText(sku?: ProductSku): string {
|
||||
return sku?.specSummary || sku?.name || "默认 SKU";
|
||||
}
|
||||
|
||||
function matchesSearchText(value?: string | null): boolean {
|
||||
return !!normalizedKeyword.value && !!value?.toLocaleLowerCase().includes(normalizedKeyword.value);
|
||||
}
|
||||
|
||||
function matchesProductName(product: Product): boolean {
|
||||
return [
|
||||
product.name,
|
||||
product.namePinyinFull,
|
||||
product.namePinyinInitial,
|
||||
product.namePinyinMixed,
|
||||
product.code
|
||||
].some(matchesSearchText);
|
||||
}
|
||||
|
||||
function matchesSku(sku: ProductSku): boolean {
|
||||
return [sku.name, sku.specSummary, sku.code, sku.barcode].some(matchesSearchText);
|
||||
}
|
||||
|
||||
function matchesProductSearch(product: Product): boolean {
|
||||
return !normalizedKeyword.value
|
||||
|| matchesProductName(product)
|
||||
|| getProductSkuList(product).some(matchesSku);
|
||||
}
|
||||
|
||||
function getVisibleProductSkuList(product: Product): ProductSku[] {
|
||||
const skuList = getProductSkuList(product);
|
||||
if (!normalizedKeyword.value || matchesProductName(product)) {
|
||||
return skuList;
|
||||
}
|
||||
return skuList.filter(matchesSku);
|
||||
}
|
||||
|
||||
function getSelectedSkuCount(product: Product): number {
|
||||
const skuIdSet = new Set(getProductSkuList(product).map(getSkuId));
|
||||
return draftSkuIdList.value.filter(skuId => skuIdSet.has(skuId)).length;
|
||||
}
|
||||
|
||||
function getVisibleSelectedSkuCount(product: Product): number {
|
||||
const skuIdSet = new Set(getVisibleProductSkuList(product).map(getSkuId));
|
||||
return draftSkuIdList.value.filter(skuId => skuIdSet.has(skuId)).length;
|
||||
}
|
||||
|
||||
function isProductPartiallySelected(product: Product): boolean {
|
||||
const selectedCount = getVisibleSelectedSkuCount(product);
|
||||
return 0 < selectedCount && selectedCount < getVisibleProductSkuList(product).length;
|
||||
}
|
||||
|
||||
function toggleProductSkuSelection(product: Product): void {
|
||||
const skuIdList = getVisibleProductSkuList(product).map(getSkuId);
|
||||
const skuIdSet = new Set(draftSkuIdList.value);
|
||||
const shouldSelectAll = !skuIdList.every(skuId => skuIdSet.has(skuId));
|
||||
for (const skuId of skuIdList) {
|
||||
if (shouldSelectAll) {
|
||||
skuIdSet.add(skuId);
|
||||
} else {
|
||||
skuIdSet.delete(skuId);
|
||||
}
|
||||
}
|
||||
draftSkuIdList.value = [...skuIdSet];
|
||||
}
|
||||
|
||||
function expandSelectedProducts(): void {
|
||||
if (normalizedKeyword.value) {
|
||||
expandedProductIdList.value = multiSkuProductList.value.map(product => product.id || "");
|
||||
return;
|
||||
}
|
||||
expandedProductIdList.value = multiSkuProductList.value
|
||||
.filter(product => getProductSkuList(product).some(sku => props.skuIdList.includes(getSkuId(sku))))
|
||||
.map(product => product.id || "");
|
||||
}
|
||||
|
||||
function setSkuSelected(skuId: string, checked: boolean): void {
|
||||
if (!skuId) {
|
||||
return;
|
||||
}
|
||||
const skuIdSet = new Set(draftSkuIdList.value);
|
||||
if (checked) {
|
||||
skuIdSet.add(skuId);
|
||||
} else {
|
||||
skuIdSet.delete(skuId);
|
||||
}
|
||||
draftSkuIdList.value = [...skuIdSet];
|
||||
}
|
||||
|
||||
function toggleSkuSelected(skuId: string): void {
|
||||
setSkuSelected(skuId, !draftSkuIdList.value.includes(skuId));
|
||||
}
|
||||
|
||||
function resetSelection(): void {
|
||||
draftSkuIdList.value = [];
|
||||
}
|
||||
|
||||
function confirmSelection(): void {
|
||||
emit("confirm", [...new Set(draftSkuIdList.value)]);
|
||||
popupVisible.value = false;
|
||||
}
|
||||
|
||||
async function loadFilterProducts(): Promise<void> {
|
||||
loadingProducts.value = true;
|
||||
try {
|
||||
const result = await ProductAPI.list({ index: 0, size: 1000 });
|
||||
productList.value = result.list || [];
|
||||
emit("options-loaded", skuFilterOptionList.value);
|
||||
expandSelectedProducts();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "产品 SKU 筛选项加载失败"));
|
||||
} finally {
|
||||
loadingProducts.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadFilterProducts);
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.sku-filter-popup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
:deep(.t-cell-group) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.filters {
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
padding: .5rem 1rem;
|
||||
position: sticky;
|
||||
|
||||
.search {
|
||||
border: 1px solid var(--td-component-border);
|
||||
padding: .5rem 1rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.single-list,
|
||||
.multi-list {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.multi-list {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
|
||||
.collapse-panel {
|
||||
|
||||
:deep(.t-collapse-panel__content) {
|
||||
padding: 0 0 0 1rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
.group-checkbox {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sku-choice-list {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sku-cell,
|
||||
:deep(.t-collapse-panel__title) {
|
||||
padding: .5rem;
|
||||
|
||||
.title {
|
||||
gap: .125rem;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.tips {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
margin-left: .5rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,26 +1,36 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.eventRecord.create" class="quick-sign-in-page">
|
||||
<space class="content-margin" direction="vertical" v-entrance-transition>
|
||||
<div class="event-panel">
|
||||
<event-selector
|
||||
v-if="!isEventLoading && !eventLoadFailed"
|
||||
:model-value="selectedEventIdList"
|
||||
:event-list="eventList"
|
||||
required-mark
|
||||
@update:model-value="handleEventSelectionChange"
|
||||
/>
|
||||
<div v-else-if="isEventLoading" class="empty-block">正在加载登记事件</div>
|
||||
<div v-else class="event-load-error">
|
||||
<span>登记事件加载失败</span>
|
||||
<t-button size="small" theme="primary" variant="text" @click="loadActions">重试</t-button>
|
||||
</div>
|
||||
<div class="tips red">事件可多选,请注意勾选的登记事件</div>
|
||||
</div>
|
||||
<t-cell-group v-if="!isEventLoading && !eventLoadFailed" theme="card">
|
||||
<t-cell title="登记事件" arrow @click="eventPopupVisible = true">
|
||||
<template #left-icon>
|
||||
<t-icon name="task-setting" />
|
||||
</template>
|
||||
<template #note>
|
||||
<span class="red text-bold" v-text="selectedEventName" />
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell title="识别成功自动登记">
|
||||
<template #left-icon>
|
||||
<t-icon name="task-checked" />
|
||||
</template>
|
||||
<template #right-icon>
|
||||
<t-switch v-model="autoRegisterEnabled" />
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="red">扫码匹配客户后自动提交登记,请注意已选登记事件和选项</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<div v-else-if="isEventLoading" class="center-tips">正在加载登记事件</div>
|
||||
<div v-else class="center-tips">登记事件加载失败</div>
|
||||
<div v-if="selectedEventList && selectedEventList[0]?.optionGroupList?.length !== 0" class="content-margin">
|
||||
<event-option-selector
|
||||
v-model="selectedOptionSelectionMap"
|
||||
:event-list="eventList"
|
||||
:selected-event-id-list="selectedEventIdList"
|
||||
/>
|
||||
</div>
|
||||
<div class="content-margin">
|
||||
<code-scanner
|
||||
visible
|
||||
:session-key="scannerSessionKey"
|
||||
@@ -29,14 +39,14 @@
|
||||
@decode="handleDecodedText"
|
||||
@status-change="handleScanStatusChange"
|
||||
/>
|
||||
</space>
|
||||
</div>
|
||||
<t-button
|
||||
class="cell-button"
|
||||
theme="primary"
|
||||
:disabled="!canSubmitRegister"
|
||||
:loading="submitting"
|
||||
v-entrance-transition="70"
|
||||
@click="doSubmit"
|
||||
@click="doSubmit()"
|
||||
>登记</t-button>
|
||||
<customer-profile-card
|
||||
v-if="matchedCustomer"
|
||||
@@ -65,14 +75,16 @@
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
<div v-if="showRecordPhotoInput" class="input-form photo-form content-margin">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
title="登记事件照片"
|
||||
:required="selectedRequiredPhotoEventList.length > 0"
|
||||
v-model="recordPhotoList"
|
||||
v-model:photo-items="recordPhotoItemList"
|
||||
:edit-mode="true"
|
||||
:loading="recordPhotoUploading"
|
||||
@add="capturePhoto"
|
||||
@add="selectPhotoFile"
|
||||
@capture-photo="capturePhoto"
|
||||
@capture-video="captureVideo"
|
||||
/>
|
||||
</div>
|
||||
<t-cell-group
|
||||
@@ -105,11 +117,50 @@
|
||||
ref="recordPhotoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept="*/*"
|
||||
multiple
|
||||
@change="handleRecordPhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="recordPhotoCameraInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
@change="handleRecordPhotoSelected"
|
||||
>
|
||||
<input
|
||||
ref="videoInputRef"
|
||||
class="file-input"
|
||||
type="file"
|
||||
accept="video/*"
|
||||
capture="environment"
|
||||
@change="handleRecordPhotoSelected"
|
||||
>
|
||||
</div>
|
||||
<bottom-popup
|
||||
v-model="eventPopupVisible"
|
||||
title="选择登记事件"
|
||||
left-button-text="关闭"
|
||||
right-button-text=""
|
||||
@left-button-click="eventPopupVisible = false"
|
||||
>
|
||||
<div class="event-popup">
|
||||
<event-selector
|
||||
v-if="!isEventLoading && !eventLoadFailed"
|
||||
:model-value="selectedEventIdList"
|
||||
:event-list="eventList"
|
||||
selection-mode="single"
|
||||
label=""
|
||||
@update:model-value="handleEventSelectionChange"
|
||||
/>
|
||||
<div v-else-if="isEventLoading" class="empty-block">正在加载登记事件</div>
|
||||
<div v-else class="event-load-error">
|
||||
<span>登记事件加载失败</span>
|
||||
<t-button size="small" theme="primary" variant="text" @click="loadActions">重试</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
@@ -120,7 +171,7 @@ import EventRecordAPI from "@/api/EventRecordAPI";
|
||||
import CodeScanner from "@/components/CodeScanner.vue";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import EventOptionSelector from "@/components/EventOptionSelector.vue";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import { useSettingStore } from "@/store/settingStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { EventItem, EventOptionSelectionMap } from "@/types/EventItem";
|
||||
@@ -132,10 +183,11 @@ import { resolveSelectedOptionGroupList, validateEventOptionSelection } from "@/
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { getEventRecordPhotoURL, hasPhotoAttachment } from "@/utils/eventRecord";
|
||||
import { compressUploadImageList } from "@/utils/imageCompression";
|
||||
import { saveCapturedFilesFromInput } from "@/utils/twaBridge";
|
||||
import { Storage, Time } from "timi-web";
|
||||
import { AttachmentAPI, type Attachment } from "timi-web-api";
|
||||
import { type Attachment, AttachmentAPI } from "timi-web-api";
|
||||
import EventSelector from "@/components/EventSelector.vue";
|
||||
import { Space } from "timi-tdesign-mobile";
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
|
||||
defineOptions({
|
||||
name: "QuickSignInPage"
|
||||
@@ -147,14 +199,17 @@ const settingStore = useSettingStore();
|
||||
// ---------- 登记事件 ----------
|
||||
|
||||
const EventItemStorageKey = "quick-scan-event-id";
|
||||
const autoRegisterEnabled = ref(false);
|
||||
const selectedEventIdList = ref<string[]>([]);
|
||||
const eventList = ref<EventItem[]>([]);
|
||||
const selectedOptionSelectionMap = reactive<EventOptionSelectionMap>({});
|
||||
const isEventLoading = ref(false);
|
||||
const eventLoadFailed = ref(false);
|
||||
const eventPopupVisible = ref(false);
|
||||
const selectedEventList = computed(() => selectedEventIdList.value
|
||||
.map(eventId => eventList.value.find(item => normalizeEventId(item) === eventId))
|
||||
.filter((item): item is EventItem => !!item));
|
||||
const selectedEventName = computed(() => selectedEventList.value[0]?.name || "请选择登记事件");
|
||||
const selectedNumberEventList = computed(() => selectedEventList.value.filter(item => item.valueType === "NUMBER"));
|
||||
const selectedRequiredPhotoEventList = computed(() => selectedEventList.value.filter(item => item.requirePhoto === true));
|
||||
|
||||
@@ -200,12 +255,13 @@ function buildInitialSelectedEventIdList(): string[] {
|
||||
|
||||
function normalizeSelectedEventIdList(eventIdList: string[]): string[] {
|
||||
const validEventIdSet = new Set(eventList.value.map(normalizeEventId).filter(Boolean));
|
||||
return [...new Set(eventIdList.map(String))].filter(eventId => validEventIdSet.has(eventId));
|
||||
return [...new Set(eventIdList.map(String))].filter(eventId => validEventIdSet.has(eventId)).slice(0, 1);
|
||||
}
|
||||
|
||||
async function handleEventSelectionChange(eventIdList: string[]): Promise<void> {
|
||||
selectedEventIdList.value = normalizeSelectedEventIdList(eventIdList);
|
||||
syncStoredEventId();
|
||||
eventPopupVisible.value = false;
|
||||
}
|
||||
|
||||
function resolveRecordOptionGroupList(eventId: string) {
|
||||
@@ -243,6 +299,7 @@ const scanCode = ref("");
|
||||
const scanStatus = ref("正在启动扫码预览");
|
||||
const scannerSessionKey = ref(0);
|
||||
const matchedCustomer = ref<Customer>();
|
||||
const registeredCustomerIdSet = new Set<string>();
|
||||
let latestDecodedText = "";
|
||||
|
||||
async function handleDecodedText(rawText: string): Promise<void> {
|
||||
@@ -254,8 +311,16 @@ async function handleDecodedText(rawText: string): Promise<void> {
|
||||
scanCode.value = normalizedText;
|
||||
await settingStore.playScanSuccessSound();
|
||||
await loadCustomer(normalizedText);
|
||||
if (matchedCustomer.value) {
|
||||
const customer = matchedCustomer.value;
|
||||
if (customer) {
|
||||
if (customer.id && registeredCustomerIdSet.has(customer.id)) {
|
||||
scanStatus.value = `客户 ${customer.name || customer.code || normalizedText} 已在本页面登记`;
|
||||
return;
|
||||
}
|
||||
scanStatus.value = `已识别 ${normalizedText},可直接登记`;
|
||||
if (autoRegisterEnabled.value) {
|
||||
await doSubmit(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
scanStatus.value = `已识别 ${normalizedText},但未匹配客户档案`;
|
||||
@@ -340,6 +405,8 @@ function validateNumberValueList(): boolean {
|
||||
// ---------- 照片 ----------
|
||||
|
||||
const recordPhotoInputRef = ref<HTMLInputElement>();
|
||||
const recordPhotoCameraInputRef = ref<HTMLInputElement>();
|
||||
const videoInputRef = ref<HTMLInputElement>();
|
||||
const recordPhotoItemList = ref<PhotoItem[]>([]);
|
||||
const recordPhotoUploading = ref(false);
|
||||
const showRecordPhotoInput = computed(() => selectedRequiredPhotoEventList.value.length > 0 || recordPhotoItemList.value.length > 0);
|
||||
@@ -354,26 +421,36 @@ const recordPhotoList = computed<string[]>({
|
||||
});
|
||||
|
||||
function capturePhoto(): void {
|
||||
recordPhotoCameraInputRef.value?.click();
|
||||
}
|
||||
|
||||
function selectPhotoFile(): void {
|
||||
recordPhotoInputRef.value?.click();
|
||||
}
|
||||
|
||||
function captureVideo(): void {
|
||||
videoInputRef.value?.click();
|
||||
}
|
||||
|
||||
async function handleRecordPhotoSelected(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const fileList = Array.from(input.files || []);
|
||||
if (!fileList.length) {
|
||||
return;
|
||||
}
|
||||
saveCapturedFilesFromInput(input, fileList);
|
||||
recordPhotoUploading.value = true;
|
||||
try {
|
||||
const compressedFileList = await compressUploadImageList(fileList);
|
||||
const tempFileList = await AttachmentAPI.upload(compressedFileList);
|
||||
for (const item of tempFileList) {
|
||||
for (const [index, item] of tempFileList.entries()) {
|
||||
if (!item.id) {
|
||||
continue;
|
||||
}
|
||||
recordPhotoItemList.value.push({
|
||||
tempFileId: item.id,
|
||||
attachType: "PHOTO",
|
||||
mimeType: fileList[index]?.type,
|
||||
url: AttachmentAPI.getTempReadURL(item.id)
|
||||
});
|
||||
}
|
||||
@@ -399,11 +476,19 @@ function buildPhotoAttachmentList(): Array<Partial<Attachment>> {
|
||||
}));
|
||||
}
|
||||
|
||||
async function doSubmit(): Promise<void> {
|
||||
async function doSubmit(isAutoRegister = false): Promise<void> {
|
||||
const customer = matchedCustomer.value;
|
||||
if (!customer) {
|
||||
return;
|
||||
}
|
||||
const customerId = customer.id;
|
||||
if (!customerId) {
|
||||
return;
|
||||
}
|
||||
if (registeredCustomerIdSet.has(customerId)) {
|
||||
Message.warning("该客户已在本页面登记,请勿重复登记");
|
||||
return;
|
||||
}
|
||||
if (!selectedEventIdList.value.length) {
|
||||
Message.warning("请至少选择一个登记事件");
|
||||
return;
|
||||
@@ -425,22 +510,29 @@ async function doSubmit(): Promise<void> {
|
||||
try {
|
||||
await EventRecordAPI.createBatch(selectedEventIdList.value.map(eventId => ({
|
||||
eventId,
|
||||
customerId: customer.id,
|
||||
customerId,
|
||||
selectedOptionGroupList: resolveRecordOptionGroupList(eventId),
|
||||
numberValue: resolveNumberValue(eventId),
|
||||
remark: "客户快速扫码登记",
|
||||
attachmentList: buildPhotoAttachmentList()
|
||||
})));
|
||||
scanStatus.value = `登记成功:${customer.name || customer.code || scanCode.value}。`;
|
||||
registeredCustomerIdSet.add(customerId);
|
||||
const customerText = customer.name || customer.code || scanCode.value || "客户";
|
||||
scanStatus.value = `登记成功:${customerText}。`;
|
||||
if (isAutoRegister) {
|
||||
Message.success(`自动登记成功:${customerText}`);
|
||||
}
|
||||
scanCode.value = "";
|
||||
matchedCustomer.value = undefined;
|
||||
recordPhotoItemList.value = [];
|
||||
for (const eventId of Object.keys(numberValueTextMap)) {
|
||||
delete numberValueTextMap[eventId];
|
||||
}
|
||||
if (!isAutoRegister) {
|
||||
for (const eventId of Object.keys(selectedOptionSelectionMap)) {
|
||||
delete selectedOptionSelectionMap[eventId];
|
||||
}
|
||||
}
|
||||
recentRecordList.value = [];
|
||||
latestDecodedText = "";
|
||||
scannerSessionKey.value += 1;
|
||||
@@ -459,18 +551,6 @@ async function doSubmit(): Promise<void> {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.event-panel {
|
||||
padding: .75rem 1rem;
|
||||
background: rgba(255, 255, 255, .94);
|
||||
box-shadow: 0 .75rem 2rem rgba(15, 23, 42, .08);
|
||||
border-radius: .875rem;
|
||||
|
||||
.tips {
|
||||
margin-top: .5rem;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.input-form {
|
||||
padding: .5rem 0;
|
||||
background: rgba(255, 255, 255, .94);
|
||||
@@ -492,24 +572,6 @@ async function doSubmit(): Promise<void> {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.empty-block,
|
||||
.event-load-error {
|
||||
color: #52607a;
|
||||
min-height: 4rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.empty-block {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.event-load-error {
|
||||
gap: .5rem;
|
||||
display: grid;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.code-box {
|
||||
padding: .875rem;
|
||||
background: #f7faff;
|
||||
@@ -547,6 +609,10 @@ async function doSubmit(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
.event-popup {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.quick-sign-in-page {
|
||||
.panel,
|
||||
|
||||
@@ -20,6 +20,13 @@
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<t-cell-group v-if="canReadSalesOrder" theme="card" v-entrance-transition="35">
|
||||
<t-cell title="套餐订单列表" arrow @click="toPackageOrderList">
|
||||
<template #left-icon>
|
||||
<t-icon name="gift" />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<t-cell-group title="基本信息" theme="card" v-entrance-transition="70">
|
||||
<t-cell title="标准价" :note="formatPackageAmount(config.standardAmount)" />
|
||||
<t-cell title="起始日期" :note="config.beginAt ? Time.toDateTime(config.beginAt) : '不限'" />
|
||||
@@ -30,7 +37,6 @@
|
||||
<t-cell
|
||||
class="item"
|
||||
v-for="item in config.itemList || []"
|
||||
:title="getItemTitle(item)"
|
||||
:key="item.id || `${item.skuId}-${item.skuUnitId}`"
|
||||
:note="`${item.defaultQuantity} ${item.unitSnapshot || ''}${item.remark ? `|${item.remark}` : ''}`"
|
||||
>
|
||||
@@ -48,12 +54,14 @@
|
||||
v-text="(item.productNameSnapshot || '产').slice(0, 1)"
|
||||
/>
|
||||
</template>
|
||||
<template #description>
|
||||
<t-tag
|
||||
:content="item.skuCodeSnapshot || item.sku?.code || 'SKU'"
|
||||
theme="primary"
|
||||
variant="light"
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<span v-text="item.productNameSnapshot || '未命名产品'" />
|
||||
<product-sku-tags
|
||||
:product-name="item.productNameSnapshot"
|
||||
:fallback="item.specSummarySnapshot || item.skuNameSnapshot || '默认 SKU'"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
<div v-if="!config.itemList?.length" class="empty" v-text="'暂无产品权益'" />
|
||||
@@ -82,6 +90,7 @@ import { DialogPlugin } from "tdesign-mobile-vue";
|
||||
import { Time } from "timi-web";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import PackageAPI from "@/api/PackageAPI";
|
||||
import ProductSkuTags from "@/components/ProductSkuTags.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { GaoPackageConfig, PackageConfigItem, PackageConfigStatus } from "@/types/Package";
|
||||
@@ -89,7 +98,7 @@ import { getErrorMessage } from "@/utils/error";
|
||||
import { formatPackageAmount, getPackageConfigStatusText } from "@/utils/package";
|
||||
import { Message } from "@/utils/message";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
import { getProductPhotoURL as getProductPhotoUrl, getProductSkuSnapshotText } from "@/utils/product";
|
||||
import { getProductPhotoURL as getProductPhotoUrl } from "@/utils/product";
|
||||
|
||||
defineOptions({ name: "PackageConfigDetail" });
|
||||
|
||||
@@ -102,6 +111,7 @@ const config = ref<GaoPackageConfig>();
|
||||
const isLoading = ref(false);
|
||||
const canUpdate = computed(() => !!config.value && userStore.hasPermissions(permissionCodes.packageConfig.update));
|
||||
const canDelete = computed(() => !!config.value && userStore.hasPermissions(permissionCodes.packageConfig.delete));
|
||||
const canReadSalesOrder = computed(() => userStore.hasPermissions(permissionCodes.salesOrder.read));
|
||||
const canPurchase = computed(() =>
|
||||
!!config.value
|
||||
&& config.value.status === "ACTIVE"
|
||||
@@ -116,11 +126,6 @@ function getItemPhotoURL(item: PackageConfigItem): string {
|
||||
return getProductPhotoUrl(item.sku || {});
|
||||
}
|
||||
|
||||
function getItemTitle(item: PackageConfigItem): string {
|
||||
const skuText = getProductSkuSnapshotText(item.productNameSnapshot, item.skuNameSnapshot, item.specSummarySnapshot);
|
||||
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""}`;
|
||||
}
|
||||
|
||||
async function loadData(): Promise<void> {
|
||||
const id = String(route.params.id || "");
|
||||
if (!id) {
|
||||
@@ -153,6 +158,21 @@ async function toPurchase(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function toPackageOrderList(): Promise<void> {
|
||||
if (!config.value?.id || !canReadSalesOrder.value) {
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "SalesOrderList",
|
||||
query: {
|
||||
orderType: "PACKAGE",
|
||||
packageConfigId: config.value.id,
|
||||
packageConfigName: config.value.name || "未命名套餐",
|
||||
transitionDepth: String(Number(route.meta.depth ?? 0) + 1)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function removeConfig(): void {
|
||||
if (!config.value?.id || !canDelete.value) {
|
||||
return;
|
||||
@@ -286,16 +306,20 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
.item {
|
||||
padding: 10px;
|
||||
|
||||
.item-title {
|
||||
gap: .5rem;
|
||||
:deep(.t-cell__title) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
}
|
||||
|
||||
.title {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,10 +50,8 @@
|
||||
placeholder="请选择产品"
|
||||
required-mark
|
||||
@update:model-value="applyProduct(index, $event)"
|
||||
@select="applyProductSelection(index, $event)"
|
||||
/>
|
||||
<t-form-item v-if="item.skuId" label="SKU 单位" content-align="right">
|
||||
<span v-text="getUnit(item)?.name || '未选择单位'" />
|
||||
</t-form-item>
|
||||
<t-form-item label="默认配额" content-align="right" required-mark>
|
||||
<t-stepper
|
||||
v-model="item.defaultQuantity"
|
||||
@@ -111,7 +109,7 @@ import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { GaoPackageConfig, PackageConfigItem, PackageConfigStatus } from "@/types/Package";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import type { Product, ProductSku, ProductSkuUnit } from "@/types/Product";
|
||||
import type { Product, ProductSelection, ProductSku, ProductSkuUnit } from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { formatPackageAmountInput, getPackageConfigStatusText, normalizePackageQuantity, parsePackageAmount } from "@/utils/package";
|
||||
import { Message } from "@/utils/message";
|
||||
@@ -204,23 +202,27 @@ const estimatedOriginalAmount = computed<number | undefined>(() => {
|
||||
});
|
||||
const estimatedOriginalAmountText = computed(() => estimatedOriginalAmount.value === undefined ? "待完善" : `¥${formatProductAmount(estimatedOriginalAmount.value)}`);
|
||||
|
||||
async function applyProduct(index: number, value?: { skuId: string; skuUnitId: string }): Promise<void> {
|
||||
function applyProduct(index: number, value?: { skuId: string; skuUnitId: string }): void {
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
const sku = skuCache.get(value.skuId) || await ProductAPI.skuDetail(value.skuId);
|
||||
skuCache.set(value.skuId, sku);
|
||||
const product = productCache.get(sku.productId || "") || await ProductAPI.detail(sku.productId || "");
|
||||
productCache.set(sku.productId || "", product);
|
||||
const unit = (sku.unitList || []).find(item => item.id === value.skuUnitId);
|
||||
Object.assign(form.itemList[index], {
|
||||
skuId: value.skuId,
|
||||
skuUnitId: value.skuUnitId,
|
||||
productNameSnapshot: product.name,
|
||||
skuNameSnapshot: sku.name,
|
||||
specSummarySnapshot: sku.specSummary,
|
||||
unitSnapshot: unit?.name || "",
|
||||
baseQuantityPerUnitSnapshot: unit?.baseQuantityPerUnit
|
||||
skuUnitId: value.skuUnitId
|
||||
});
|
||||
}
|
||||
|
||||
function applyProductSelection(index: number, selection: ProductSelection): void {
|
||||
skuCache.set(selection.sku.id || "", selection.sku);
|
||||
productCache.set(selection.product.id || "", selection.product);
|
||||
Object.assign(form.itemList[index], {
|
||||
productNameSnapshot: selection.product.name,
|
||||
productIdSnapshot: selection.product.id,
|
||||
skuCodeSnapshot: selection.sku.code,
|
||||
skuNameSnapshot: selection.sku.name,
|
||||
specSummarySnapshot: selection.sku.specSummary,
|
||||
unitSnapshot: selection.unit.name,
|
||||
baseQuantityPerUnitSnapshot: selection.unit.baseQuantityPerUnit
|
||||
});
|
||||
}
|
||||
|
||||
@@ -396,13 +398,16 @@ async function loadData(): Promise<void> {
|
||||
}
|
||||
const result = await PackageAPI.configDetail(routeId.value);
|
||||
const itemList = (result.itemList || []).map(createItem);
|
||||
const skuIdList = [...new Set(itemList.map(item => item.skuId).filter((id): id is string => !!id))];
|
||||
await Promise.all(skuIdList.map(async skuId => {
|
||||
const sku = itemList.find(item => item.skuId === skuId)?.sku || await ProductAPI.skuDetail(skuId);
|
||||
skuCache.set(skuId, sku);
|
||||
if (sku.productId) {
|
||||
productCache.set(sku.productId, await ProductAPI.detail(sku.productId));
|
||||
for (const item of itemList) {
|
||||
if (item.skuId && item.sku) {
|
||||
skuCache.set(item.skuId, item.sku);
|
||||
}
|
||||
}
|
||||
const productIdList = [...new Set(itemList
|
||||
.map(item => item.sku?.productId || item.productIdSnapshot)
|
||||
.filter((id): id is string => !!id))];
|
||||
await Promise.all(productIdList.map(async productId => {
|
||||
productCache.set(productId, await ProductAPI.detail(productId));
|
||||
}));
|
||||
Object.assign(form, {
|
||||
id: result.id || routeId.value,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.packageConfig.read" class="package-config-list">
|
||||
<div class="filters">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="keyword"
|
||||
@@ -193,7 +193,7 @@ function getStatusTheme(statusValue?: PackageConfigStatus): "success" | "warning
|
||||
function getProductRightText(item: PackageConfigItem): string {
|
||||
const quantity = getPackageQuantityText(item.defaultQuantity);
|
||||
const skuText = getProductSkuSnapshotText(item.productNameSnapshot, item.skuNameSnapshot, item.specSummarySnapshot);
|
||||
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""} × ${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
|
||||
return `${item.productNameSnapshot || "未命名产品"}${skuText ? `(${skuText})` : " "}${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
@@ -217,16 +217,14 @@ onUnmounted(() => {
|
||||
padding: var(--app-nav-height) 0 1rem;
|
||||
|
||||
.filters {
|
||||
gap: .5rem;
|
||||
top: var(--app-nav-height);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: var(--td-bg-color-page);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
|
||||
.keyword {
|
||||
--td-input-vertical-padding: .25rem 1rem;
|
||||
@@ -234,7 +232,6 @@ onUnmounted(() => {
|
||||
flex: 1;
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 1;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
@@ -246,10 +243,6 @@ onUnmounted(() => {
|
||||
margin-left: -2rem;
|
||||
padding-left: 2rem;
|
||||
border-radius: 1rem;
|
||||
|
||||
&:after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.packageConfig.read" class="package-order-config-list">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="keyword"
|
||||
borderless
|
||||
clearable
|
||||
placeholder="搜索套餐名称或说明"
|
||||
/>
|
||||
<t-dropdown-menu class="status">
|
||||
<t-dropdown-item
|
||||
v-model="status"
|
||||
label="状态"
|
||||
:options="statusOptions"
|
||||
@change="selectStatus"
|
||||
/>
|
||||
</t-dropdown-menu>
|
||||
</div>
|
||||
<t-pull-down-refresh
|
||||
v-model="refreshing"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="reload"
|
||||
@scrolltolower="loadMore"
|
||||
>
|
||||
<t-cell-group
|
||||
v-if="configList.length"
|
||||
class="list fix-last-cell-line empty-cell-title-margin"
|
||||
theme="card"
|
||||
>
|
||||
<t-cell
|
||||
v-for="(item, index) in configList"
|
||||
:key="item.id"
|
||||
class="item"
|
||||
arrow
|
||||
v-entrance-transition="index * 30"
|
||||
@click="selectConfig(item)"
|
||||
>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<strong class="name clip-text" v-text="item.name || '未命名套餐'" />
|
||||
<t-tag :content="getPackageConfigStatusText(item.status)" variant="light-outline" :theme="getStatusTheme(item.status)" />
|
||||
</div>
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="description">
|
||||
<div class="products">
|
||||
<t-tag
|
||||
v-for="productItem in item.itemList || []"
|
||||
:key="productItem.id || `${productItem.skuId}-${productItem.skuUnitId}`"
|
||||
:content="getProductText(productItem)"
|
||||
theme="primary"
|
||||
variant="light"
|
||||
/>
|
||||
<t-tag v-if="!item.itemList?.length" content="暂无产品权益" />
|
||||
</div>
|
||||
<div class="price">
|
||||
<span class="label gray">标准价:</span>
|
||||
<span class="value red" v-text="formatPackageAmount(item.standardAmount)" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<div v-else class="center-tips" v-text="loading ? '正在加载套餐' : '暂无套餐'" />
|
||||
<div class="center-tips" v-text="loadStateText" />
|
||||
</t-pull-down-refresh>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { type DropdownValue } from "tdesign-mobile-vue";
|
||||
import { Toolkit } from "timi-web";
|
||||
import PackageAPI from "@/api/PackageAPI";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { GaoPackageConfig, PackageConfigItem, PackageConfigStatus } from "@/types/Package";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatPackageAmount, getPackageConfigStatusText, getPackageQuantityText } from "@/utils/package";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { getProductSkuSnapshotText } from "@/utils/product";
|
||||
|
||||
defineOptions({ name: "PackageOrderConfigList" });
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const navBarStore = useNavBarStore();
|
||||
|
||||
const keyword = ref("");
|
||||
const status = ref("ALL");
|
||||
const configList = ref<GaoPackageConfig[]>([]);
|
||||
const pageIndex = ref(0);
|
||||
const total = ref(0);
|
||||
const loading = ref(false);
|
||||
const refreshing = ref(false);
|
||||
const noMore = ref(false);
|
||||
const pageSize = 15;
|
||||
const statusOptions = [
|
||||
{ label: "全部状态", value: "ALL" },
|
||||
{ label: "草稿", value: "DRAFT" },
|
||||
{ label: "启用", value: "ACTIVE" },
|
||||
{ label: "停用", value: "INACTIVE" }
|
||||
];
|
||||
const loadStateText = computed(() => loading.value ? "正在加载" : noMore.value ? "已经到底了" : "上拉加载更多");
|
||||
|
||||
async function loadMore(): Promise<void> {
|
||||
if (loading.value || noMore.value) {
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await PackageAPI.configList({
|
||||
index: pageIndex.value,
|
||||
size: pageSize,
|
||||
keyword: keyword.value || undefined,
|
||||
status: status.value === "ALL" ? undefined : status.value as PackageConfigStatus
|
||||
});
|
||||
const rows = result.list || [];
|
||||
configList.value = configList.value.concat(rows);
|
||||
total.value = result.total || 0;
|
||||
pageIndex.value += 1;
|
||||
noMore.value = rows.length < pageSize || total.value <= configList.value.length;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function reload(): Promise<void> {
|
||||
if (loading.value) {
|
||||
return;
|
||||
}
|
||||
pageIndex.value = 0;
|
||||
configList.value = [];
|
||||
total.value = 0;
|
||||
noMore.value = false;
|
||||
try {
|
||||
await loadMore();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "套餐加载失败"));
|
||||
} finally {
|
||||
refreshing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function selectStatus(value: DropdownValue): Promise<void> {
|
||||
if (Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
status.value = String(value);
|
||||
await reload();
|
||||
}
|
||||
|
||||
const reloadByKeyword = Toolkit.debounce(async () => {
|
||||
await reload();
|
||||
}, false);
|
||||
|
||||
watch(keyword, () => {
|
||||
reloadByKeyword();
|
||||
});
|
||||
|
||||
async function selectConfig(config: GaoPackageConfig): Promise<void> {
|
||||
if (!config.id) {
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "SalesOrderList",
|
||||
query: {
|
||||
orderType: "PACKAGE",
|
||||
packageConfigId: config.id,
|
||||
packageConfigName: config.name || "未命名套餐",
|
||||
transitionDepth: String(Number(route.meta.depth ?? 0) + 1)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getStatusTheme(statusValue?: PackageConfigStatus): "success" | "warning" | "default" {
|
||||
return statusValue === "ACTIVE" ? "success" : statusValue === "INACTIVE" ? "warning" : "default";
|
||||
}
|
||||
|
||||
function getProductText(item: PackageConfigItem): string {
|
||||
const quantity = getPackageQuantityText(item.defaultQuantity);
|
||||
const skuText = getProductSkuSnapshotText(item.productNameSnapshot, item.skuNameSnapshot, item.specSummarySnapshot);
|
||||
return `${item.productNameSnapshot || "未命名产品"}${skuText ? `(${skuText})` : " "}${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.clearRight();
|
||||
try {
|
||||
await reload();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "套餐加载失败"));
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
navBarStore.clearRight();
|
||||
reloadByKeyword.cancel();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.package-order-config-list {
|
||||
padding: var(--app-nav-height) 0 1rem;
|
||||
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
|
||||
.keyword {
|
||||
--td-input-vertical-padding: .25rem 1rem;
|
||||
|
||||
flex: 1;
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 1;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
--td-spacer: 4px;
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
margin-left: -2rem;
|
||||
padding-left: 2rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding-top: 1rem;
|
||||
flex-direction: column;
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
min-width: 0;
|
||||
|
||||
:deep(.t-cell__title) {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
gap: .5rem;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.description {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
|
||||
.products {
|
||||
gap: .35rem;
|
||||
display: flex;
|
||||
margin-top: .5rem;
|
||||
overflow-x: auto;
|
||||
white-space: nowrap;
|
||||
scrollbar-width: none;
|
||||
|
||||
:deep(.t-tag) {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.price {
|
||||
margin-top: .5rem;
|
||||
text-align: right;
|
||||
|
||||
.value {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -65,13 +65,12 @@
|
||||
<div class="description" v-text="config.description" />
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="成交价(元)" label-width="6rem" required-mark>
|
||||
<t-form-item v-if="canPriceOverride" label="成交价" label-width="6rem" required-mark>
|
||||
<t-input
|
||||
v-model.trim="saleAmountText"
|
||||
type="number"
|
||||
align="right"
|
||||
borderless
|
||||
:readonly="!canPriceOverride"
|
||||
placeholder="请输入成交价"
|
||||
/>
|
||||
</t-form-item>
|
||||
@@ -170,6 +169,62 @@
|
||||
/>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item
|
||||
v-if="canReceiveImmediately"
|
||||
class="payment-item"
|
||||
:class="{ disabled: receiveFullPayment }"
|
||||
:label="receiveFullPayment ? '收款和核销金额' : '已部分收款和核销'"
|
||||
label-width="9rem"
|
||||
content-align="right"
|
||||
>
|
||||
<t-input
|
||||
:model-value="receiveFullPayment ? formatPackageAmount(parsedSaleAmount || 0) : paymentAmountText"
|
||||
type="number"
|
||||
align="right"
|
||||
borderless
|
||||
:disabled="receiveFullPayment"
|
||||
:placeholder="paymentAmountPlaceholder"
|
||||
@update:model-value="paymentAmountText = String($event)"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="canReceiveImmediately" label="已全额收款和核销" content-align="right">
|
||||
<t-switch
|
||||
v-model="receiveFullPayment"
|
||||
size="small"
|
||||
:disabled="!canReceiveImmediately"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="canFulfillImmediately" label="已全部产品履约和核销" content-align="right">
|
||||
<t-switch
|
||||
v-model="fulfillAll"
|
||||
size="small"
|
||||
:disabled="!canFulfillImmediately || isStockChecking"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="canFulfillImmediately" label-width="0">
|
||||
<div class="stock-tips">
|
||||
<div class="tips red">全部履约会同步启用全额收款;请先准备充足的库存,任意一步失败都会下单失败。</div>
|
||||
<product-stock-preview v-if="stockPreviewList.length" :items="stockPreviewList" />
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="(paymentVerified && parsedPaymentAmount) || (receiveFullPayment && parsedSaleAmount)" label-width="0">
|
||||
<media-selector
|
||||
:model-value="paymentPhotoUrlList"
|
||||
v-model:photo-items="paymentPhotoItems"
|
||||
:upload="uploadPhotoList"
|
||||
:edit-mode="true"
|
||||
title="收款凭证照片(必要)"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item v-if="fulfillAll" label-width="0">
|
||||
<media-selector
|
||||
:model-value="fulfillmentPhotoUrlList"
|
||||
v-model:photo-items="fulfillmentPhotoItems"
|
||||
:upload="uploadPhotoList"
|
||||
:edit-mode="true"
|
||||
title="履约凭证照片(必要)"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="购买备注">
|
||||
<t-textarea
|
||||
v-model.trim="note"
|
||||
@@ -179,7 +234,7 @@
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
:model-value="photoUrlList"
|
||||
v-model:photo-items="photoItems"
|
||||
:upload="uploadPhotoList"
|
||||
@@ -195,26 +250,48 @@
|
||||
:enable-scan="false"
|
||||
@change="handleCustomerChange"
|
||||
/>
|
||||
<t-popup v-model="configSelectorVisible" placement="bottom">
|
||||
<div class="config-selector bg-white">
|
||||
<div class="popup-header">
|
||||
<t-button variant="text" size="small" @click="configSelectorVisible = false">关闭</t-button>
|
||||
<h3>选择套餐</h3>
|
||||
<span />
|
||||
</div>
|
||||
<bottom-popup
|
||||
v-model="configSelectorVisible"
|
||||
title="选择套餐"
|
||||
height="70vh"
|
||||
right-button-text=""
|
||||
@left-button-click="configSelectorVisible = false"
|
||||
>
|
||||
<div class="config-selector fix-cell-title-clip empty-cell-title-margin">
|
||||
<t-cell-group v-if="configList.length">
|
||||
<t-cell
|
||||
v-for="item in configList"
|
||||
:key="item.id"
|
||||
:title="item.name || '未命名套餐'"
|
||||
:note="`标准价:${formatPackageAmount(item.standardAmount)}`"
|
||||
class="config-option"
|
||||
arrow
|
||||
@click="selectConfig(item)"
|
||||
>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<div class="clip-text" v-text="item.name || '未命名套餐'" />
|
||||
<div class="price keep-text">
|
||||
<span class="label gray">标准价:</span>
|
||||
<span class="red" v-text="formatPackageAmount(item.standardAmount)" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="products">
|
||||
<t-tag
|
||||
v-for="productItem in item.itemList || []"
|
||||
:key="productItem.id || `${productItem.skuId}-${productItem.skuUnitId}`"
|
||||
:content="getConfigProductText(productItem)"
|
||||
theme="primary"
|
||||
variant="light"
|
||||
/>
|
||||
<t-tag v-if="!item.itemList?.length" content="暂无产品权益" />
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<div v-else class="center-tips" v-text="'暂无可购买套餐'" />
|
||||
</div>
|
||||
</t-popup>
|
||||
</bottom-popup>
|
||||
<t-popup v-model="unitPickerVisible" placement="bottom">
|
||||
<t-picker v-model="unitPickerDraft" :columns="unitPickerOptions" title="调整权益单位" @cancel="unitPickerVisible = false" @confirm="confirmItemUnitPicker" />
|
||||
</t-popup>
|
||||
@@ -252,6 +329,8 @@
|
||||
<script setup lang="ts">
|
||||
import { Time } from "timi-web";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { DialogPlugin } from "tdesign-mobile-vue";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import PackageAPI from "@/api/PackageAPI";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
@@ -259,23 +338,30 @@ import CodeScanner from "@/components/CodeScanner.vue";
|
||||
import CustomerList from "@/components/CustomerList.vue";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import ProductStockPreview from "@/components/ProductStockPreview.vue";
|
||||
import { usePackagePurchase } from "@/pages/package/usePackagePurchase";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import { useSettingStore } from "@/store/settingStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import type { GaoPackageConfig, PackageAttachment, PackagePurchaseItem } from "@/types/Package";
|
||||
import type { GaoPackageConfig, PackageAttachment, PackageConfigItem, PackagePurchaseItem } from "@/types/Package";
|
||||
import type { Product, ProductSku, ProductSkuUnit } from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||||
import {
|
||||
addPackageQuantity,
|
||||
convertPackageQuantity,
|
||||
formatPackageAmount,
|
||||
normalizePackageQuantity
|
||||
getPackageQuantityText,
|
||||
normalizePackageQuantity,
|
||||
parsePackageAmount,
|
||||
toPackageBaseQuantity
|
||||
} from "@/utils/package";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { buildProductStockPreview, getProductStockShortageMessage, mergeProductStockRequirements } from "@/utils/productStock";
|
||||
import type { ProductStockPreviewItem } from "@/utils/productStock";
|
||||
import { uploadPhotoList } from "@/utils/photo";
|
||||
import { getProductPhotoURL, getProductSkuSnapshotText } from "@/utils/product";
|
||||
|
||||
@@ -423,10 +509,24 @@ function parseDateTime(value: string): Date {
|
||||
const note = ref("");
|
||||
const isSaving = ref(false);
|
||||
const photoItems = ref<PhotoItem[]>([]);
|
||||
const paymentPhotoItems = ref<PhotoItem[]>([]);
|
||||
const fulfillmentPhotoItems = ref<PhotoItem[]>([]);
|
||||
const paymentAmountText = ref("0");
|
||||
const photoUrlList = computed(() => photoItems.value.map(item => item.url));
|
||||
const paymentPhotoUrlList = computed(() => paymentPhotoItems.value.map(item => item.url));
|
||||
const fulfillmentPhotoUrlList = computed(() => fulfillmentPhotoItems.value.map(item => item.url));
|
||||
const receiveFullPayment = ref(false);
|
||||
const fulfillAll = ref(false);
|
||||
const isStockChecking = ref(false);
|
||||
const stockPreviewList = ref<ProductStockPreviewItem[]>([]);
|
||||
let stockCheckToken = 0;
|
||||
const parsedPaymentAmount = computed(() => parsePackageAmount(paymentAmountText.value));
|
||||
const paymentVerified = computed(() => !receiveFullPayment.value
|
||||
&& 0 < paymentAmountText.value.trim().length
|
||||
&& parsedPaymentAmount.value !== 0);
|
||||
|
||||
function buildAttachments(): PackageAttachment[] {
|
||||
return photoItems.value.flatMap(item => item.tempFileId ? [{
|
||||
function buildAttachments(source: PhotoItem[] = photoItems.value): PackageAttachment[] {
|
||||
return source.flatMap(item => item.tempFileId ? [{
|
||||
tempFileId: item.tempFileId,
|
||||
attachType: item.attachType || "PHOTO"
|
||||
}] : []);
|
||||
@@ -446,9 +546,53 @@ const {
|
||||
config,
|
||||
selectedCustomerList,
|
||||
note,
|
||||
paymentVerified,
|
||||
paymentAmount: parsedPaymentAmount,
|
||||
receiveFullPayment,
|
||||
fulfillAll,
|
||||
hasPermission: permissionCode => userStore.hasPermissions(permissionCode),
|
||||
buildRegisteredAt: buildPurchasedAt,
|
||||
buildAttachments
|
||||
buildAttachments,
|
||||
buildPaymentAttachments: () => buildAttachments(paymentPhotoItems.value),
|
||||
buildFulfillmentAttachments: () => buildAttachments(fulfillmentPhotoItems.value)
|
||||
});
|
||||
|
||||
const parsedSaleAmount = computed(() => parsePackageAmount(saleAmountText.value));
|
||||
const paymentAmountPlaceholder = computed(() => `订单总金额:${formatPackageAmount(parsedSaleAmount.value || 0)}`);
|
||||
const canReceiveImmediately = computed(() => userStore.hasPermissions(permissionCodes.fundReceive.create)
|
||||
&& userStore.hasPermissions(permissionCodes.fundReceive.verify));
|
||||
const canFulfillImmediately = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.create)
|
||||
&& userStore.hasPermissions(permissionCodes.orderFulfillment.verify)
|
||||
&& userStore.hasPermissions(permissionCodes.productStock.read)
|
||||
&& (parsedSaleAmount.value === 0 || canReceiveImmediately.value));
|
||||
|
||||
watch(fulfillAll, async value => {
|
||||
stockCheckToken += 1;
|
||||
const token = stockCheckToken;
|
||||
if (!value) {
|
||||
isStockChecking.value = false;
|
||||
return;
|
||||
}
|
||||
isStockChecking.value = true;
|
||||
try {
|
||||
if (!await validateDirectStock() && token === stockCheckToken && fulfillAll.value) {
|
||||
fulfillAll.value = false;
|
||||
return;
|
||||
}
|
||||
if (token === stockCheckToken && fulfillAll.value && parsedSaleAmount.value !== 0) {
|
||||
receiveFullPayment.value = true;
|
||||
}
|
||||
} finally {
|
||||
if (token === stockCheckToken) {
|
||||
isStockChecking.value = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
watch(receiveFullPayment, value => {
|
||||
if (!value && parsedSaleAmount.value !== 0 && (!paymentVerified.value || parsedPaymentAmount.value !== parsedSaleAmount.value)) {
|
||||
fulfillAll.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
const unitPickerOptions = computed(() => {
|
||||
@@ -456,6 +600,12 @@ const unitPickerOptions = computed(() => {
|
||||
return item ? getSelectableUnitList(item).map(unit => ({ label: unit.name, value: unit.id || "" })) : [];
|
||||
});
|
||||
|
||||
function getConfigProductText(item: PackageConfigItem): string {
|
||||
const quantity = getPackageQuantityText(item.defaultQuantity);
|
||||
const skuText = getProductSkuSnapshotText(item.productNameSnapshot, item.skuNameSnapshot, item.specSummarySnapshot);
|
||||
return `${item.productNameSnapshot || "未命名产品"}${skuText ? `(${skuText})` : " "}${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
|
||||
}
|
||||
|
||||
function getItemLabel(item: PackagePurchaseItem): string {
|
||||
const configItem = config.value?.itemList?.find(configItem => configItem.skuId === item.skuId);
|
||||
const product = item.gifted ? giftProductMap[item.skuId] : undefined;
|
||||
@@ -481,6 +631,14 @@ function getItemSku(item: PackagePurchaseItem): ProductSku | undefined {
|
||||
return skuMap[item.skuId] || config.value?.itemList?.find(configItem => configItem.skuId === item.skuId)?.sku;
|
||||
}
|
||||
|
||||
function syncConfigSkuMap(value?: GaoPackageConfig): void {
|
||||
for (const item of value?.itemList || []) {
|
||||
if (item.skuId && item.sku) {
|
||||
skuMap[item.skuId] = item.sku;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getItemUnit(item: PackagePurchaseItem): ProductSkuUnit | undefined {
|
||||
return getItemSku(item)?.unitList?.find(unit => unit.id === item.skuUnitId);
|
||||
}
|
||||
@@ -640,23 +798,110 @@ function validateItemDecimalQuantity(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
async function validateDirectStock(): Promise<boolean> {
|
||||
stockPreviewList.value = [];
|
||||
const selected = packagePurchaseItemList.value.filter(item => {
|
||||
const quantity = normalizePackageQuantity(item.totalQuantity);
|
||||
return !!quantity && quantity !== "0";
|
||||
});
|
||||
const skuIdList = [...new Set(selected.map(item => item.skuId).filter(Boolean))];
|
||||
await Promise.all(skuIdList.map(async skuId => {
|
||||
if (skuMap[skuId]) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
skuMap[skuId] = await ProductAPI.skuDetail(skuId);
|
||||
} catch {
|
||||
// 统一在下方提示,避免部分 SKU 查询失败时静默跳过库存校验
|
||||
}
|
||||
}));
|
||||
for (const item of selected) {
|
||||
if (!skuMap[item.skuId]) {
|
||||
Message.warning(`${getItemName(item)} 的库存信息加载失败,请刷新后重试`);
|
||||
return false;
|
||||
}
|
||||
if (!getItemUnit(item)) {
|
||||
Message.warning(`${getItemName(item)} 的权益单位不存在,请刷新后重试`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const requirementList = mergeProductStockRequirements(selected.flatMap(item => {
|
||||
const sku = skuMap[item.skuId];
|
||||
const unit = getItemUnit(item);
|
||||
const quantity = normalizePackageQuantity(item.totalQuantity);
|
||||
const baseQuantity = quantity && unit ? toPackageBaseQuantity(quantity, unit.baseQuantityPerUnit) : undefined;
|
||||
if (!sku?.stockEnabled || !baseQuantity) {
|
||||
return [];
|
||||
}
|
||||
return [{ skuId: item.skuId, baseQuantity, productName: getItemName(item), unitName: "基础单位", stockEnabled: sku.stockEnabled }];
|
||||
}));
|
||||
if (!requirementList.length) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const stockList = await ProductAPI.stockBatchDetail({ skuIdList: requirementList.map(item => item.skuId) });
|
||||
stockPreviewList.value = buildProductStockPreview(stockList, requirementList);
|
||||
const shortageMessage = getProductStockShortageMessage(stockList, requirementList);
|
||||
if (shortageMessage) {
|
||||
Message.warning(`${shortageMessage},不能直接履约`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
stockPreviewList.value = [];
|
||||
Message.error(getErrorMessage(error, "库存查询失败,暂不能直接履约"));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function submitRecord(): Promise<void> {
|
||||
if (isSaving.value) {
|
||||
return;
|
||||
}
|
||||
if (isStockChecking.value) {
|
||||
Message.warning("库存正在预检,请稍候再提交");
|
||||
return;
|
||||
}
|
||||
if (!validatePurchaseForm() || !validateItemDecimalQuantity()) {
|
||||
return;
|
||||
}
|
||||
if (paymentVerified.value || receiveFullPayment.value || fulfillAll.value) {
|
||||
const dialog = DialogPlugin.confirm({
|
||||
title: "确认直通完成交易",
|
||||
content: fulfillAll.value
|
||||
? "将一次性购买套餐、完成收款核销,并完成全部履约和库存扣减。提交后如需更正,只能走撤销或冲正流程。"
|
||||
: paymentVerified.value
|
||||
? "将一次性购买套餐并登记已核销收款。提交后如需更正,只能走资金冲正流程。"
|
||||
: "将一次性购买套餐并核销全额收款。提交后如需更正,只能走资金冲正流程。",
|
||||
cancelBtn: "取消",
|
||||
confirmBtn: "确认并提交",
|
||||
onCancel() {
|
||||
dialog.destroy();
|
||||
},
|
||||
async onConfirm() {
|
||||
dialog.destroy();
|
||||
await purchasePackage();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
await purchasePackage();
|
||||
}
|
||||
|
||||
async function purchasePackage(): Promise<void> {
|
||||
|
||||
isSaving.value = true;
|
||||
try {
|
||||
if (fulfillAll.value && !await validateDirectStock()) return;
|
||||
const result = await submitPurchase();
|
||||
if (!result?.salesOrderId) {
|
||||
Message.error("套餐购买成功但未返回完整订单关联,请联系管理员");
|
||||
return;
|
||||
}
|
||||
emitListDataChanged(listDataEventKeys.salesOrderChanged, result.salesOrderId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||||
await settingStore.playRegisterSuccessSound();
|
||||
Message.success("套餐购买已提交");
|
||||
Message.success(fulfillAll.value ? "套餐、收款及履约已完成" : paymentVerified.value ? "套餐及已核销收款已完成" : receiveFullPayment.value ? "套餐及全额收款已完成" : "套餐购买已提交");
|
||||
await router.replace({
|
||||
name: "SalesOrderDetail",
|
||||
params: { id: result.salesOrderId },
|
||||
@@ -677,8 +922,8 @@ async function loadPageData(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
config.value = await PackageAPI.configDetail(configId.value);
|
||||
syncConfigSkuMap(config.value);
|
||||
applyConfig(config.value);
|
||||
await loadConfigSkuList(config.value);
|
||||
}
|
||||
|
||||
async function selectConfig(item: GaoPackageConfig): Promise<void> {
|
||||
@@ -686,21 +931,11 @@ async function selectConfig(item: GaoPackageConfig): Promise<void> {
|
||||
return;
|
||||
}
|
||||
config.value = await PackageAPI.configDetail(item.id);
|
||||
await loadConfigSkuList(config.value);
|
||||
syncConfigSkuMap(config.value);
|
||||
applyConfig(config.value);
|
||||
configSelectorVisible.value = false;
|
||||
}
|
||||
|
||||
async function loadConfigSkuList(value?: GaoPackageConfig): Promise<void> {
|
||||
const skuIdList = [...new Set((value?.itemList || []).map(item => item.skuId).filter(Boolean))];
|
||||
await Promise.all(skuIdList.map(async skuId => {
|
||||
try {
|
||||
skuMap[skuId] = await ProductAPI.skuDetail(skuId);
|
||||
} catch {
|
||||
// 后端会校验最终权益单位,单个 SKU 的单位加载失败不影响套餐查看
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.clearRight();
|
||||
if (userStore.hasPermissions(permissionCodes.customerPackage.create)) {
|
||||
@@ -749,6 +984,10 @@ watch(config, value => {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tips {
|
||||
font-size: .875rem;
|
||||
}
|
||||
|
||||
.customer-profile {
|
||||
margin: 1rem;
|
||||
}
|
||||
@@ -809,15 +1048,14 @@ watch(config, value => {
|
||||
}
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
padding: 6px;
|
||||
box-shadow: .25rem .25rem 1rem rgba(0, 0, 0, .08);
|
||||
border-radius: 1rem;
|
||||
|
||||
.avatar {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
flex: none;
|
||||
border-radius: .5rem;
|
||||
border-radius: .5rem !important;
|
||||
}
|
||||
|
||||
&::after {
|
||||
@@ -860,6 +1098,14 @@ watch(config, value => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.payment-item.disabled {
|
||||
color: var(--td-text-color-disabled);
|
||||
|
||||
:deep(.t-form__label) {
|
||||
color: var(--td-text-color-disabled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.time-actions {
|
||||
@@ -874,14 +1120,40 @@ watch(config, value => {
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.package-purchase-form .avatar .t-image__img) {
|
||||
width: 100%;
|
||||
.config-selector {
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: inherit;
|
||||
overflow: auto;
|
||||
|
||||
.config-option {
|
||||
|
||||
.title {
|
||||
gap: .5rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
.price {
|
||||
flex: none;
|
||||
display: flex;
|
||||
|
||||
.label {
|
||||
font-size: .75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.products {
|
||||
gap: .35rem;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
margin-top: .5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.config-selector,
|
||||
.selected-customer-popup {
|
||||
height: 70vh;
|
||||
overflow: auto;
|
||||
|
||||
@@ -10,9 +10,15 @@ interface UsePackagePurchaseOptions {
|
||||
config: Ref<GaoPackageConfig | undefined>;
|
||||
selectedCustomerList: Ref<Customer[]>;
|
||||
note: Ref<string>;
|
||||
paymentVerified: Ref<boolean>;
|
||||
paymentAmount: Ref<number | undefined>;
|
||||
receiveFullPayment: Ref<boolean>;
|
||||
fulfillAll: Ref<boolean>;
|
||||
hasPermission: (permissionCode: string) => boolean;
|
||||
buildRegisteredAt: () => number;
|
||||
buildAttachments: () => PackageAttachment[];
|
||||
buildPaymentAttachments: () => PackageAttachment[];
|
||||
buildFulfillmentAttachments: () => PackageAttachment[];
|
||||
}
|
||||
|
||||
/** 套餐配置直接购买流程,购买请求只依赖套餐配置 ID,不再关联购买事件。 */
|
||||
@@ -91,12 +97,21 @@ export function usePackagePurchase(options: UsePackagePurchaseOptions) {
|
||||
saleAmount,
|
||||
purchasedAt: options.buildRegisteredAt(),
|
||||
attachmentList: options.buildAttachments(),
|
||||
straightThrough: options.paymentVerified.value || options.receiveFullPayment.value || options.fulfillAll.value ? {
|
||||
paymentVerified: options.paymentVerified.value,
|
||||
paymentAmount: options.paymentAmount.value,
|
||||
receiveFullPayment: options.receiveFullPayment.value,
|
||||
paymentAttachmentList: options.buildPaymentAttachments(),
|
||||
fulfillAll: options.fulfillAll.value,
|
||||
fulfillmentAttachmentList: options.buildFulfillmentAttachments()
|
||||
} : undefined,
|
||||
itemList,
|
||||
remark: options.note.value.trim() || null
|
||||
});
|
||||
}
|
||||
|
||||
function validatePurchaseForm(): boolean {
|
||||
const saleAmount = parsePackageAmount(saleAmountText.value);
|
||||
if (!options.hasPermission(permissionCodes.customerPackage.create)) {
|
||||
Message.warning("当前账号没有套餐购买权限");
|
||||
return false;
|
||||
@@ -113,7 +128,7 @@ export function usePackagePurchase(options: UsePackagePurchaseOptions) {
|
||||
Message.warning("套餐当前不可购买,请检查套餐状态和有效期");
|
||||
return false;
|
||||
}
|
||||
if (parsePackageAmount(saleAmountText.value) === undefined) {
|
||||
if (saleAmount === undefined) {
|
||||
Message.warning("成交价必须是合法的元金额,最多两位小数");
|
||||
return false;
|
||||
}
|
||||
@@ -139,6 +154,39 @@ export function usePackagePurchase(options: UsePackagePurchaseOptions) {
|
||||
Message.warning("套餐至少需要保留一项正数量权益");
|
||||
return false;
|
||||
}
|
||||
const canReceiveImmediately = options.hasPermission(permissionCodes.fundReceive.create)
|
||||
&& options.hasPermission(permissionCodes.fundReceive.verify);
|
||||
const canFulfillImmediately = options.hasPermission(permissionCodes.orderFulfillment.create)
|
||||
&& options.hasPermission(permissionCodes.orderFulfillment.verify)
|
||||
&& (saleAmount === 0 || canReceiveImmediately);
|
||||
if ((options.paymentVerified.value || options.receiveFullPayment.value) && !canReceiveImmediately) {
|
||||
Message.warning("当前账号没有收款登记和核销权限");
|
||||
return false;
|
||||
}
|
||||
if (options.paymentVerified.value && (options.paymentAmount.value === undefined || options.paymentAmount.value <= 0 || options.paymentAmount.value > saleAmount)) {
|
||||
Message.warning("已核销收款金额必须大于 0 且不能超过成交价");
|
||||
return false;
|
||||
}
|
||||
if (options.fulfillAll.value && !canFulfillImmediately) {
|
||||
Message.warning("当前账号没有交易直通所需权限");
|
||||
return false;
|
||||
}
|
||||
if (options.fulfillAll.value && saleAmount !== 0 && !options.paymentVerified.value && !options.receiveFullPayment.value) {
|
||||
Message.warning("全部履约直通必须同时完成收款核销");
|
||||
return false;
|
||||
}
|
||||
if (options.fulfillAll.value && options.paymentVerified.value && options.paymentAmount.value !== saleAmount) {
|
||||
Message.warning("全部履约直通必须先完成全额收款核销");
|
||||
return false;
|
||||
}
|
||||
if ((options.paymentVerified.value || options.receiveFullPayment.value) && saleAmount !== 0 && !options.buildPaymentAttachments().length) {
|
||||
Message.warning("收款核销必须上传收款凭证照片");
|
||||
return false;
|
||||
}
|
||||
if (options.fulfillAll.value && !options.buildFulfillmentAttachments().length) {
|
||||
Message.warning("全部履约直通必须上传履约凭证照片");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -92,12 +92,10 @@ const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
const permissionStore = usePermissionSettingsStore();
|
||||
const authorizationRoleList = ref<Role[]>([]);
|
||||
const directRoleIdSet = ref(new Set<string>());
|
||||
const manageableRoleIdSet = ref(new Set<string>());
|
||||
const isSystemAdmin = computed(() => userStore.hasRoles(coreRoleCodes.admin));
|
||||
const roleCount = computed(() => authorizationRoleList.value.length);
|
||||
const permissionCount = computed(() => permissionStore.permissionList.length);
|
||||
type RoleTreeItem = Pick<Role, "id" | "name" | "parentRoleId" | "protectedRole"> & { level: number };
|
||||
type RoleTreeItem = Pick<Role, "id" | "name" | "parentRoleId" | "protectedRole" | "ownerType"> & { level: number };
|
||||
|
||||
const visibleRoleTree = computed<RoleTreeItem[]>(() => {
|
||||
if (isSystemAdmin.value) {
|
||||
@@ -147,36 +145,15 @@ function canAssignRole(role: Pick<Role, "protectedRole">): boolean {
|
||||
return isSystemAdmin.value || role.protectedRole !== true;
|
||||
}
|
||||
|
||||
function getRoleScopeLabel(role: Pick<Role, "id">): string {
|
||||
const direct = directRoleIdSet.value.has(role.id);
|
||||
const manageable = manageableRoleIdSet.value.has(role.id);
|
||||
if (direct && manageable) {
|
||||
return "直属且可管理";
|
||||
}
|
||||
return direct ? "直属角色" : "可管理角色";
|
||||
function getRoleScopeLabel(role: Pick<Role, "ownerType">): string {
|
||||
return isSystemAdmin.value ? "系统角色" : role.ownerType === "STORE" ? "本店角色" : "可管理角色";
|
||||
}
|
||||
|
||||
// ---------- 页面数据 ----------
|
||||
|
||||
onMounted(async () => {
|
||||
if (isSystemAdmin.value) {
|
||||
await permissionStore.loadAll();
|
||||
authorizationRoleList.value = permissionStore.roleList;
|
||||
return;
|
||||
}
|
||||
|
||||
await permissionStore.loadAll();
|
||||
const [manageableRoleList, currentRoleList] = await Promise.all([
|
||||
permissionStore.loadManageableRoles(),
|
||||
permissionStore.loadCurrentRoleDetails()
|
||||
]);
|
||||
const roleMap = new Map<string, Role>();
|
||||
for (const role of [...currentRoleList, ...manageableRoleList]) {
|
||||
roleMap.set(role.id, role);
|
||||
}
|
||||
authorizationRoleList.value = Array.from(roleMap.values());
|
||||
directRoleIdSet.value = new Set(currentRoleList.map(item => item.id).filter((id): id is string => Boolean(id)));
|
||||
manageableRoleIdSet.value = new Set(manageableRoleList.map(item => item.id).filter((id): id is string => Boolean(id)));
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -186,7 +186,7 @@ function clearPermissionState(): void {
|
||||
// ---------- 授权范围 ----------
|
||||
|
||||
async function loadAuthorizationScope(): Promise<void> {
|
||||
candidateRoleList.value = isSystemAdmin.value ? permissionStore.roleList : await permissionStore.loadManageableRoles();
|
||||
candidateRoleList.value = permissionStore.roleList;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
|
||||
@@ -330,7 +330,7 @@ async function fillForm(): Promise<void> {
|
||||
await permissionStore.loadAll();
|
||||
await loadAuthorizationScope();
|
||||
if (isCreateMode.value) {
|
||||
parentRoleOptions.value = await permissionStore.loadCreateParentGrantableRoles();
|
||||
parentRoleOptions.value = filterStoreParentRoles(await permissionStore.loadCreateParentGrantableRoles());
|
||||
formModel.parentRoleId = parentRoleOptions.value[0]?.id || "";
|
||||
return;
|
||||
}
|
||||
@@ -355,30 +355,38 @@ async function reloadCurrentRole(): Promise<void> {
|
||||
childRoleIdList
|
||||
});
|
||||
parentRoleOptions.value = canEditParentRole.value
|
||||
? await permissionStore.loadParentGrantableRoles(current.id)
|
||||
? filterStoreParentRoles(await permissionStore.loadParentGrantableRoles(current.id))
|
||||
: [];
|
||||
if (current.parentRole?.id && !parentRoleOptions.value.some(item => item.id === current.parentRoleId)) {
|
||||
const currentParent = current.parentRole;
|
||||
const canKeepCurrentParent = isSystemAdmin.value || Boolean(currentParent && (
|
||||
currentParent.moduleCode === moduleCode && currentParent.code === "STORE_MANAGER"
|
||||
|| permissionStore.roleList.some(item => item.id === currentParent.id)
|
||||
));
|
||||
if (currentParent?.id && canKeepCurrentParent && !parentRoleOptions.value.some(item => item.id === current.parentRoleId)) {
|
||||
parentRoleOptions.value.unshift({
|
||||
...current.parentRole,
|
||||
id: current.parentRole.id,
|
||||
permissionIdList: current.parentRole.permissionIdList || current.parentRole.permissionList?.map(item => item.id) || [],
|
||||
childRoleIdList: current.parentRole.childRoleIdList || current.parentRole.childRoleList?.map(item => item.id).filter((id): id is string => Boolean(id)) || [],
|
||||
delegationPermissionIdList: current.parentRole.delegationPermissionIdList || current.parentRole.delegationPermissionList?.map(item => item.id) || []
|
||||
...currentParent,
|
||||
id: currentParent.id,
|
||||
permissionIdList: currentParent.permissionIdList || currentParent.permissionList?.map(item => item.id) || [],
|
||||
childRoleIdList: currentParent.childRoleIdList || currentParent.childRoleList?.map(item => item.id).filter((id): id is string => Boolean(id)) || [],
|
||||
delegationPermissionIdList: currentParent.delegationPermissionIdList || currentParent.delegationPermissionList?.map(item => item.id) || []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAuthorizationScope(): Promise<void> {
|
||||
candidateRoleList.value = isSystemAdmin.value ? permissionStore.roleList : await permissionStore.loadManageableRoles();
|
||||
inheritanceRoleList.value = mergeRoleList(permissionStore.roleList, candidateRoleList.value);
|
||||
/** 限制门店角色可选择的管理父级。 */
|
||||
function filterStoreParentRoles(roleList: Role[]): Role[] {
|
||||
if (isSystemAdmin.value) {
|
||||
return roleList;
|
||||
}
|
||||
|
||||
const storeRoleIdSet = new Set(permissionStore.roleList.map(item => item.id));
|
||||
return roleList.filter(role => storeRoleIdSet.has(role.id)
|
||||
|| (role.moduleCode === moduleCode && role.code === "STORE_MANAGER"));
|
||||
}
|
||||
|
||||
function mergeRoleList(...roleLists: Role[][]): Role[] {
|
||||
const roleMap = new Map<string, Role>();
|
||||
for (const role of roleLists.flat()) {
|
||||
roleMap.set(role.id, role);
|
||||
}
|
||||
return Array.from(roleMap.values());
|
||||
async function loadAuthorizationScope(): Promise<void> {
|
||||
candidateRoleList.value = permissionStore.roleList;
|
||||
inheritanceRoleList.value = [...permissionStore.roleList];
|
||||
}
|
||||
|
||||
// ---------- 保存 ----------
|
||||
|
||||
@@ -53,7 +53,6 @@ const permissionStore = usePermissionSettingsStore();
|
||||
const userStore = useUserStore();
|
||||
const isRefreshing = ref(false);
|
||||
const deletableRoleIdSet = ref(new Set<string>());
|
||||
const directRoleIdSet = ref(new Set<string>());
|
||||
|
||||
// ---------- 顶部导航 ----------
|
||||
|
||||
@@ -80,9 +79,11 @@ const sortedRoles = computed<Array<Role & { level: number }>>(() => {
|
||||
async function removeRole(id: string): Promise<void> {
|
||||
try {
|
||||
await permissionStore.removeRole(id);
|
||||
} catch (error) {
|
||||
await refreshAuthorizationScope();
|
||||
await permissionStore.loadAll(true);
|
||||
await refreshAuthorizationScope();
|
||||
} catch (error) {
|
||||
await permissionStore.loadAll(true);
|
||||
await refreshAuthorizationScope();
|
||||
Message.error(getErrorMessage(error, "角色删除失败"));
|
||||
}
|
||||
}
|
||||
@@ -95,12 +96,7 @@ function canDeleteRole(role: Role): boolean {
|
||||
}
|
||||
|
||||
function getRoleScopeLabel(role: Role): string {
|
||||
const direct = directRoleIdSet.value.has(role.id);
|
||||
const manageable = deletableRoleIdSet.value.has(role.id);
|
||||
if (direct && manageable) {
|
||||
return "直属且可管理";
|
||||
}
|
||||
return direct ? "直属角色" : "可管理角色";
|
||||
return userStore.hasRoles(coreRoleCodes.admin) ? "系统角色" : role.ownerType === "STORE" ? "本店角色" : "可管理角色";
|
||||
}
|
||||
|
||||
// ---------- 页面数据 ----------
|
||||
@@ -121,9 +117,7 @@ onMounted(async () => {
|
||||
if (canCreateRole.value) {
|
||||
navBarStore.setRightText("添加", "var(--td-brand-color)", toCreate);
|
||||
}
|
||||
if (userStore.hasRoles(coreRoleCodes.admin)) {
|
||||
await permissionStore.loadAll();
|
||||
}
|
||||
await refreshAuthorizationScope();
|
||||
if (!displayRoleList.value.length) {
|
||||
displayRoleList.value = getDisplayRoleList();
|
||||
@@ -163,23 +157,8 @@ async function refreshAuthorizationScope(): Promise<void> {
|
||||
deletableRoleIdSet.value = new Set(permissionStore.roleList.map(item => item.id));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const [manageableRoleList, currentRoleList] = await Promise.all([
|
||||
permissionStore.loadManageableRoles(),
|
||||
permissionStore.loadCurrentRoleDetails()
|
||||
]);
|
||||
const roleMap = new Map<string, Role>();
|
||||
for (const role of [...currentRoleList, ...manageableRoleList]) {
|
||||
roleMap.set(role.id, role);
|
||||
}
|
||||
displayRoleList.value = Array.from(roleMap.values());
|
||||
directRoleIdSet.value = new Set(currentRoleList.map(item => item.id).filter((id): id is string => Boolean(id)));
|
||||
deletableRoleIdSet.value = new Set(manageableRoleList.map(item => item.id).filter((id): id is string => Boolean(id)));
|
||||
} catch {
|
||||
directRoleIdSet.value = new Set<string>();
|
||||
deletableRoleIdSet.value = new Set<string>();
|
||||
}
|
||||
displayRoleList.value = permissionStore.roleList;
|
||||
deletableRoleIdSet.value = new Set(permissionStore.roleList.map(item => item.id));
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
@@ -217,7 +217,7 @@ function clearPermissionState(): void {
|
||||
// ---------- 授权范围 ----------
|
||||
|
||||
async function loadAuthorizationScope(): Promise<void> {
|
||||
candidateRoleList.value = isSystemAdmin.value ? permissionStore.roleList : await permissionStore.loadManageableRoles();
|
||||
candidateRoleList.value = permissionStore.roleList;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
|
||||
@@ -51,6 +51,7 @@ import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PointAccount as PointAccountData } from "@/types/Point";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
@@ -149,7 +150,7 @@ async function toAdjust(): Promise<void> {
|
||||
// ---------- 展示 ----------
|
||||
|
||||
function formatPoints(value?: number): string {
|
||||
return `${(value ?? 0).toLocaleString("zh-CN")} 分`;
|
||||
return `${formatWanInteger(value ?? 0)} 分`;
|
||||
}
|
||||
|
||||
function formatTimestamp(timestamp?: number): string {
|
||||
@@ -165,7 +166,7 @@ function formatTimestamp(timestamp?: number): string {
|
||||
|
||||
function formatSignedPoints(value?: number): string {
|
||||
const pointValue = value ?? 0;
|
||||
return pointValue < 0 ? `扣除 ${Math.abs(pointValue).toLocaleString("zh-CN")} 分` : `增加 ${pointValue.toLocaleString("zh-CN")} 分`;
|
||||
return pointValue < 0 ? `扣除 ${formatWanInteger(Math.abs(pointValue))} 分` : `增加 ${formatWanInteger(pointValue)} 分`;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.point.accountRead" class="point-account-list">
|
||||
<div class="filters">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="customer"
|
||||
@@ -19,12 +19,12 @@
|
||||
</t-input>
|
||||
</div>
|
||||
<t-pull-down-refresh
|
||||
class="list-wrapper"
|
||||
v-model="isRefreshing"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="reload"
|
||||
@scrolltolower="load"
|
||||
>
|
||||
<div class="list-wrap">
|
||||
<t-cell-group v-if="pageResult.list.length" class="list" theme="card">
|
||||
<customer-cell
|
||||
v-entrance-transition="index * 30"
|
||||
@@ -46,6 +46,7 @@
|
||||
</customer-cell>
|
||||
</t-cell-group>
|
||||
<div class="center-tips" v-text="loadStateText" />
|
||||
</div>
|
||||
</t-pull-down-refresh>
|
||||
<customer-selector
|
||||
v-model="selectedCustomerId"
|
||||
@@ -63,6 +64,7 @@ import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import type { PointAccount, PointAccountPage } from "@/types/Point";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
@@ -195,7 +197,7 @@ async function load(): Promise<void> {
|
||||
// ---------- 展示 ----------
|
||||
|
||||
function formatPoints(value?: number): string {
|
||||
return `${(value ?? 0).toLocaleString("zh-CN")} 分`;
|
||||
return `${formatWanInteger(value ?? 0)} 分`;
|
||||
}
|
||||
|
||||
function getBalanceTheme(value?: number): string {
|
||||
@@ -255,8 +257,6 @@ onMounted(async () => {
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: #F5F5F8;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
flex-direction: column;
|
||||
|
||||
.customer {
|
||||
@@ -265,16 +265,19 @@ onMounted(async () => {
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
background: var(--td-bg-color-container);
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.list-wrapper {
|
||||
.list-wrap {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
min-height: 70vh;
|
||||
flex-direction: column;
|
||||
|
||||
.list {
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
|
||||
@@ -300,13 +303,6 @@ onMounted(async () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.center-tips {
|
||||
color: #52607a;
|
||||
padding: 1rem;
|
||||
font-size: .8125rem;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
|
||||
@@ -83,6 +83,7 @@ import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PointAccount } from "@/types/Point";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
@@ -113,7 +114,7 @@ const selectedCustomerId = ref(String(route.query.customerId || ""));
|
||||
const selectedCustomer = ref<Customer>();
|
||||
const account = ref<PointAccount>();
|
||||
const selectorVisible = ref(false);
|
||||
const balanceText = computed(() => `当前余额:${(account.value?.balance ?? 0).toLocaleString("zh-CN")} 分`);
|
||||
const balanceText = computed(() => `当前余额:${formatWanInteger(account.value?.balance ?? 0)} 分`);
|
||||
|
||||
async function handleCustomerChange(value: string | string[]): Promise<void> {
|
||||
selectedCustomerId.value = Array.isArray(value) ? String(value[0] || "") : value;
|
||||
|
||||
@@ -91,6 +91,7 @@ import type { EventItem } from "@/types/EventItem";
|
||||
import type { EventRecord } from "@/types/EventRecord";
|
||||
import type { PointLedger, PointRule, PointRuleStatus } from "@/types/Point";
|
||||
import { formatEventNumberValue, getEventValueUnitText } from "@/utils/eventValue";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
@@ -220,18 +221,18 @@ function getPointDeltaText(pointDelta?: number): string {
|
||||
if (pointDelta === undefined || pointDelta === null) {
|
||||
return "-";
|
||||
}
|
||||
return `${0 < pointDelta ? "获得" : "消耗"} ${Math.abs(pointDelta)} 分`;
|
||||
return `${0 < pointDelta ? "获得" : "消耗"} ${formatWanInteger(Math.abs(pointDelta))} 分`;
|
||||
}
|
||||
|
||||
function getPointText(value?: number | null): string {
|
||||
return value === undefined || value === null ? "-" : `${value} 分`;
|
||||
return value === undefined || value === null ? "-" : `${formatWanInteger(value)} 分`;
|
||||
}
|
||||
|
||||
function getSignedPointText(value?: number | null): string {
|
||||
if (value === undefined || value === null) {
|
||||
return "-";
|
||||
}
|
||||
return `${0 < value ? "获得" : "消耗"} ${Math.abs(value)} 分`;
|
||||
return `${0 < value ? "获得" : "消耗"} ${formatWanInteger(Math.abs(value))} 分`;
|
||||
}
|
||||
|
||||
function getEventValueTypeText(event: EventItem): string {
|
||||
@@ -252,7 +253,7 @@ function getRulePointText(rule: PointRule): string {
|
||||
if (rule.pointValue === undefined || rule.pointValue === null) {
|
||||
return "-";
|
||||
}
|
||||
return `${0 < rule.pointValue ? "发放" : "消耗"} ${Math.abs(rule.pointValue)} 分`;
|
||||
return `${0 < rule.pointValue ? "发放" : "消耗"} ${formatWanInteger(Math.abs(rule.pointValue))} 分`;
|
||||
}
|
||||
|
||||
function getRuleScriptText(rule: PointRule): string {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.point.ledgerRead" class="point-ledger-list">
|
||||
<div class="filters">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="customerKeyword"
|
||||
class="customer"
|
||||
@@ -96,7 +96,7 @@
|
||||
<span>时间:</span>
|
||||
<pass-time-label :timestamp="item.occurredAt" underline />
|
||||
</div>
|
||||
<div v-text="`余额:${item.balanceBefore ?? 0} → ${item.balanceAfter ?? 0}`" />
|
||||
<div v-text="`余额:${formatPointValue(item.balanceBefore)} → ${formatPointValue(item.balanceAfter)}`" />
|
||||
<div v-text="item.remark" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -142,7 +142,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { DropdownValue } from "tdesign-mobile-vue";
|
||||
import { PassTimeLabel, Time, Toolkit } from "timi-web";
|
||||
import { PassTimeLabel, Toolkit } from "timi-web";
|
||||
import { type PageResult, useUserStore } from "timi-web-api";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
@@ -151,7 +151,9 @@ import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PointLedger, PointLedgerChangeType, PointLedgerPage } from "@/types/Point";
|
||||
import { getCustomerPhotoURL } from "@/utils/customer";
|
||||
import { buildPresetDateRange, parseDateTime } from "@/utils/date";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
type DateFilter = "all" | "today" | "last7" | "last30" | "custom";
|
||||
@@ -175,7 +177,7 @@ const customerKeyword = ref("");
|
||||
const selectorVisible = ref(false);
|
||||
const changeTypeFilter = ref("ALL");
|
||||
const dateFilter = ref<DateFilter>("last30");
|
||||
const dateRange = ref<[string, string]>(buildDateRange(dateFilter.value));
|
||||
const dateRange = ref<[string, string]>(buildPresetDateRange("last30"));
|
||||
const startDraft = ref("");
|
||||
const endDraft = ref("");
|
||||
const startDateVisible = ref(false);
|
||||
@@ -253,7 +255,7 @@ async function selectDateFilter(value: DropdownValue): Promise<void> {
|
||||
}
|
||||
dateFilter.value = String(value) as DateFilter;
|
||||
if (dateFilter.value !== "custom") {
|
||||
dateRange.value = buildDateRange(dateFilter.value);
|
||||
dateRange.value = buildPresetDateRange(dateFilter.value);
|
||||
await reload();
|
||||
}
|
||||
}
|
||||
@@ -385,7 +387,11 @@ function buildListOptions(): { storeId: string } {
|
||||
|
||||
function getLedgerDelta(item: PointLedger): string {
|
||||
const value = item.pointDelta ?? 0;
|
||||
return `${0 < value ? "+" : "-"}${Math.abs(value)} 分`;
|
||||
return `${0 < value ? "+" : "-"}${formatWanInteger(Math.abs(value))} 分`;
|
||||
}
|
||||
|
||||
function formatPointValue(value?: number): string {
|
||||
return value === undefined || value === null ? "-" : formatWanInteger(value);
|
||||
}
|
||||
|
||||
function getLedgerShortType(item: PointLedger): string {
|
||||
@@ -436,39 +442,14 @@ async function toDetail(item: PointLedger): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 时间 ----------
|
||||
|
||||
function buildDateRange(type: DateFilter): [string, string] {
|
||||
if (type === "all") {
|
||||
return ["", ""];
|
||||
}
|
||||
const end = new Date();
|
||||
end.setHours(23, 59, 0, 0);
|
||||
if (type === "custom") {
|
||||
return ["", Time.formatDateTime(end)];
|
||||
}
|
||||
const begin = new Date(end);
|
||||
const dayCount = type === "today" ? 0 : type === "last7" ? 6 : 29;
|
||||
begin.setDate(begin.getDate() - dayCount);
|
||||
begin.setHours(0, 0, 0, 0);
|
||||
return [Time.formatDateTime(begin), Time.formatDateTime(end)];
|
||||
}
|
||||
|
||||
function buildUnixRange(): [number, number] {
|
||||
if (!dateRange.value[0] && !dateRange.value[1]) {
|
||||
return [0, Date.now()];
|
||||
}
|
||||
return [toTimestamp(dateRange.value[0], false), toTimestamp(dateRange.value[1], true)];
|
||||
}
|
||||
|
||||
function toTimestamp(value: string, isEnd: boolean): number {
|
||||
if (!value) {
|
||||
return isEnd ? Date.now() : 0;
|
||||
}
|
||||
const [dateText, timeText = isEnd ? "23:59" : "00:00"] = value.split(" ");
|
||||
const [year, month, day] = dateText.split("-").map(Number);
|
||||
const [hour, minute] = timeText.split(":").map(Number);
|
||||
return new Date(year, month - 1, day, hour || 0, minute || 0, isEnd ? 59 : 0).getTime();
|
||||
return [
|
||||
parseDateTime(dateRange.value[0], false).getTime(),
|
||||
parseDateTime(dateRange.value[1], true).getTime()
|
||||
];
|
||||
}
|
||||
|
||||
// ---------- 页面数据 ----------
|
||||
@@ -501,7 +482,6 @@ onUnmounted(() => {
|
||||
|
||||
<style scoped lang="less">
|
||||
.point-ledger-list {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding: var(--app-nav-height) 0 1rem;
|
||||
flex-direction: column;
|
||||
@@ -514,8 +494,6 @@ onUnmounted(() => {
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: #F5F5F8;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
flex-direction: column;
|
||||
|
||||
.customer {
|
||||
@@ -524,7 +502,7 @@ onUnmounted(() => {
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
background: var(--td-bg-color-container);
|
||||
z-index: 1;
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
@@ -533,8 +511,7 @@ onUnmounted(() => {
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
z-index: -1;
|
||||
border: 1px solid var(--td-component-border);
|
||||
overflow: hidden;
|
||||
margin-top: -1rem;
|
||||
border-top: none;
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.pointRedeemSku.manage" class="redeem-sku-edit">
|
||||
<t-form class="form" v-entrance-transition>
|
||||
<product-selector
|
||||
v-model="selection"
|
||||
:selected-product="form.product"
|
||||
required-mark
|
||||
@select="handleProductSelection"
|
||||
/>
|
||||
<t-form-item label="默认积分" required-mark>
|
||||
<t-input
|
||||
v-model.trim="form.pointText"
|
||||
type="number"
|
||||
align="right"
|
||||
borderless
|
||||
placeholder="每单位所需积分"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="配置状态" content-align="right" arrow @click="statusVisible = true">
|
||||
<span v-text="statusText(form.status)" />
|
||||
</t-form-item>
|
||||
<t-form-item label="累计上限">
|
||||
<t-input v-model.trim="form.totalText" type="number" align="right" borderless placeholder="不限" />
|
||||
</t-form-item>
|
||||
<t-form-item label="每日上限">
|
||||
<t-input v-model.trim="form.dailyText" type="number" align="right" borderless placeholder="不限" />
|
||||
</t-form-item>
|
||||
<t-form-item label="每月上限">
|
||||
<t-input v-model.trim="form.monthlyText" type="number" align="right" borderless placeholder="不限" />
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<span class="tips gray">数量上限按兑换业务单位计算,最多三位小数。留空表示不限</span>
|
||||
</t-form-item>
|
||||
<t-form-item label="备注">
|
||||
<t-textarea v-model.trim="form.remark" maxlength="500" autosize />
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
<t-button
|
||||
v-if="form.id"
|
||||
class="cell-button"
|
||||
theme="danger"
|
||||
v-entrance-transition="70"
|
||||
content="删除"
|
||||
@click="remove"
|
||||
/>
|
||||
</div>
|
||||
<t-popup v-model="statusVisible" placement="bottom">
|
||||
<t-picker
|
||||
v-model="statusDraft"
|
||||
:columns="statusOptions"
|
||||
title="配置状态"
|
||||
@cancel="statusVisible = false"
|
||||
@confirm="confirmStatus"
|
||||
/>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
import ProductSelector from "@/components/ProductSelector.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { PointRedeemSku, PointRedeemSkuStatus } from "@/types/Point";
|
||||
import type { ProductSelection } from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { normalizePackageQuantity } from "@/utils/package";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({ name: "PointRedeemSkuEdit" });
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const navBarStore = useNavBarStore();
|
||||
const selection = ref<{ skuId: string; skuUnitId: string }>();
|
||||
const statusVisible = ref(false);
|
||||
const statusDraft = ref<Array<string | number>>(["DRAFT"]);
|
||||
const isSaving = ref(false);
|
||||
const form = reactive({
|
||||
id: "",
|
||||
product: undefined as PointRedeemSku["product"],
|
||||
sku: undefined as PointRedeemSku["sku"],
|
||||
unit: undefined as PointRedeemSku["unit"],
|
||||
pointText: "",
|
||||
status: "DRAFT" as PointRedeemSkuStatus,
|
||||
totalText: "",
|
||||
dailyText: "",
|
||||
monthlyText: "",
|
||||
remark: ""
|
||||
});
|
||||
const statusOptions = [
|
||||
{ label: "草稿", value: "DRAFT" },
|
||||
{ label: "启用", value: "ACTIVE" },
|
||||
{ label: "停用", value: "INACTIVE" }
|
||||
];
|
||||
|
||||
function statusText(status: PointRedeemSkuStatus): string {
|
||||
return ({ DRAFT: "草稿", ACTIVE: "启用", INACTIVE: "停用", DELETED: "已删除" } as Record<string, string>)[status];
|
||||
}
|
||||
|
||||
function parsePoint(): number | undefined {
|
||||
const value = Number(form.pointText);
|
||||
return Number.isSafeInteger(value) && 0 < value ? value : undefined;
|
||||
}
|
||||
|
||||
function parseLimit(value: string): string | null | undefined {
|
||||
return value ? normalizePackageQuantity(value) : null;
|
||||
}
|
||||
|
||||
function handleProductSelection(value: ProductSelection): void {
|
||||
form.product = value.product;
|
||||
form.sku = value.sku;
|
||||
form.unit = value.unit;
|
||||
}
|
||||
|
||||
function confirmStatus(value: Array<string | number>): void {
|
||||
form.status = String(value[0]) as PointRedeemSkuStatus;
|
||||
statusVisible.value = false;
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const id = String(route.params.id || "");
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
const item = await PointAPI.redeemSkuDetail(id);
|
||||
form.id = item.id || "";
|
||||
form.product = item.product;
|
||||
form.sku = item.sku;
|
||||
form.unit = item.unit;
|
||||
selection.value = item.skuId && item.skuUnitId ? { skuId: item.skuId, skuUnitId: item.skuUnitId } : undefined;
|
||||
form.pointText = String(item.defaultPointCost || "");
|
||||
form.status = item.status || "DRAFT";
|
||||
form.totalText = item.maxTotalQuantity === null || item.maxTotalQuantity === undefined ? "" : String(item.maxTotalQuantity);
|
||||
form.dailyText = item.maxDailyQuantity === null || item.maxDailyQuantity === undefined ? "" : String(item.maxDailyQuantity);
|
||||
form.monthlyText = item.maxMonthlyQuantity === null || item.maxMonthlyQuantity === undefined ? "" : String(item.maxMonthlyQuantity);
|
||||
form.remark = item.remark || "";
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
const point = parsePoint();
|
||||
const total = parseLimit(form.totalText);
|
||||
const daily = parseLimit(form.dailyText);
|
||||
const monthly = parseLimit(form.monthlyText);
|
||||
if (isSaving.value || !selection.value || !point || total === undefined || daily === undefined || monthly === undefined) {
|
||||
Message.warning("请完整填写产品、积分和合法数量上限");
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const data: PointRedeemSku = {
|
||||
id: form.id || undefined,
|
||||
skuId: selection.value.skuId,
|
||||
skuUnitId: selection.value.skuUnitId,
|
||||
status: form.status,
|
||||
defaultPointCost: point,
|
||||
maxTotalQuantity: total,
|
||||
maxDailyQuantity: daily,
|
||||
maxMonthlyQuantity: monthly,
|
||||
remark: form.remark || null
|
||||
};
|
||||
if (form.id) {
|
||||
await PointAPI.redeemSkuUpdate(data);
|
||||
} else {
|
||||
await PointAPI.redeemSkuCreate(data);
|
||||
}
|
||||
Message.success("兑换配置已保存");
|
||||
await router.replace({ name: "PointRedeemSkuList" });
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "兑换配置保存失败"));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(): Promise<void> {
|
||||
if (!form.id || isSaving.value) {
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await PointAPI.redeemSkuRemove(form.id);
|
||||
Message.success("兑换配置已标记删除");
|
||||
await router.replace({ name: "PointRedeemSkuList" });
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "兑换配置删除失败"));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.setRightText("保存", "var(--td-brand-color)", save);
|
||||
try {
|
||||
await load();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "兑换配置加载失败"));
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => navBarStore.clearRight());
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.redeem-sku-edit {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding: calc(var(--app-nav-height) + 1rem) 0 2rem;
|
||||
flex-direction: column;
|
||||
|
||||
.tips {
|
||||
font-size: .875rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,248 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.pointRedeemSku.manage" class="redeem-sku-list">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="keyword"
|
||||
type="search"
|
||||
borderless
|
||||
clearable
|
||||
placeholder="搜索产品名称、编码或 SKU"
|
||||
/>
|
||||
</div>
|
||||
<t-pull-down-refresh v-model="isRefreshing" :refresh-timeout="30000" @refresh="reload" @scrolltolower="load">
|
||||
<t-cell-group v-if="result.list.length" theme="card">
|
||||
<t-cell
|
||||
v-for="(item, index) in result.list"
|
||||
:key="item.id"
|
||||
class="item"
|
||||
arrow
|
||||
v-entrance-transition="index * 30"
|
||||
@click="toEdit(item)"
|
||||
>
|
||||
<template #left-icon>
|
||||
<t-image
|
||||
v-if="getProductPhoto(item)"
|
||||
:src="getProductPhoto(item)"
|
||||
:alt="item.product?.name || item.sku?.name || '产品图片'"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="avatar fallback"
|
||||
v-text="(item.product?.name || item.sku?.name || '产').slice(0, 1)"
|
||||
/>
|
||||
</template>
|
||||
<template #title>
|
||||
<span class="clip-text" v-text="item.product?.name || item.sku?.name || '未命名产品'" />
|
||||
</template>
|
||||
<template #note>
|
||||
<span class="orange keep-text" v-text="formatPoint(item.defaultPointCost)" />
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="description">
|
||||
<t-tag
|
||||
size="small"
|
||||
:theme="item.status === 'ACTIVE' ? 'success' : 'default'"
|
||||
:content="statusText(item.status)"
|
||||
/>
|
||||
<product-sku-tags
|
||||
:product-name="item.product?.name"
|
||||
:fallback="item.sku?.specSummary || item.sku?.name || '默认 SKU'"
|
||||
:unit="item.unit?.name"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<t-empty v-else :description="isLoading ? '正在加载兑换配置' : '暂无兑换配置'" />
|
||||
<div class="tips" v-text="isNoMore ? `共 ${result.total} 条配置` : '上拉加载更多'" />
|
||||
</t-pull-down-refresh>
|
||||
</div>
|
||||
<nav-bar-action-menu
|
||||
v-can="permissionCodes.pointRedeemSku.manage"
|
||||
:actions="[{ key: 'create', icon: 'add', text: '新增兑换配置', theme: 'primary', action: toCreate }]"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Toolkit } from "timi-web";
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
import ProductSkuTags from "@/components/ProductSkuTags.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { PointRedeemSku, PointRedeemSkuStatus } from "@/types/Point";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { getProductPhotoURL } from "@/utils/product";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({ name: "PointRedeemSkuList" });
|
||||
const router = useRouter();
|
||||
const navBarStore = useNavBarStore();
|
||||
const result = reactive({ total: 0, list: [] as PointRedeemSku[] });
|
||||
const keyword = shallowRef("");
|
||||
const index = ref(0);
|
||||
const isLoading = ref(false);
|
||||
const isRefreshing = ref(false);
|
||||
const isNoMore = ref(false);
|
||||
const pageSize = 20;
|
||||
let reloadRequested = false;
|
||||
|
||||
async function reload(): Promise<void> {
|
||||
if (isLoading.value) {
|
||||
reloadRequested = true;
|
||||
return;
|
||||
}
|
||||
index.value = 0;
|
||||
result.total = 0;
|
||||
result.list = [];
|
||||
isNoMore.value = false;
|
||||
try {
|
||||
await load();
|
||||
} finally {
|
||||
isRefreshing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
if (isLoading.value || isNoMore.value) {
|
||||
return;
|
||||
}
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const page = await PointAPI.redeemSkuList({
|
||||
index: index.value,
|
||||
size: pageSize,
|
||||
keyword: keyword.value.trim() || undefined
|
||||
});
|
||||
const list = page.list || [];
|
||||
result.list = result.list.concat(list);
|
||||
result.total = page.total || 0;
|
||||
index.value++;
|
||||
isNoMore.value = result.total <= result.list.length || list.length < pageSize;
|
||||
} catch {
|
||||
Message.error("兑换配置加载失败");
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
if (reloadRequested) {
|
||||
reloadRequested = false;
|
||||
await reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const reloadByKeyword = Toolkit.debounce(async () => {
|
||||
await reload();
|
||||
}, false);
|
||||
|
||||
function formatPoint(value?: number): string {
|
||||
return `${formatWanInteger(value ?? 0)} 分`;
|
||||
}
|
||||
|
||||
function getProductPhoto(item: PointRedeemSku): string {
|
||||
const product = item.product || item.sku;
|
||||
return product ? getProductPhotoURL(product) : "";
|
||||
}
|
||||
|
||||
function statusText(status?: PointRedeemSkuStatus): string {
|
||||
return ({
|
||||
DRAFT: "草稿",
|
||||
ACTIVE: "启用",
|
||||
INACTIVE: "停用",
|
||||
DELETED: "已删除"
|
||||
} as Record<string, string>)[status || ""] || "未知";
|
||||
}
|
||||
|
||||
async function toCreate(): Promise<void> {
|
||||
await router.push({ name: "PointRedeemSkuCreate" });
|
||||
}
|
||||
|
||||
async function toEdit(item: PointRedeemSku): Promise<void> {
|
||||
if (item.id) {
|
||||
await router.push({ name: "PointRedeemSkuEdit", params: { id: item.id } });
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.setCustomRightVisible(true);
|
||||
await reload();
|
||||
});
|
||||
|
||||
watch(keyword, () => {
|
||||
reloadByKeyword();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
reloadByKeyword.cancel();
|
||||
navBarStore.clearRight();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.redeem-sku-list {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding: var(--app-nav-height) 0 5rem;
|
||||
flex-direction: column;
|
||||
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
flex-direction: column;
|
||||
|
||||
.keyword {
|
||||
--td-input-vertical-padding: .25rem 1rem;
|
||||
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
|
||||
.avatar {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
}
|
||||
|
||||
.description {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.title {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.tips {
|
||||
color: var(--td-text-color-secondary);
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.redeem-sku-list {
|
||||
.filters {
|
||||
background: #10161f;
|
||||
}
|
||||
|
||||
.fallback {
|
||||
color: #ccfbf1;
|
||||
background: #115e59;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,415 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.pointRedemption.create" class="redemption-create">
|
||||
<t-form class="form" label-width="7rem" v-entrance-transition>
|
||||
<t-form-item label="客户" required-mark>
|
||||
<t-input
|
||||
:model-value="customerName || '请选择客户'"
|
||||
class="customer"
|
||||
readonly
|
||||
borderless
|
||||
placeholder="选择或扫码客户"
|
||||
@click="customerVisible = true"
|
||||
>
|
||||
<template #suffix-icon>
|
||||
<div class="actions">
|
||||
<t-button
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
size="extra-small"
|
||||
@click.stop="customerVisible = true"
|
||||
>选择</t-button>
|
||||
<t-button theme="primary" size="extra-small" @click.stop="toggleScanner">
|
||||
<span v-text="scannerVisible ? '关闭扫码' : '扫码'" />
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-input>
|
||||
</t-form-item>
|
||||
<div v-if="scannerVisible" class="code-scanner-wrapper">
|
||||
<code-scanner
|
||||
visible
|
||||
:status-text="scanStatus"
|
||||
active-text="正在识别客户编码,请将条码或二维码移入取景框。"
|
||||
@decode="handleDecodedText"
|
||||
@status-change="handleScanStatusChange"
|
||||
/>
|
||||
</div>
|
||||
<customer-profile-card
|
||||
v-if="customer"
|
||||
class="customer-profile"
|
||||
:customer="customer"
|
||||
v-entrance-transition
|
||||
/>
|
||||
<t-form-item v-if="customer" label="积分余额" content-align="right">
|
||||
<span class="orange" v-text="pointBalanceText" />
|
||||
</t-form-item>
|
||||
<t-form-item label="兑换商品" required-mark content-align="right" arrow @click="skuVisible = true">
|
||||
<span v-text="skuName || '请选择兑换商品'" />
|
||||
</t-form-item>
|
||||
<product-sku-form-item
|
||||
:sku="selectedSku?.sku"
|
||||
:unit="selectedSku?.unit"
|
||||
/>
|
||||
<t-form-item label="兑换数量" content-align="right" required-mark>
|
||||
<t-stepper
|
||||
v-model="quantity"
|
||||
size="large"
|
||||
:min="quantityStep"
|
||||
:step="quantityStep"
|
||||
:integer="quantityIsInteger"
|
||||
theme="outline"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="预计消耗积分" content-align="right">
|
||||
<span v-text="estimatedPointText" />
|
||||
</t-form-item>
|
||||
<template v-if="canAdjust">
|
||||
<t-form-item label="实际消耗扣分">
|
||||
<t-input v-model.trim="actualPointText" type="number" align="right" borderless placeholder="默认扣分" />
|
||||
</t-form-item>
|
||||
<t-form-item label="备注">
|
||||
<t-textarea v-model="remark" maxlength="500" autosize />
|
||||
</t-form-item>
|
||||
</template>
|
||||
<div class="photo-wrap">
|
||||
<media-selector
|
||||
v-model="photoUrls"
|
||||
v-model:photo-items="photos"
|
||||
:upload="uploadPhotoList"
|
||||
edit-mode
|
||||
required
|
||||
title="兑换凭证照片"
|
||||
/>
|
||||
</div>
|
||||
</t-form>
|
||||
</div>
|
||||
<customer-selector
|
||||
v-model="customerId"
|
||||
v-model:visible="customerVisible"
|
||||
:enable-scan="false"
|
||||
@change="loadCustomer"
|
||||
/>
|
||||
<bottom-popup
|
||||
v-model="skuVisible"
|
||||
title="选择兑换商品"
|
||||
height="70vh"
|
||||
right-button-text=""
|
||||
@left-button-click="closeSkuPicker"
|
||||
>
|
||||
<div class="sku-picker">
|
||||
<t-cell
|
||||
v-for="item in skuList"
|
||||
:key="item.id"
|
||||
:title="item.product?.name || item.sku?.name || '未命名产品'"
|
||||
:note="`${formatPoint(item.defaultPointCost)} / ${item.unit?.name || '单位未知'}`"
|
||||
class="item"
|
||||
arrow
|
||||
@click="selectSku(item)"
|
||||
>
|
||||
<template #left-icon>
|
||||
<t-image
|
||||
v-if="getProductPhoto(item)"
|
||||
:src="getProductPhoto(item)"
|
||||
:alt="item.product?.name || item.sku?.name || '产品图片'"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="avatar fallback"
|
||||
v-text="(item.product?.name || item.sku?.name || '产').slice(0, 1)"
|
||||
/>
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-empty v-if="!skuList.length" description="暂无启用的兑换商品" />
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
import CodeScanner from "@/components/CodeScanner.vue";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import { useSettingStore } from "@/store/settingStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import type { PointAccount, PointRedeemSku } from "@/types/Point";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { normalizePackageQuantity } from "@/utils/package";
|
||||
import { getProductPhotoURL, getProductQuantityStep } from "@/utils/product";
|
||||
import { uploadPhotoList } from "@/utils/photo";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({ name: "PointRedemptionCreate" });
|
||||
|
||||
const router = useRouter();
|
||||
const navBarStore = useNavBarStore();
|
||||
const settingStore = useSettingStore();
|
||||
const userStore = useUserStore();
|
||||
const customerId = ref("");
|
||||
const customer = ref<Customer>();
|
||||
const pointAccount = ref<PointAccount>();
|
||||
const pointAccountLoading = ref(false);
|
||||
const customerVisible = ref(false);
|
||||
const skuVisible = ref(false);
|
||||
const skuList = ref<PointRedeemSku[]>([]);
|
||||
const selectedSku = ref<PointRedeemSku>();
|
||||
const quantity = ref("1");
|
||||
const actualPointText = ref("");
|
||||
const remark = ref("");
|
||||
const photos = ref<PhotoItem[]>([]);
|
||||
const requestNo = ref("");
|
||||
const saving = ref(false);
|
||||
const canReadPointAccount = computed(() => userStore.hasPermissions(permissionCodes.point.accountRead));
|
||||
const canAdjust = computed(() => userStore.hasPermissions(permissionCodes.pointRedemption.pointAdjust));
|
||||
const photoUrls = computed(() => photos.value.map(item => item.url));
|
||||
const customerName = computed(() => customer.value?.name);
|
||||
const skuName = computed(() => selectedSku.value ? `${selectedSku.value.product?.name || selectedSku.value.sku?.name || "未命名产品"} · ${selectedSku.value.unit?.name || ""}` : "");
|
||||
const quantityStep = computed(() => getProductQuantityStep(selectedSku.value?.sku));
|
||||
const quantityIsInteger = computed(() => !selectedSku.value?.sku?.allowDecimalQuantity);
|
||||
const estimatedPointText = computed(() => {
|
||||
const unitPoint = selectedSku.value?.defaultPointCost || 0;
|
||||
const count = Number(quantity.value);
|
||||
return Number.isFinite(count) && 0 < count ? formatPoint(Math.round(unitPoint * count)) : "填写数量后计算";
|
||||
});
|
||||
const pointBalanceText = computed(() => {
|
||||
if (!canReadPointAccount.value) {
|
||||
return "无余额读取权限";
|
||||
}
|
||||
return pointAccountLoading.value ? "正在加载" : `${formatWanInteger(pointAccount.value?.balance ?? 0)} 分`;
|
||||
});
|
||||
const scannerVisible = ref(false);
|
||||
const scanStatus = ref("点击扫码开始识别。");
|
||||
let latestDecodedText = "";
|
||||
|
||||
|
||||
async function loadCustomer(value: string | string[]): Promise<void> {
|
||||
const id = Array.isArray(value) ? value[0] : value;
|
||||
if (!id) {
|
||||
customer.value = undefined;
|
||||
pointAccount.value = undefined;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
customer.value = await CustomerAPI.detail(id);
|
||||
if (canReadPointAccount.value) {
|
||||
await loadPointAccount(id, customer.value.storeId);
|
||||
}
|
||||
} catch {
|
||||
customer.value = undefined;
|
||||
pointAccount.value = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPointAccount(customerIdValue: string, storeId?: string): Promise<void> {
|
||||
pointAccountLoading.value = true;
|
||||
try {
|
||||
pointAccount.value = await PointAPI.detailByCustomerId(customerIdValue, storeId);
|
||||
} catch {
|
||||
pointAccount.value = undefined;
|
||||
} finally {
|
||||
pointAccountLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleScanner(): void {
|
||||
scannerVisible.value = !scannerVisible.value;
|
||||
if (scannerVisible.value) {
|
||||
latestDecodedText = "";
|
||||
scanStatus.value = "点击扫码开始识别。";
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDecodedText(rawText: string): Promise<void> {
|
||||
const normalizedText = rawText.trim();
|
||||
if (!normalizedText || normalizedText === latestDecodedText) {
|
||||
return;
|
||||
}
|
||||
latestDecodedText = normalizedText;
|
||||
await settingStore.playScanSuccessSound();
|
||||
await applyScanCode(normalizedText);
|
||||
}
|
||||
|
||||
async function applyScanCode(code: string): Promise<void> {
|
||||
scanStatus.value = `已识别 ${code},正在加载客户档案。`;
|
||||
try {
|
||||
const result = await CustomerAPI.findByCode(code);
|
||||
if (!result?.id) {
|
||||
customer.value = undefined;
|
||||
customerId.value = "";
|
||||
scanStatus.value = `客户 ${code} 不存在,请先建档。`;
|
||||
return;
|
||||
}
|
||||
customer.value = result;
|
||||
customerId.value = result.id;
|
||||
if (canReadPointAccount.value) {
|
||||
await loadPointAccount(result.id, result.storeId);
|
||||
}
|
||||
scanStatus.value = `已识别 ${result.code || code},已自动选中 ${result.name || "未命名客户"}。`;
|
||||
scannerVisible.value = false;
|
||||
} catch (error) {
|
||||
scanStatus.value = getErrorMessage(error, "客户查询失败,请重试。");
|
||||
}
|
||||
}
|
||||
|
||||
function handleScanStatusChange(value: string): void {
|
||||
scanStatus.value = value;
|
||||
}
|
||||
|
||||
async function loadSkuList(): Promise<void> {
|
||||
const page = await PointAPI.redeemSkuList({ index: 0, size: 1000, status: "ACTIVE" });
|
||||
skuList.value = page.list || [];
|
||||
}
|
||||
|
||||
function selectSku(item: PointRedeemSku): void {
|
||||
selectedSku.value = item;
|
||||
skuVisible.value = false;
|
||||
}
|
||||
|
||||
function getProductPhoto(item: PointRedeemSku): string {
|
||||
const product = item.product || item.sku;
|
||||
return product ? getProductPhotoURL(product) : "";
|
||||
}
|
||||
|
||||
function closeSkuPicker(): void {
|
||||
skuVisible.value = false;
|
||||
}
|
||||
|
||||
function attachments(): Array<{ tempFileId: string; attachType: "PHOTO"; name?: string }> {
|
||||
return photos.value.flatMap(item => item.tempFileId ? [{
|
||||
tempFileId: item.tempFileId,
|
||||
attachType: "PHOTO" as const
|
||||
}] : []);
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
const normalized = normalizePackageQuantity(quantity.value);
|
||||
const actual = actualPointText.value ? Number(actualPointText.value) : undefined;
|
||||
if (
|
||||
saving.value
|
||||
|| !customerId.value
|
||||
|| !selectedSku.value?.id
|
||||
|| !normalized
|
||||
|| !attachments().length
|
||||
|| (actual !== undefined && (!canAdjust.value || !Number.isSafeInteger(actual) || actual < 0))
|
||||
) {
|
||||
Message.warning("请填写客户、商品、正数数量并上传兑换照片");
|
||||
return;
|
||||
}
|
||||
if (!requestNo.value) {
|
||||
requestNo.value = window.crypto.randomUUID();
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const result = await PointAPI.redemptionCreate({
|
||||
requestNo: requestNo.value,
|
||||
customerId: customerId.value,
|
||||
redeemSkuId: selectedSku.value.id,
|
||||
quantity: normalized,
|
||||
actualPointCost: actual,
|
||||
attachmentList: attachments(),
|
||||
remark: remark.value || null
|
||||
});
|
||||
Message.success("兑换已完成");
|
||||
await router.replace({ name: "PointRedemptionDetail", params: { id: result.id } });
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "兑换失败,重试将复用同一请求号"));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function formatPoint(value?: number): string {
|
||||
return `${formatWanInteger(value ?? 0)} 分`;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.setRightText("兑换", "var(--td-brand-color)", save);
|
||||
try {
|
||||
await loadSkuList();
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "兑换商品加载失败"));
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => navBarStore.clearRight());
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.redemption-create {
|
||||
padding: calc(var(--app-nav-height) + 1rem) 0 2rem;
|
||||
|
||||
.form {
|
||||
margin: 0 1rem;
|
||||
padding: .5rem 0;
|
||||
background: rgba(255, 255, 255, .92);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
border-radius: 1.4rem;
|
||||
|
||||
.customer {
|
||||
.actions {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
.code-scanner-wrapper,
|
||||
.photo-wrap {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.customer-profile {
|
||||
margin: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sku-picker {
|
||||
max-height: 70vh;
|
||||
overflow: auto;
|
||||
padding: 1rem 0;
|
||||
|
||||
.item {
|
||||
padding: .625rem 1rem;
|
||||
border-radius: 1rem;
|
||||
|
||||
:deep(.t-cell__title) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: .5rem !important;
|
||||
}
|
||||
|
||||
.fallback {
|
||||
color: var(--td-brand-color);
|
||||
display: flex;
|
||||
font-size: 1rem;
|
||||
background: var(--td-brand-color-1);
|
||||
font-weight: 600;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.redemption-create {
|
||||
.form {
|
||||
background: rgba(15, 23, 42, .88);
|
||||
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,246 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.pointRedemption.create" class="redemption-detail">
|
||||
<customer-profile-card
|
||||
v-if="customer"
|
||||
class="customer-profile"
|
||||
:customer="customer"
|
||||
v-entrance-transition
|
||||
/>
|
||||
<t-cell-group v-if="item" title="兑换信息" theme="card" v-entrance-transition="70">
|
||||
<t-cell title="客户" :note="item.customer?.name || item.customerId || '-'" />
|
||||
<t-cell title="兑换商品" :note="item.productNameSnapshot || item.skuNameSnapshot || '-'" />
|
||||
<t-cell title="兑换数量" :note="`${quantityText(item.quantity)} ${item.unitSnapshot || ''}`" />
|
||||
<t-cell title="积分" :note="`${formatPoint(item.actualPointCost)}${item.actualPointCost !== item.defaultPointCost ? '(已减免)' : ''}`" />
|
||||
<t-cell title="状态" :note="statusText(item.status)" />
|
||||
<t-cell title="兑换时间" :note="timeText(item.redeemedAt)" />
|
||||
<t-cell v-if="item.remark" title="备注" :note="item.remark" />
|
||||
<div class="photo-wrap bg-white">
|
||||
<media-selector
|
||||
:model-value="attachmentUrls"
|
||||
:show-add="false"
|
||||
:show-remove="false"
|
||||
:show-viewer-actions="false"
|
||||
title="兑换凭证照片"
|
||||
/>
|
||||
</div>
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="returnList.length" title="退货记录" theme="card" v-entrance-transition="140">
|
||||
<t-cell
|
||||
v-for="record in returnList"
|
||||
:key="record.id"
|
||||
:title="`退货 ${quantityText(record.quantity)} ${item?.unitSnapshot || ''}`"
|
||||
:note="`${formatPoint(record.pointCost)} · ${timeText(record.returnedAt)}`"
|
||||
/>
|
||||
</t-cell-group>
|
||||
<t-empty v-if="!item" :description="loading ? '正在加载兑换单' : '兑换单不存在'" />
|
||||
<t-button
|
||||
v-if="canReturn"
|
||||
class="return-button cell-button"
|
||||
theme="danger"
|
||||
content="冲正兑换"
|
||||
v-entrance-transition="140"
|
||||
@click="returnVisible = true"
|
||||
/>
|
||||
</div>
|
||||
<bottom-popup
|
||||
v-model="returnVisible"
|
||||
title="冲正兑换"
|
||||
left-button-text="取消"
|
||||
:right-button-text="returning ? '提交中' : '确认冲正'"
|
||||
@left-button-click="returnVisible = false"
|
||||
@right-button-click="submitReturn"
|
||||
>
|
||||
<div class="return-form">
|
||||
<t-form class="form" label-width="6rem">
|
||||
<t-form-item label="剩余数量">
|
||||
<span v-text="`${remainText} ${item?.unitSnapshot || ''}`" />
|
||||
</t-form-item>
|
||||
<t-form-item label="冲正数量" required-mark>
|
||||
<t-input v-model.trim="returnQuantity" type="number" align="right" borderless />
|
||||
</t-form-item>
|
||||
<t-form-item label="冲正原因">
|
||||
<t-textarea v-model.trim="returnRemark" maxlength="500" autosize />
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<media-selector
|
||||
v-model="returnPhotoUrls"
|
||||
v-model:photo-items="returnPhotos"
|
||||
:upload="uploadPhotoList"
|
||||
edit-mode
|
||||
required
|
||||
title="冲正凭证照片"
|
||||
/>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { AttachmentAPI, useUserStore } from "timi-web-api";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import type { PointRedemption, PointRedemptionReturn, PointRedemptionStatus } from "@/types/Point";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { comparePackageQuantity, getPackageQuantityText, normalizePackageQuantity } from "@/utils/package";
|
||||
import { uploadPhotoList } from "@/utils/photo";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({ name: "PointRedemptionDetail" });
|
||||
|
||||
const route = useRoute();
|
||||
const userStore = useUserStore();
|
||||
const item = ref<PointRedemption>();
|
||||
const customer = ref<Customer>();
|
||||
const returnList = ref<PointRedemptionReturn[]>([]);
|
||||
const loading = ref(false);
|
||||
const returnVisible = ref(false);
|
||||
const returnQuantity = ref("");
|
||||
const returnRemark = ref("");
|
||||
const returnPhotos = ref<PhotoItem[]>([]);
|
||||
const returnRequestNo = ref("");
|
||||
const returning = ref(false);
|
||||
const attachmentUrls = computed(() => (item.value?.attachmentList || [])
|
||||
.filter(attachment => !!attachment.id)
|
||||
.map(attachment => AttachmentAPI.getReadURL(attachment.id!)));
|
||||
const returnPhotoUrls = computed(() => returnPhotos.value.map(photo => photo.url));
|
||||
const canReturn = computed(() => userStore.hasPermissions(permissionCodes.pointRedemption.return)
|
||||
&& (item.value?.status === "COMPLETED" || item.value?.status === "PARTIALLY_RETURNED")
|
||||
&& 0 < comparePackageQuantity(remaining(), "0"));
|
||||
const remainText = computed(() => quantityText(remaining()));
|
||||
|
||||
function remaining(): string {
|
||||
const total = Number(item.value?.quantity || 0);
|
||||
const returned = Number(item.value?.returnedQuantity || 0);
|
||||
return String(Math.max(0, total - returned));
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const id = String(route.params.id || "");
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
item.value = await PointAPI.redemptionDetail(id);
|
||||
customer.value = item.value.customer;
|
||||
if (!customer.value && item.value.customerId) {
|
||||
try {
|
||||
customer.value = await CustomerAPI.detail(item.value.customerId);
|
||||
} catch {
|
||||
customer.value = undefined;
|
||||
}
|
||||
}
|
||||
returnList.value = await PointAPI.redemptionReturnList(id);
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "兑换单加载失败"));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function attachments(): Array<{ tempFileId: string; attachType: "PHOTO"; name?: string }> {
|
||||
return returnPhotos.value.flatMap(photo => photo.tempFileId ? [{
|
||||
tempFileId: photo.tempFileId,
|
||||
attachType: "PHOTO" as const
|
||||
}] : []);
|
||||
}
|
||||
|
||||
async function submitReturn(): Promise<void> {
|
||||
const quantity = normalizePackageQuantity(returnQuantity.value);
|
||||
const redemptionId = item.value?.id;
|
||||
if (
|
||||
returning.value
|
||||
|| !redemptionId
|
||||
|| !quantity
|
||||
|| 0 < comparePackageQuantity(quantity, remaining())
|
||||
|| !attachments().length
|
||||
) {
|
||||
Message.warning("请填写不超过剩余数量的退货数量并上传照片");
|
||||
return;
|
||||
}
|
||||
if (!returnRequestNo.value) {
|
||||
returnRequestNo.value = window.crypto.randomUUID();
|
||||
}
|
||||
returning.value = true;
|
||||
try {
|
||||
item.value = await PointAPI.redemptionReturn({
|
||||
redemptionId,
|
||||
requestNo: returnRequestNo.value,
|
||||
quantity,
|
||||
attachmentList: attachments(),
|
||||
remark: returnRemark.value || null
|
||||
});
|
||||
customer.value = item.value.customer || customer.value;
|
||||
returnList.value = await PointAPI.redemptionReturnList(redemptionId);
|
||||
returnVisible.value = false;
|
||||
returnQuantity.value = "";
|
||||
returnRemark.value = "";
|
||||
returnPhotos.value = [];
|
||||
returnRequestNo.value = "";
|
||||
Message.success("退货已完成");
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "退货失败,重试将复用同一请求号"));
|
||||
} finally {
|
||||
returning.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function formatPoint(value?: number): string {
|
||||
return `${formatWanInteger(value ?? 0)} 分`;
|
||||
}
|
||||
|
||||
function quantityText(value?: number | string): string {
|
||||
return getPackageQuantityText(value);
|
||||
}
|
||||
|
||||
function statusText(value?: PointRedemptionStatus): string {
|
||||
return ({
|
||||
COMPLETED: "已兑换",
|
||||
PARTIALLY_RETURNED: "部分退货",
|
||||
FULLY_RETURNED: "已退完"
|
||||
} as Record<string, string>)[value || ""] || "未知";
|
||||
}
|
||||
|
||||
function timeText(value?: number): string {
|
||||
return value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "-";
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.redemption-detail {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding: calc(var(--app-nav-height) + 1rem) 0 2rem;
|
||||
flex-direction: column;
|
||||
|
||||
.return-button {
|
||||
margin: 0 1rem;
|
||||
}
|
||||
|
||||
.customer-profile {
|
||||
margin: 0 1rem;
|
||||
}
|
||||
|
||||
.photo-wrap {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.return-form {
|
||||
padding-bottom: 1rem;
|
||||
|
||||
.form {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,505 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.pointRedemption.create" class="redemption-list">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model.trim="keyword"
|
||||
class="keyword"
|
||||
clearable
|
||||
borderless
|
||||
placeholder="搜索客户、产品或 SKU"
|
||||
>
|
||||
<template #suffix-icon>
|
||||
<div class="actions">
|
||||
<t-button
|
||||
v-if="customerId"
|
||||
shape="circle"
|
||||
theme="danger"
|
||||
variant="text"
|
||||
size="extra-small"
|
||||
aria-label="清除客户选择"
|
||||
@click.stop="clearCustomer"
|
||||
>
|
||||
<t-icon name="close" size="1rem" />
|
||||
</t-button>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
content="选择客户"
|
||||
@click.stop="customerSelectorVisible = true"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</t-input>
|
||||
<t-dropdown-menu class="menus">
|
||||
<t-dropdown-item
|
||||
v-model="dateFilterType"
|
||||
:label="dateFilterLabel"
|
||||
:options="dateOptions"
|
||||
@change="selectDateFilter"
|
||||
/>
|
||||
</t-dropdown-menu>
|
||||
</div>
|
||||
<t-pull-down-refresh
|
||||
v-model="refreshing"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="reload"
|
||||
@scrolltolower="load"
|
||||
>
|
||||
<div class="list-wrap">
|
||||
<t-cell-group class="date-summary" theme="card" v-entrance-transition>
|
||||
<template v-if="isCustomDate">
|
||||
<t-cell
|
||||
title="开始时间"
|
||||
:note="dateRange[0] || '-'"
|
||||
arrow
|
||||
@click="openStartTime"
|
||||
/>
|
||||
<t-cell
|
||||
title="结束时间"
|
||||
:note="dateRange[1] || '-'"
|
||||
arrow
|
||||
@click="openEndTime"
|
||||
/>
|
||||
</template>
|
||||
<t-cell title="总数据量" :note="Text.display(result.total)" />
|
||||
</t-cell-group>
|
||||
<div v-if="result.list.length" class="items">
|
||||
<t-cell-group theme="card">
|
||||
<t-cell
|
||||
v-for="(item, index) in result.list"
|
||||
:key="item.id"
|
||||
class="item"
|
||||
arrow
|
||||
v-entrance-transition="70 + index * 30"
|
||||
@click="toDetail(item)"
|
||||
>
|
||||
<template #left-icon>
|
||||
<t-image
|
||||
v-if="getCustomerPhoto(item)"
|
||||
:src="getCustomerPhoto(item)"
|
||||
:alt="item.customer?.name || '客户照片'"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="avatar fallback"
|
||||
v-text="(item.customer?.name || item.customer?.code || '客').slice(0, 1)"
|
||||
/>
|
||||
</template>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<strong v-text="item.productNameSnapshot || item.skuNameSnapshot || '未命名产品'" />
|
||||
<t-tag
|
||||
size="small"
|
||||
:theme="item.status === 'FULLY_RETURNED' ? 'default' : 'success'"
|
||||
:content="statusText(item.status)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template #note>
|
||||
<span class="orange" v-text="formatPoint(item.actualPointCost)" />
|
||||
</template>
|
||||
<template #description>
|
||||
<span v-text="`${item.customer?.name || item.customerId || '未知客户'} · ${quantityText(item.quantity)} ${item.unitSnapshot || ''}`" />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
</div>
|
||||
<t-empty
|
||||
v-else
|
||||
:description="loading ? '正在加载兑换记录' : hasFilter ? '未找到匹配的兑换记录' : '暂无兑换记录'"
|
||||
/>
|
||||
</div>
|
||||
</t-pull-down-refresh>
|
||||
</div>
|
||||
<customer-selector
|
||||
v-model="customerId"
|
||||
v-model:visible="customerSelectorVisible"
|
||||
@change="handleCustomerChange"
|
||||
/>
|
||||
<nav-bar-action-menu
|
||||
v-can="permissionCodes.pointRedemption.create"
|
||||
:actions="[{ key: 'create', icon: 'add', text: '客户兑换', theme: 'primary', action: toCreate }]"
|
||||
/>
|
||||
<t-popup v-model="startVisible" placement="bottom">
|
||||
<t-date-time-picker
|
||||
v-if="startVisible"
|
||||
v-model="startDraft"
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
:mode="['date', 'minute']"
|
||||
title="开始时间"
|
||||
:default-value="dateRange[0]"
|
||||
@cancel="cancelStartTime"
|
||||
@confirm="confirmStartTime"
|
||||
/>
|
||||
</t-popup>
|
||||
<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="结束时间"
|
||||
:default-value="dateRange[1]"
|
||||
@cancel="cancelEndTime"
|
||||
@confirm="confirmEndTime"
|
||||
/>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { type DropdownValue } from "tdesign-mobile-vue";
|
||||
import { Text, Time, Toolkit } from "timi-web";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PointRedemption, PointRedemptionStatus } from "@/types/Point";
|
||||
import { buildPresetDateRange, parseDateFilterType, parseDateTime } from "@/utils/date";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { getPackageQuantityText } from "@/utils/package";
|
||||
import { getCustomerPhotoURL } from "@/utils/customer";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({ name: "PointRedemptionList" });
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const navBarStore = useNavBarStore();
|
||||
const result = reactive({ total: 0, list: [] as PointRedemption[] });
|
||||
type DateFilterType = "today" | "yesterday" | "thisWeek" | "thisMonth" | "lastMonth" | "all" | "custom";
|
||||
const dateOptions: Array<{ label: string; value: DateFilterType }> = [
|
||||
{ label: "今天", value: "today" },
|
||||
{ label: "昨天", value: "yesterday" },
|
||||
{ label: "本周", value: "thisWeek" },
|
||||
{ label: "本月", value: "thisMonth" },
|
||||
{ label: "上个月", value: "lastMonth" },
|
||||
{ label: "全部", value: "all" },
|
||||
{ label: "自定义范围", value: "custom" }
|
||||
];
|
||||
const keyword = ref(getQueryText(route.query.keyword));
|
||||
const customerId = ref(getQueryText(route.query.customerId));
|
||||
const selectedCustomer = ref<Customer>();
|
||||
const customerSelectorVisible = ref(false);
|
||||
const dateFilterType = ref<DateFilterType>(parseDateFilterType(getQueryText(route.query.dateType), dateOptions, "today"));
|
||||
const dateRange = ref<[string, string]>(parseDateRange(dateFilterType.value));
|
||||
const startDraft = ref("");
|
||||
const endDraft = ref("");
|
||||
const startVisible = ref(false);
|
||||
const endVisible = ref(false);
|
||||
const index = ref(0);
|
||||
const loading = ref(false);
|
||||
const refreshing = ref(false);
|
||||
const noMore = ref(false);
|
||||
let reloadRequested = false;
|
||||
const dateFilterLabel = computed(() => dateOptions.find(item => item.value === dateFilterType.value)?.label || "时间范围");
|
||||
const isCustomDate = computed(() => dateFilterType.value === "custom");
|
||||
const hasFilter = computed(() => Boolean(keyword.value.trim() || customerId.value || dateFilterType.value !== "all"));
|
||||
|
||||
function getQueryText(value: unknown): string {
|
||||
return Array.isArray(value) ? "" : typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function parseDateRange(type: DateFilterType): [string, string] {
|
||||
if (type !== "custom") {
|
||||
return buildPresetDateRange(type);
|
||||
}
|
||||
return [getQueryText(route.query.beginAt), getQueryText(route.query.endAt)];
|
||||
}
|
||||
|
||||
async function reload(): Promise<void> {
|
||||
if (loading.value) {
|
||||
reloadRequested = true;
|
||||
return;
|
||||
}
|
||||
index.value = 0;
|
||||
result.total = 0;
|
||||
result.list = [];
|
||||
noMore.value = false;
|
||||
try {
|
||||
await load();
|
||||
} finally {
|
||||
refreshing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
if (loading.value || noMore.value) {
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const [beginAt, endAt] = buildUnixRange();
|
||||
const page = await PointAPI.redemptionList({
|
||||
index: index.value,
|
||||
size: 20,
|
||||
customerId: customerId.value || undefined,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
beginAt,
|
||||
endAt
|
||||
});
|
||||
const list = page.list || [];
|
||||
result.list = result.list.concat(list);
|
||||
result.total = page.total || 0;
|
||||
index.value++;
|
||||
noMore.value = result.total <= result.list.length || list.length < 20;
|
||||
} catch {
|
||||
Message.error("兑换记录加载失败");
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (reloadRequested) {
|
||||
reloadRequested = false;
|
||||
await reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatPoint(value?: number): string {
|
||||
return `${formatWanInteger(value ?? 0)} 分`;
|
||||
}
|
||||
|
||||
function quantityText(value?: number | string): string {
|
||||
return getPackageQuantityText(value);
|
||||
}
|
||||
|
||||
function getCustomerPhoto(item: PointRedemption): string {
|
||||
return getCustomerPhotoURL(item.customer, 64);
|
||||
}
|
||||
|
||||
async function handleCustomerChange(value: string | string[]): Promise<void> {
|
||||
customerId.value = Array.isArray(value) ? String(value[0] || "") : value;
|
||||
try {
|
||||
selectedCustomer.value = customerId.value ? await CustomerAPI.detail(customerId.value) : undefined;
|
||||
await reload();
|
||||
} catch {
|
||||
selectedCustomer.value = undefined;
|
||||
Message.error("客户信息加载失败");
|
||||
}
|
||||
}
|
||||
|
||||
async function clearCustomer(): Promise<void> {
|
||||
customerId.value = "";
|
||||
selectedCustomer.value = undefined;
|
||||
await reload();
|
||||
}
|
||||
|
||||
async function selectDateFilter(value: DropdownValue): Promise<void> {
|
||||
if (Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
dateFilterType.value = String(value) as DateFilterType;
|
||||
if (dateFilterType.value !== "custom") {
|
||||
dateRange.value = buildPresetDateRange(dateFilterType.value);
|
||||
await replaceFilterQuery();
|
||||
await reload();
|
||||
} else {
|
||||
await replaceFilterQuery();
|
||||
}
|
||||
}
|
||||
|
||||
function openStartTime(): void {
|
||||
startDraft.value = dateRange.value[0];
|
||||
startVisible.value = true;
|
||||
}
|
||||
|
||||
function openEndTime(): void {
|
||||
endDraft.value = dateRange.value[1];
|
||||
endVisible.value = true;
|
||||
}
|
||||
|
||||
function cancelStartTime(): void {
|
||||
startVisible.value = false;
|
||||
startDraft.value = dateRange.value[0];
|
||||
}
|
||||
|
||||
function cancelEndTime(): void {
|
||||
endVisible.value = false;
|
||||
endDraft.value = dateRange.value[1];
|
||||
}
|
||||
|
||||
async function confirmStartTime(value?: string | number): Promise<void> {
|
||||
startVisible.value = false;
|
||||
dateRange.value = [String(value || startDraft.value), dateRange.value[1]];
|
||||
await confirmCustomRange();
|
||||
}
|
||||
|
||||
async function confirmEndTime(value?: string | number): Promise<void> {
|
||||
endVisible.value = false;
|
||||
dateRange.value = [dateRange.value[0], String(value || endDraft.value)];
|
||||
await confirmCustomRange();
|
||||
}
|
||||
|
||||
async function confirmCustomRange(): Promise<void> {
|
||||
if (dateRange.value[0] && dateRange.value[1] && dateRange.value[1] < dateRange.value[0]) {
|
||||
dateRange.value = [dateRange.value[1], dateRange.value[0]];
|
||||
}
|
||||
dateFilterType.value = "custom";
|
||||
await replaceFilterQuery();
|
||||
await reload();
|
||||
}
|
||||
|
||||
async function replaceFilterQuery(): Promise<void> {
|
||||
await router.replace({
|
||||
name: "PointRedemptionList",
|
||||
query: {
|
||||
customerId: customerId.value || undefined,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
dateType: dateFilterType.value,
|
||||
beginAt: dateRange.value[0] || undefined,
|
||||
endAt: dateRange.value[1] || undefined
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildUnixRange(): [number | undefined, number | undefined] {
|
||||
if (dateFilterType.value === "all") {
|
||||
return [0, Time.toTimestamp(new Date())];
|
||||
}
|
||||
return [
|
||||
Time.toTimestamp(parseDateTime(dateRange.value[0], false)),
|
||||
Time.toTimestamp(parseDateTime(dateRange.value[1], true))
|
||||
];
|
||||
}
|
||||
|
||||
function statusText(value?: PointRedemptionStatus): string {
|
||||
return ({
|
||||
COMPLETED: "已兑换",
|
||||
PARTIALLY_RETURNED: "部分退货",
|
||||
FULLY_RETURNED: "已退完"
|
||||
} as Record<string, string>)[value || ""] || "未知";
|
||||
}
|
||||
|
||||
async function toCreate(): Promise<void> {
|
||||
await router.push({ name: "PointRedemptionCreate" });
|
||||
}
|
||||
|
||||
async function toDetail(item: PointRedemption): Promise<void> {
|
||||
if (item.id) {
|
||||
await router.push({ name: "PointRedemptionDetail", params: { id: item.id } });
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.setCustomRightVisible(true);
|
||||
try {
|
||||
if (customerId.value) {
|
||||
selectedCustomer.value = await CustomerAPI.detail(customerId.value);
|
||||
}
|
||||
await reload();
|
||||
} catch {
|
||||
Message.error("兑换记录加载失败");
|
||||
}
|
||||
});
|
||||
|
||||
const reloadByKeyword = Toolkit.debounce(async () => {
|
||||
await reload();
|
||||
}, false);
|
||||
|
||||
watch(keyword, () => {
|
||||
reloadByKeyword();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
reloadByKeyword.cancel();
|
||||
navBarStore.clearRight();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.redemption-list {
|
||||
padding: var(--app-nav-height) 0 1rem;
|
||||
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
flex-direction: column;
|
||||
|
||||
.keyword {
|
||||
--td-input-vertical-padding: .25rem 1rem;
|
||||
|
||||
flex: 1;
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 2;
|
||||
padding-right: .3rem;
|
||||
border-radius: 1rem;
|
||||
|
||||
.actions {
|
||||
--td-button-border-radius: .75rem;
|
||||
|
||||
gap: .25rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.menus {
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid var(--td-component-border);
|
||||
overflow: hidden;
|
||||
margin-top: -1rem;
|
||||
border-top: none;
|
||||
padding-top: .8rem;
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.list-wrap {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
min-height: 70vh;
|
||||
flex-direction: column;
|
||||
|
||||
.items {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
border-radius: 1rem;
|
||||
|
||||
.title {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
border-radius: .875rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:global(html.theme-dark) {
|
||||
.redemption-list {
|
||||
.filters {
|
||||
background: #10161f;
|
||||
|
||||
.menus {
|
||||
background: #1d2733;
|
||||
}
|
||||
}
|
||||
|
||||
.fallback {
|
||||
color: #ccfbf1;
|
||||
background: #115e59;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -101,6 +101,7 @@ import type { EventItem } from "@/types/EventItem";
|
||||
import type { PointRule, PointRuleStatus } from "@/types/Point";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { Message } from "@/utils/message";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({
|
||||
@@ -217,7 +218,7 @@ function formatPointValue(value?: number | null): string {
|
||||
if (value === 0) {
|
||||
return "不产生积分流水";
|
||||
}
|
||||
return `${0 < value ? "发放" : "消耗"} ${Math.abs(value)} 分`;
|
||||
return `${0 < value ? "发放" : "消耗"} ${formatWanInteger(Math.abs(value))} 分`;
|
||||
}
|
||||
|
||||
function formatNumber(value?: number): string {
|
||||
|
||||
@@ -70,6 +70,7 @@ import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { EventItem } from "@/types/EventItem";
|
||||
import type { NavBarAction } from "@/types/NavBarAction";
|
||||
import type { PointRule, PointRuleStatus } from "@/types/Point";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
import { type Page, type PageResult, useUserStore } from "timi-web-api";
|
||||
import { Message } from "@/utils/message.ts";
|
||||
@@ -242,7 +243,7 @@ function getPointText(rule: PointRule): string {
|
||||
if (rule.pointValue === undefined || rule.pointValue === null) {
|
||||
return "?";
|
||||
}
|
||||
return `${0 < rule.pointValue ? "+" : "-"}${Math.abs(rule.pointValue)}`;
|
||||
return `${0 < rule.pointValue ? "+" : "-"}${formatWanInteger(Math.abs(rule.pointValue))}`;
|
||||
}
|
||||
|
||||
function getStatusText(status?: PointRuleStatus): string {
|
||||
|
||||
@@ -52,6 +52,7 @@ import PointAPI from "@/api/PointAPI";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { EventItem } from "@/types/EventItem";
|
||||
import type { PointRule } from "@/types/Point";
|
||||
import { formatWanInteger } from "@/utils/money";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({ name: "PointRuleSort" });
|
||||
@@ -72,7 +73,7 @@ function getPointText(rule: PointRule): string {
|
||||
if (rule.pointValue === undefined || rule.pointValue === null) {
|
||||
return "未配置";
|
||||
}
|
||||
return (0 < rule.pointValue ? "+" : "") + rule.pointValue;
|
||||
return (0 < rule.pointValue ? "+" : "") + formatWanInteger(rule.pointValue);
|
||||
}
|
||||
|
||||
async function loadData(): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.productCategory.read" class="product-category-list">
|
||||
<div class="filters bg-white">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="keyword"
|
||||
class="keyword"
|
||||
@@ -368,19 +368,19 @@ onUnmounted(() => {
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: var(--td-bg-color-page);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
|
||||
.keyword {
|
||||
--td-input-vertical-padding: 8px 14px;
|
||||
|
||||
flex: 1;
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 1;
|
||||
padding: .5rem 1rem;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
margin-left: -2rem;
|
||||
padding-left: 1.5rem;
|
||||
border-radius: 1rem;
|
||||
@@ -392,7 +392,6 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.list {
|
||||
padding-top: .75rem;
|
||||
|
||||
.item {
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<t-cell title="状态" :note="getProductStatusText(product.status)" />
|
||||
<t-cell title="备注" :note="Text.display(product.remark)"></t-cell>
|
||||
<t-cell>
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
:model-value="attachmentUrlList"
|
||||
:photo-items="attachmentItemList"
|
||||
title="附件列表"
|
||||
@@ -28,8 +28,9 @@
|
||||
@click="viewStock"
|
||||
/>
|
||||
</t-cell-group>
|
||||
<t-cell-group title="SKU 列表" theme="card" class="units" v-entrance-transition="210">
|
||||
<t-cell-group title="SKU 列表" theme="card" class="skus" v-entrance-transition="210">
|
||||
<t-cell
|
||||
class="sku"
|
||||
v-for="sku in product.skuList || []"
|
||||
:key="sku.id || sku.code"
|
||||
role="button"
|
||||
@@ -38,14 +39,18 @@
|
||||
hover
|
||||
@click="openSkuDetail(sku)"
|
||||
>
|
||||
<template #leftIcon>
|
||||
<t-image
|
||||
v-if="getProductPhotoURL(sku)"
|
||||
:src="getProductPhotoURL(sku)"
|
||||
:alt="getSkuTitle(sku)"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
/>
|
||||
<div v-else class="avatar fallback" v-text="getSkuTitle(sku).slice(0, 1)" />
|
||||
</template>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<t-tag
|
||||
class="code"
|
||||
size="small"
|
||||
variant="light"
|
||||
:content="sku.code || '无编码'"
|
||||
/>
|
||||
<h5 class="name" v-text="getSkuTitle(sku)" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -78,38 +83,15 @@
|
||||
<bottom-popup
|
||||
v-model="skuDetailVisible"
|
||||
title="SKU 详情"
|
||||
height="min(88vh, 48rem)"
|
||||
height="min(80vh, 48rem)"
|
||||
left-button-text="关闭"
|
||||
right-button-text=""
|
||||
:z-index="skuDetailPopupZIndex"
|
||||
:overlay-props="{ zIndex: skuDetailPopupZIndex - 1 }"
|
||||
@left-button-click="closeSkuDetail"
|
||||
>
|
||||
<div v-if="selectedSku" class="sku-popup">
|
||||
<div class="sku-popup-header">
|
||||
<div class="sku-heading">
|
||||
<strong v-text="getSkuTitle(selectedSku)" />
|
||||
<span class="code" v-text="selectedSku.code || '无 SKU 编码'" />
|
||||
</div>
|
||||
<t-tag
|
||||
size="small"
|
||||
variant="light-outline"
|
||||
:theme="selectedSku.status === 'ACTIVE' ? 'success' : 'warning'"
|
||||
:content="selectedSku.status === 'ACTIVE' ? '启用' : '停用'"
|
||||
/>
|
||||
</div>
|
||||
<div class="sku-spec-panel">
|
||||
<div class="section-title">
|
||||
<strong>销售规格</strong>
|
||||
<span v-if="selectedSku.specSummary" v-text="`摘要:${selectedSku.specSummary}`" />
|
||||
</div>
|
||||
<div v-if="skuSpecEntries.length" class="sku-spec-list">
|
||||
<div v-for="entry in skuSpecEntries" :key="`${entry.specName}-${entry.valueName}`" class="sku-spec-item">
|
||||
<span class="spec-name" v-text="entry.specName" />
|
||||
<strong v-text="entry.valueName" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="sku-spec-empty" v-text="product?.specList?.length ? '暂无匹配的规格值' : '无多规格产品,使用默认 SKU'" />
|
||||
</div>
|
||||
<t-cell-group title="基本信息" theme="card">
|
||||
<t-cell-group>
|
||||
<t-cell title="明细名称" :note="selectedSku.name || '未命名 SKU'" />
|
||||
<t-cell title="SKU 编码" :note="selectedSku.code || '无编码'" />
|
||||
<t-cell v-if="selectedSku.barcode" title="SKU 条码" :note="selectedSku.barcode" />
|
||||
@@ -118,7 +100,8 @@
|
||||
<t-cell v-if="selectedSku.stockEnabled" title="最低库存" :note="`${getProductQuantityText(selectedSku.minStockQuantity)} 基础单位`" />
|
||||
<t-cell v-if="selectedSku.remark" title="备注" :note="Text.display(selectedSku.remark)" />
|
||||
</t-cell-group>
|
||||
<photo-scroller
|
||||
<div class="media-wrap">
|
||||
<media-selector
|
||||
v-if="skuPhotoItemList.length"
|
||||
:model-value="skuPhotoUrlList"
|
||||
:photo-items="skuPhotoItemList"
|
||||
@@ -127,22 +110,14 @@
|
||||
:show-remove="false"
|
||||
:show-viewer-actions="false"
|
||||
/>
|
||||
|
||||
<div class="unit-section">
|
||||
<div class="unit-heading">
|
||||
</div>
|
||||
<div class="unit">
|
||||
<div class="header">
|
||||
<strong>销售单位</strong>
|
||||
<span>采购、销售和库存操作共用</span>
|
||||
</div>
|
||||
<div v-if="selectedSku.unitList?.length" class="unit-list">
|
||||
<div v-for="unit in selectedSku.unitList" :key="unit.id || unit.name" class="unit-item">
|
||||
<div class="unit-name">
|
||||
<strong v-text="unit.name || '未命名单位'" />
|
||||
<t-tag v-if="unit.isBase" size="small" theme="primary" variant="light-outline" content="基础" />
|
||||
</div>
|
||||
<div class="unit-meta" v-text="getUnitSummary(unit)" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="unit-empty" v-text="'暂无销售单位'" />
|
||||
<product-sku-unit-list v-if="selectedSku.unitList?.length" :unit-list="selectedSku.unitList" />
|
||||
<div v-else class="center-tips" v-text="'暂无销售单位'" />
|
||||
</div>
|
||||
</div>
|
||||
</bottom-popup>
|
||||
@@ -154,15 +129,21 @@ import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import NavBarActionMenu from "@/components/NavBarActionMenu.vue";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import ProductProfile from "@/pages/product/component/ProductProfile.vue";
|
||||
import ProductSkuUnitList from "@/pages/product/component/ProductSkuUnitList.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { NavBarAction } from "@/types/NavBarAction";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import type { Product, ProductSku, ProductSkuUnit } from "@/types/Product";
|
||||
import type { Product, ProductSku } from "@/types/Product";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { formatProductAmount, getProductQuantityText, getProductSkuSpecEntries, getProductStatusText } from "@/utils/product";
|
||||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||||
import {
|
||||
getProductPhotoURL,
|
||||
getProductQuantityText,
|
||||
getProductStatusText
|
||||
} from "@/utils/product";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { Text } from "timi-web";
|
||||
@@ -177,6 +158,7 @@ const product = ref<Product>();
|
||||
const isLoading = ref(false);
|
||||
const selectedSku = ref<ProductSku>();
|
||||
const skuDetailVisible = ref(false);
|
||||
const skuDetailPopupZIndex = 1000;
|
||||
const attachmentItemList = computed<PhotoItem[]>(() => (product.value?.attachmentList || [])
|
||||
.filter(item => !!item.id)
|
||||
.map(item => ({
|
||||
@@ -186,7 +168,6 @@ const attachmentItemList = computed<PhotoItem[]>(() => (product.value?.attachmen
|
||||
url: getAttachmentReadURL(item.id || "", 90)
|
||||
})));
|
||||
const attachmentUrlList = computed(() => attachmentItemList.value.map(item => item.url));
|
||||
const skuSpecEntries = computed(() => getProductSkuSpecEntries(selectedSku.value || { specValueIdList: [] }, product.value?.specList || []));
|
||||
const skuPhotoItemList = computed<PhotoItem[]>(() => (selectedSku.value?.attachmentList || [])
|
||||
.filter(item => !!item.id)
|
||||
.map(item => ({
|
||||
@@ -203,6 +184,7 @@ const actionList = computed<NavBarAction[]>(() => {
|
||||
if (product.value?.status === "ACTIVE") {
|
||||
list.push({ key: "disable", text: "停用产品", icon: "close", theme: "danger", action: disable });
|
||||
}
|
||||
list.push({ key: "remove", text: "移除产品", icon: "delete", theme: "danger", action: remove });
|
||||
}
|
||||
return list;
|
||||
});
|
||||
@@ -253,14 +235,6 @@ function closeSkuDetail(): void {
|
||||
skuDetailVisible.value = false;
|
||||
}
|
||||
|
||||
function getUnitSummary(unit: ProductSkuUnit): string {
|
||||
const quantityText = unit.isBase ? "基础单位" : `1 ${unit.name || "单位"} = ${getProductQuantityText(unit.baseQuantityPerUnit)} 基础单位`;
|
||||
const priceText = unit.salePrice === null || unit.salePrice === undefined ? "未定价" : `¥${formatProductAmount(unit.salePrice)}`;
|
||||
const saleText = unit.allowSale ? "可销售" : "停售";
|
||||
const purchaseText = unit.allowPurchase ? "可采购" : "禁采购";
|
||||
return `${quantityText} · ${priceText} · ${saleText} · ${purchaseText}`;
|
||||
}
|
||||
|
||||
function getCurrentRouteDepth(): number {
|
||||
const transitionDepth = Array.isArray(route.query.transitionDepth)
|
||||
? route.query.transitionDepth[0]
|
||||
@@ -285,6 +259,8 @@ function disable(): void {
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await ProductAPI.disable(id);
|
||||
emitListDataChanged(listDataEventKeys.productChanged, id);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged, id);
|
||||
await load();
|
||||
Message.success("产品已停用");
|
||||
} catch (error) {
|
||||
@@ -296,6 +272,32 @@ function disable(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function remove(): void {
|
||||
const id = product.value?.id;
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
const dialog = DialogPlugin.confirm({
|
||||
title: "移除产品",
|
||||
content: "仅可移除没有订单、履约、库存流水、配置引用和库存余额的产品。确定提交移除?",
|
||||
cancelBtn: "取消",
|
||||
confirmBtn: { content: "移除", theme: "danger" },
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await ProductAPI.remove(id);
|
||||
emitListDataChanged(listDataEventKeys.productChanged, id);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged, id);
|
||||
Message.success("产品已移除");
|
||||
await router.replace("/management/products");
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "产品移除失败"));
|
||||
} finally {
|
||||
dialog.destroy();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.clearRight();
|
||||
navBarStore.setCustomRightVisible(actionList.value.length > 0);
|
||||
@@ -317,7 +319,15 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
padding: calc(var(--app-nav-height) + 1rem) 0 1rem 0;
|
||||
flex-direction: column;
|
||||
|
||||
.units {
|
||||
.skus {
|
||||
|
||||
.sku {
|
||||
padding: 10px;
|
||||
|
||||
.avatar {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
}
|
||||
|
||||
.title {
|
||||
gap: .5rem;
|
||||
@@ -335,116 +345,23 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sku-popup {
|
||||
padding: 0 0 calc(1rem + env(safe-area-inset-bottom, 0px));
|
||||
max-height: 100%;
|
||||
padding: 1rem 0 calc(1rem + env(safe-area-inset-bottom, 0px));
|
||||
overflow-y: auto;
|
||||
|
||||
.sku-popup-header {
|
||||
gap: .75rem;
|
||||
display: flex;
|
||||
padding: 0 1rem .75rem;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
.media-wrap {
|
||||
margin: 0 1rem;
|
||||
}
|
||||
|
||||
.sku-heading {
|
||||
gap: .5rem;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
strong {
|
||||
font-size: 1.125rem;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.code {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.sku-spec-panel {
|
||||
margin: 0 .75rem .75rem;
|
||||
padding: .75rem;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-radius: .875rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
|
||||
span {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
.sku-spec-list {
|
||||
gap: .5rem;
|
||||
display: grid;
|
||||
margin-top: .625rem;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.sku-spec-item {
|
||||
gap: .375rem;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
padding: .5rem .625rem;
|
||||
align-items: baseline;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: .625rem;
|
||||
|
||||
.spec-name {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
strong {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
.sku-spec-empty,
|
||||
.unit-empty {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
}
|
||||
|
||||
.sku-spec-empty {
|
||||
margin-top: .5rem;
|
||||
}
|
||||
|
||||
:deep(.t-cell-group) {
|
||||
margin: 0 0 .75rem;
|
||||
}
|
||||
|
||||
:deep(.photo-scroller) {
|
||||
margin: 0 .75rem .75rem;
|
||||
}
|
||||
|
||||
.unit-section {
|
||||
.unit {
|
||||
margin-top: .75rem;
|
||||
border-top: 1px solid var(--td-component-border);
|
||||
}
|
||||
|
||||
.unit-heading {
|
||||
.header {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
padding: .75rem 1rem .5rem;
|
||||
@@ -458,33 +375,6 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
}
|
||||
}
|
||||
|
||||
.unit-list {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
padding: 0 1rem .75rem;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.unit-item {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
padding: .625rem .75rem;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-radius: .75rem;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.unit-name {
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.unit-meta {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: .75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<t-textarea v-model="form.remark" borderless maxlength="255" autosize placeholder="可填写产品说明" />
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
v-model="attachmentUrlList"
|
||||
v-model:photo-items="attachmentItemList"
|
||||
title="产品公共图片及附件"
|
||||
@@ -31,8 +31,10 @@
|
||||
:loading="isAttachmentUploading"
|
||||
:show-viewer-actions="false"
|
||||
:add-actions="attachmentAddActions"
|
||||
@add-photo="openAttachmentPicker('PHOTO')"
|
||||
@add-other="openAttachmentPicker('OTHER')"
|
||||
@add="openAttachmentPicker('OTHER')"
|
||||
@action="handleAttachmentAction"
|
||||
@capture-photo="capturePhoto"
|
||||
@capture-video="captureVideo"
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item label="纯色封面" label-width="8rem" content-align="right">
|
||||
@@ -64,7 +66,6 @@
|
||||
v-model="spec.name"
|
||||
borderless
|
||||
maxlength="32"
|
||||
:readonly="!!spec.id"
|
||||
placeholder="如 颜色、尺寸"
|
||||
/>
|
||||
<t-button
|
||||
@@ -83,10 +84,11 @@
|
||||
:key="value.clientKey"
|
||||
class="tag"
|
||||
variant="light-outline"
|
||||
:content="value.name"
|
||||
closable
|
||||
@close="removeSpecValue(spec, spec.valueList.indexOf(value))"
|
||||
/>
|
||||
>
|
||||
<t-input v-model.trim="value.name" class="value-name" borderless maxlength="32" />
|
||||
</t-tag>
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label="规格值" label-width="3.5rem">
|
||||
@@ -149,7 +151,7 @@
|
||||
</t-cell>
|
||||
<t-cell title="当前 SKU" :note="`${form.skuList.length} 个`" />
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="form.skuList.length" theme="card" class="sku-list">
|
||||
<t-cell-group v-if="form.skuList.length" theme="card" class="sku-list fix-last-cell-line">
|
||||
<product-sku-editor
|
||||
v-for="(sku, skuIndex) in form.skuList"
|
||||
:key="sku.clientKey"
|
||||
@@ -183,6 +185,7 @@
|
||||
<product-sku-unit-batch-editor
|
||||
v-model="batchUnitEditorVisible"
|
||||
v-model:unit-list="batchUnitList"
|
||||
v-model:base-unit-migration-ratio-text="batchBaseUnitMigrationRatioText"
|
||||
:product-type="form.productType"
|
||||
:sku-count="form.skuList.length"
|
||||
@apply="applyBatchUnitTemplate"
|
||||
@@ -197,29 +200,34 @@
|
||||
>
|
||||
<t-color-picker v-if="coverColorPickerVisible" v-model="coverColorDraft" format="HEX" type="multiple" :swatch-colors="colorSwatchList" @palette-bar-change="updateCoverColorDraftFromPalette" />
|
||||
</bottom-popup>
|
||||
<input ref="attachmentInputRef" class="file-input" type="file" accept="image/*" @change="handleAttachmentSelected" />
|
||||
<input ref="attachmentInputRef" class="file-input" type="file" accept="*/*" @change="handleAttachmentSelected" />
|
||||
<input ref="photoInputRef" class="file-input" type="file" accept="image/*" capture="environment" @change="handleAttachmentSelected" />
|
||||
<input ref="videoInputRef" class="file-input" type="file" accept="video/*" capture="environment" @change="handleAttachmentSelected" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import type { ColorObject } from "tdesign-mobile-vue";
|
||||
import { DialogPlugin, type ColorObject } from "tdesign-mobile-vue";
|
||||
import { type Attachment, AttachmentAPI, useUserStore } from "timi-web-api";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import ProductSkuEditor from "@/pages/product/component/ProductSkuEditor.vue";
|
||||
import ProductSkuUnitEditor from "@/pages/product/component/ProductSkuUnitEditor.vue";
|
||||
import ProductSkuUnitBatchEditor from "@/pages/product/component/ProductSkuUnitBatchEditor.vue";
|
||||
import type { MediaSelectorAddAction } from "@/components/mediaSelector/types";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
import type { Product, ProductAttachmentType, ProductCategory, ProductSku, ProductSkuUnit, ProductSpec } from "@/types/Product";
|
||||
import type { Product, ProductAttachmentType, ProductCategory, ProductSku, ProductSkuUnit, ProductSpec, ProductType } from "@/types/Product";
|
||||
import type { ProductAttachmentItem, ProductForm, ProductSkuForm as SkuForm, ProductSkuUnitForm as UnitForm, ProductSpecForm as SpecForm, ProductSpecValueForm as SpecValueForm } from "@/types/ProductEditor";
|
||||
import { compressUploadImage } from "@/utils/imageCompression";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||||
import { formatProductAmount, getProductStatusText, getProductTypeText, normalizeProductQuantity, parseProductAmount } from "@/utils/product";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { saveCapturedFilesFromInput } from "@/utils/twaBridge";
|
||||
|
||||
type PickerValue = string | number;
|
||||
|
||||
@@ -252,6 +260,8 @@ const typePickerVisible = ref(false);
|
||||
const categoryPickerVisible = ref(false);
|
||||
const statusPickerVisible = ref(false);
|
||||
const attachmentInputRef = ref<HTMLInputElement>();
|
||||
const photoInputRef = ref<HTMLInputElement>();
|
||||
const videoInputRef = ref<HTMLInputElement>();
|
||||
const attachmentPickerTarget = ref<ProductAttachmentType>("PHOTO");
|
||||
const isAttachmentUploading = ref(false);
|
||||
const coverColorPickerVisible = ref(false);
|
||||
@@ -269,7 +279,6 @@ const statusOptions = [{ label: "启用", value: "ACTIVE" }, { label: "停用",
|
||||
const colorSwatchList = ["#2F88FF", "#0EA5E9", "#10B981", "#22C55E", "#F59E0B", "#F97316", "#EF4444", "#EC4899", "#8B5CF6", "#64748B"];
|
||||
const selectedCategoryName = computed(() => categoryList.value.find(item => item.id === form.categoryId)?.name || "不设置分类");
|
||||
const attachmentAddActions = [
|
||||
{ icon: "camera", text: "产品图片", emit: "add-photo", theme: "primary" },
|
||||
{ icon: "file-attachment", text: "其他文件", emit: "add-other", theme: "default" }
|
||||
] as const;
|
||||
const attachmentItemList = ref<ProductAttachmentItem[]>([]);
|
||||
@@ -298,6 +307,7 @@ const unitEditorVisible = ref(false);
|
||||
const editingSku = ref<SkuForm>();
|
||||
const batchUnitEditorVisible = ref(false);
|
||||
const batchUnitList = ref<UnitForm[]>([]);
|
||||
const batchBaseUnitMigrationRatioText = ref("");
|
||||
const removedSkuKeySet = new Set<string>();
|
||||
const removedSkuMap = new Map<string, SkuForm>();
|
||||
|
||||
@@ -318,6 +328,7 @@ function createUnit(unit?: Partial<ProductSkuUnit>, defaultName = "件"): UnitFo
|
||||
|
||||
function createSku(sku?: Partial<ProductSku>): SkuForm {
|
||||
const sourceUnitList = sku?.unitList || [];
|
||||
const originalBaseUnitId = sourceUnitList.find(unit => unit.isBase)?.id;
|
||||
const photoItemList = (sku?.attachmentList || []).filter(item => !!item.id).map(item => ({
|
||||
attachment: item,
|
||||
attachType: item.attachType || "PHOTO",
|
||||
@@ -336,6 +347,8 @@ function createSku(sku?: Partial<ProductSku>): SkuForm {
|
||||
status: sku?.status || "ACTIVE",
|
||||
minStockQuantityText: sku?.minStockQuantity === null || sku?.minStockQuantity === undefined ? "" : String(sku.minStockQuantity),
|
||||
unitList: sourceUnitList.length ? sourceUnitList.map(unit => createUnit(unit)) : [createUnit({ isBase: true, baseQuantityPerUnit: "1" })],
|
||||
originalBaseUnitId,
|
||||
baseUnitMigrationRatioText: "",
|
||||
photoItemList
|
||||
};
|
||||
}
|
||||
@@ -346,7 +359,17 @@ function createSpec(spec?: Partial<ProductSpec>): SpecForm {
|
||||
id: spec?.id,
|
||||
clientKey: window.crypto.randomUUID(),
|
||||
name: spec?.name || "",
|
||||
valueList: (spec?.valueList || []).map(value => ({ ...value, id: value.id, clientKey: window.crypto.randomUUID(), name: value.name || "", enabled: value.enabled ?? true }))
|
||||
originalName: spec?.name || "",
|
||||
originalSort: spec?.sort,
|
||||
valueList: (spec?.valueList || []).map(value => ({
|
||||
...value,
|
||||
id: value.id,
|
||||
clientKey: window.crypto.randomUUID(),
|
||||
name: value.name || "",
|
||||
originalName: value.name || "",
|
||||
originalSort: value.sort,
|
||||
enabled: value.enabled ?? true
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -377,7 +400,7 @@ function addSpecValue(spec: SpecForm): void {
|
||||
Message.warning("同一规格项的规格值不能重复");
|
||||
return;
|
||||
}
|
||||
spec.valueList.push({ clientKey: window.crypto.randomUUID(), name, enabled: true });
|
||||
spec.valueList.push({ clientKey: window.crypto.randomUUID(), name, originalName: name, originalSort: spec.valueList.length, enabled: true });
|
||||
specValueDraftMap[spec.clientKey] = "";
|
||||
}
|
||||
|
||||
@@ -409,6 +432,7 @@ function openBatchUnitEditor(): void {
|
||||
return;
|
||||
}
|
||||
batchUnitList.value = sourceSku.unitList.map(unit => ({ ...unit, id: undefined, skuId: undefined, clientKey: window.crypto.randomUUID() }));
|
||||
batchBaseUnitMigrationRatioText.value = "";
|
||||
batchUnitEditorVisible.value = true;
|
||||
}
|
||||
|
||||
@@ -420,13 +444,19 @@ function applyBatchUnitTemplate(): void {
|
||||
const templateList = batchUnitList.value;
|
||||
form.skuList.forEach(sku => {
|
||||
const oldUnitList = sku.unitList;
|
||||
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) => ({
|
||||
...unit,
|
||||
id: oldUnitList[unitIndex]?.id,
|
||||
id: oldUnitMap.get(unit.name.trim())?.id,
|
||||
skuId: sku.id,
|
||||
clientKey: window.crypto.randomUUID(),
|
||||
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 统一配置销售单位`);
|
||||
}
|
||||
@@ -436,7 +466,7 @@ function removeSku(index: number): void {
|
||||
if (!sku) {
|
||||
return;
|
||||
}
|
||||
if (form.skuList.length < 2) {
|
||||
if (isCreateMode.value && form.skuList.length < 2) {
|
||||
Message.warning("产品至少需要一个 SKU");
|
||||
return;
|
||||
}
|
||||
@@ -447,7 +477,7 @@ function removeSku(index: number): void {
|
||||
}
|
||||
form.skuList.splice(index, 1);
|
||||
if (sku.id) {
|
||||
Message.success("SKU 已移除,保存后将停用");
|
||||
Message.success("SKU 已移除,保存后由后端检查引用并处理");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,19 +486,64 @@ function openTypePicker(): void {
|
||||
typePickerVisible.value = true;
|
||||
}
|
||||
|
||||
function confirmType(value: Array<string | number>): void {
|
||||
async function confirmType(value: Array<string | number>): Promise<void> {
|
||||
const type = String(value[0] || "");
|
||||
if (type === "SERVICE" || type === "GOODS" || type === "CONSUMABLE") {
|
||||
if (type !== "SERVICE" && type !== "GOODS" && type !== "CONSUMABLE") {
|
||||
typePickerVisible.value = false;
|
||||
return;
|
||||
}
|
||||
typePickerVisible.value = false;
|
||||
if (type !== "SERVICE" || form.productType === "SERVICE") {
|
||||
applyProductType(type);
|
||||
return;
|
||||
}
|
||||
if (!await canChangeToService()) {
|
||||
return;
|
||||
}
|
||||
const dialog = DialogPlugin.confirm({
|
||||
title: "切换为服务产品",
|
||||
content: "切换后将关闭产品及全部 SKU 的库存管理,并清空最低库存设置;已有库存流水会保留。确定继续吗?",
|
||||
cancelBtn: "取消",
|
||||
confirmBtn: "确定切换",
|
||||
onCancel() {
|
||||
dialog.destroy();
|
||||
},
|
||||
onConfirm() {
|
||||
dialog.destroy();
|
||||
applyProductType("SERVICE");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function applyProductType(type: ProductType): void {
|
||||
form.productType = type;
|
||||
if (type === "SERVICE") {
|
||||
if (type !== "SERVICE") {
|
||||
return;
|
||||
}
|
||||
form.stockEnabled = false;
|
||||
form.skuList.forEach(sku => {
|
||||
sku.stockEnabled = false;
|
||||
sku.minStockQuantityText = "";
|
||||
sku.unitList.forEach(unit => { unit.allowPurchase = false; });
|
||||
});
|
||||
}
|
||||
|
||||
async function canChangeToService(): Promise<boolean> {
|
||||
const skuIdList = form.skuList.map(sku => sku.id).filter((id): id is string => !!id);
|
||||
if (!skuIdList.length) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const stockList = await ProductAPI.stockBatchDetail({ skuIdList });
|
||||
if (stockList.some(stock => 0 < Number(stock.reservedQuantity || 0))) {
|
||||
Message.warning("当前产品存在预占库存,不能切换为服务产品,请先完成或取消相关订单");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "无法确认预占库存,暂不能切换为服务产品"));
|
||||
return false;
|
||||
}
|
||||
typePickerVisible.value = false;
|
||||
}
|
||||
|
||||
function openCategoryPicker(): void {
|
||||
@@ -499,6 +574,22 @@ function openAttachmentPicker(target: ProductAttachmentType): void {
|
||||
attachmentInputRef.value?.click();
|
||||
}
|
||||
|
||||
function capturePhoto(): void {
|
||||
attachmentPickerTarget.value = "PHOTO";
|
||||
photoInputRef.value?.click();
|
||||
}
|
||||
|
||||
function captureVideo(): void {
|
||||
attachmentPickerTarget.value = "OTHER";
|
||||
videoInputRef.value?.click();
|
||||
}
|
||||
|
||||
function handleAttachmentAction(action: MediaSelectorAddAction): void {
|
||||
if (action.emit === "add-other") {
|
||||
openAttachmentPicker("OTHER");
|
||||
}
|
||||
}
|
||||
|
||||
function openCoverColorPicker(): void {
|
||||
coverColorDraft.value = solidColorCoverColor.value || DEFAULT_COVER_COLOR;
|
||||
coverColorPickerVisible.value = true;
|
||||
@@ -571,11 +662,12 @@ async function handleAttachmentSelected(event: Event): Promise<void> {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
saveCapturedFilesFromInput(input, [file]);
|
||||
isAttachmentUploading.value = true;
|
||||
try {
|
||||
const tempFile = (await AttachmentAPI.upload(await compressUploadImage(file)))[0];
|
||||
if (tempFile?.id) {
|
||||
attachmentItemList.value.push({ attachType: attachmentPickerTarget.value, tempFileId: tempFile.id, url: AttachmentAPI.getTempReadURL(tempFile.id) });
|
||||
attachmentItemList.value.push({ attachType: attachmentPickerTarget.value, mimeType: file.type, tempFileId: tempFile.id, url: AttachmentAPI.getTempReadURL(tempFile.id) });
|
||||
}
|
||||
} catch (error) {
|
||||
Message.error(getErrorMessage(error, "产品附件上传失败"));
|
||||
@@ -587,24 +679,33 @@ async function handleAttachmentSelected(event: Event): Promise<void> {
|
||||
|
||||
function buildAttachmentList(): Attachment[] {
|
||||
return attachmentItemList.value.flatMap(item => {
|
||||
if (item.tempFileId) {
|
||||
return [{
|
||||
...item.attachment,
|
||||
attachType: item.attachType || item.attachment?.attachType || "PHOTO",
|
||||
tempFileId: item.tempFileId,
|
||||
metadata: item.isSolidColorCover && item.solidColor ? { purpose: SOLID_COLOR_COVER_PURPOSE, color: item.solidColor } : undefined
|
||||
} as Attachment];
|
||||
}
|
||||
if (item.attachment) {
|
||||
return [{ ...item.attachment, attachType: item.attachType || item.attachment.attachType || "PHOTO" }];
|
||||
}
|
||||
if (item.tempFileId) {
|
||||
return [{ attachType: item.attachType, tempFileId: item.tempFileId, metadata: item.isSolidColorCover && item.solidColor ? { purpose: SOLID_COLOR_COVER_PURPOSE, color: item.solidColor } : undefined }];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
function buildSkuAttachmentList(photoItemList: PhotoItem[]): Attachment[] {
|
||||
return photoItemList.flatMap(item => {
|
||||
if (item.tempFileId) {
|
||||
return [{
|
||||
...item.attachment,
|
||||
attachType: item.attachType || item.attachment?.attachType || "PHOTO",
|
||||
tempFileId: item.tempFileId
|
||||
} as Attachment];
|
||||
}
|
||||
if (item.attachment) {
|
||||
return [{ ...item.attachment, attachType: item.attachType || item.attachment.attachType || "PHOTO" } as Attachment];
|
||||
}
|
||||
if (item.tempFileId) {
|
||||
return [{ attachType: item.attachType || "PHOTO", tempFileId: item.tempFileId } as Attachment];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
}
|
||||
@@ -780,7 +881,7 @@ function validate(): boolean {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!form.skuList.length) {
|
||||
if (isCreateMode.value && !form.skuList.length) {
|
||||
Message.warning("至少需要一个 SKU");
|
||||
return false;
|
||||
}
|
||||
@@ -842,6 +943,16 @@ function validate(): boolean {
|
||||
Message.warning("每个 SKU 必须且只能有一个基础单位");
|
||||
return false;
|
||||
}
|
||||
const selectedBaseUnit = sku.unitList.find(unit => unit.isBase);
|
||||
const isBaseUnitChanged = !!sku.originalBaseUnitId && selectedBaseUnit?.id !== sku.originalBaseUnitId;
|
||||
if (isBaseUnitChanged && !/^\d+(?:\.\d{1,6})?$/.test(sku.baseUnitMigrationRatioText.trim())) {
|
||||
Message.warning("切换基础单位时,请填写有效的新旧基础单位换算比例,最多六位小数");
|
||||
return false;
|
||||
}
|
||||
if (isBaseUnitChanged && !(0 < Number(sku.baseUnitMigrationRatioText))) {
|
||||
Message.warning("新旧基础单位换算比例必须大于 0");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -871,7 +982,14 @@ function buildSkuPayload(sku: SkuForm, index: number): ProductSku {
|
||||
allowPurchase: form.productType === "SERVICE" ? false : !!unit.allowPurchase,
|
||||
allowSale: !!unit.allowSale,
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
@@ -886,11 +1004,18 @@ function buildProductPayload(skuList?: ProductSku[], includeSpecList = false): P
|
||||
status: form.status,
|
||||
remark: form.remark?.trim() || null,
|
||||
attachmentList: buildAttachmentList(),
|
||||
specList: includeSpecList ? form.specList.map(spec => ({
|
||||
...spec,
|
||||
specList: includeSpecList ? form.specList.map((spec, specIndex) => ({
|
||||
id: spec.id,
|
||||
productId: form.id,
|
||||
name: spec.name.trim(),
|
||||
valueList: spec.valueList.map(value => ({ ...value, name: value.name.trim() }))
|
||||
sort: specIndex,
|
||||
valueList: spec.valueList.map((value, valueIndex) => ({
|
||||
id: value.id,
|
||||
specId: spec.id,
|
||||
name: value.name.trim(),
|
||||
enabled: value.enabled !== false,
|
||||
sort: valueIndex
|
||||
}))
|
||||
})) : undefined,
|
||||
skuList
|
||||
};
|
||||
@@ -900,11 +1025,23 @@ async function syncSpecs(productId: string): Promise<void> {
|
||||
for (const [specIndex, spec] of form.specList.entries()) {
|
||||
if (!spec.id) {
|
||||
spec.id = await ProductAPI.specCreate({ productId, name: spec.name.trim(), sort: specIndex });
|
||||
spec.originalName = spec.name.trim();
|
||||
spec.originalSort = specIndex;
|
||||
} else if (spec.name.trim() !== spec.originalName || specIndex !== spec.originalSort) {
|
||||
await ProductAPI.specUpdate({ id: spec.id, productId, name: spec.name.trim(), sort: specIndex });
|
||||
spec.originalName = spec.name.trim();
|
||||
spec.originalSort = specIndex;
|
||||
}
|
||||
for (const [valueIndex, value] of spec.valueList.entries()) {
|
||||
if (!value.id) {
|
||||
value.specId = spec.id;
|
||||
value.id = await ProductAPI.specValueCreate({ specId: spec.id, name: value.name.trim(), enabled: value.enabled !== false, sort: valueIndex });
|
||||
value.originalName = value.name.trim();
|
||||
value.originalSort = valueIndex;
|
||||
} else if (value.name.trim() !== value.originalName || valueIndex !== value.originalSort) {
|
||||
await ProductAPI.specValueUpdate({ id: value.id, specId: spec.id, name: value.name.trim(), enabled: value.enabled !== false, sort: valueIndex });
|
||||
value.originalName = value.name.trim();
|
||||
value.originalSort = valueIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -921,6 +1058,8 @@ async function save(): Promise<void> {
|
||||
generateSkuList([], true);
|
||||
}
|
||||
const productId = await ProductAPI.create(buildProductPayload(form.skuList.map(buildSkuPayload), true));
|
||||
emitListDataChanged(listDataEventKeys.productChanged, productId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged, productId);
|
||||
Message.success("产品已创建");
|
||||
await router.replace(`/management/products/${productId}`);
|
||||
return;
|
||||
@@ -929,23 +1068,19 @@ async function save(): Promise<void> {
|
||||
await syncSpecs(productId!);
|
||||
normalizeSkuSpecValueIds();
|
||||
const latest = await ProductAPI.detail(productId!);
|
||||
const previousSkuIdSet = new Set((latest.skuList || []).map(sku => sku.id).filter((id): id is string => !!id));
|
||||
if (form.specList.length) {
|
||||
const defaultSku = latest.skuList?.find(sku => !sku.specValueIdList?.length);
|
||||
if (defaultSku?.id && form.skuList[0] && !form.skuList[0].id) {
|
||||
form.skuList[0].id = defaultSku.id;
|
||||
}
|
||||
generateSkuList(latest.skuList || [], true);
|
||||
} else if (!form.skuList.length) {
|
||||
form.skuList = [createSku(latest.skuList?.[0])];
|
||||
} else if (!form.skuList[0]?.id && latest.skuList?.[0]) {
|
||||
} else if (form.skuList[0] && !form.skuList[0].id && latest.skuList?.[0]) {
|
||||
form.skuList[0].id = latest.skuList[0].id;
|
||||
}
|
||||
const payload = buildProductPayload(form.skuList.map(buildSkuPayload));
|
||||
await ProductAPI.update(payload);
|
||||
const retainedSkuIdSet = new Set(form.skuList.map(sku => sku.id).filter((id): id is string => !!id));
|
||||
const disabledSkuIdList = [...previousSkuIdSet].filter(id => !retainedSkuIdSet.has(id));
|
||||
await Promise.all(disabledSkuIdList.map(async skuId => await ProductAPI.skuDisable(skuId)));
|
||||
emitListDataChanged(listDataEventKeys.productChanged, productId);
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged, productId);
|
||||
Message.success(isCreateMode.value ? "产品已创建" : "产品已保存");
|
||||
await router.replace(`/management/products/${productId}`);
|
||||
} catch (error) {
|
||||
@@ -1086,6 +1221,10 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.value-name {
|
||||
width: 5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.product.read" class="product-list">
|
||||
<div class="filters bg-white">
|
||||
<div ref="productListRef" v-can="permissionCodes.product.read" class="product-list">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="keyword"
|
||||
class="keyword"
|
||||
@@ -68,11 +68,6 @@
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="description">
|
||||
<t-tag
|
||||
size="small"
|
||||
variant="outline"
|
||||
:content="item.code"
|
||||
/>
|
||||
<t-tag
|
||||
size="small"
|
||||
variant="outline"
|
||||
@@ -86,12 +81,13 @@
|
||||
<div v-if="productList.length" class="center-tips" v-text="isLoading ? '正在加载更多' : isNoMore ? '已经到底了' : '上拉加载更多'" />
|
||||
</t-pull-down-refresh>
|
||||
</div>
|
||||
<nav-bar-action-menu v-if="canCreate" :actions="actionList" />
|
||||
<nav-bar-action-menu v-if="route.name === 'ProductList' && canCreate" :actions="actionList" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { type DropdownValue } from "tdesign-mobile-vue";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import { onBeforeRouteLeave } from "vue-router";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import NavBarActionMenu from "@/components/NavBarActionMenu.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
@@ -99,12 +95,15 @@ import type { NavBarAction } from "@/types/NavBarAction";
|
||||
import type { Product, ProductCategory, ProductStatus, ProductType } from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { getProductPhotoURL, getProductStatusText, getProductStatusTheme, getProductTypeText } from "@/utils/product";
|
||||
import { events, isCurrentStoreEvent, listDataEventKeys, type ListDataChangedPayload } from "@/utils/listDataEvents";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
defineOptions({ name: "ProductList" });
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const productListRef = ref<HTMLElement | null>(null);
|
||||
const navBarStore = useNavBarStore();
|
||||
const userStore = useUserStore();
|
||||
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.product.create));
|
||||
@@ -129,6 +128,46 @@ const isRefreshing = ref(false);
|
||||
const isNoMore = ref(false);
|
||||
let keywordTimer: number | undefined;
|
||||
let requestToken = 0;
|
||||
let savedPageScrollTop: number | undefined;
|
||||
let eventRefreshPromise: Promise<void> | undefined;
|
||||
let hasPendingEventRefresh = false;
|
||||
let unregisterProductListEvent: (() => void) | undefined;
|
||||
let isDisposed = false;
|
||||
|
||||
function getProductListPage(): HTMLElement | null {
|
||||
return productListRef.value?.closest<HTMLElement>(".page") || null;
|
||||
}
|
||||
|
||||
function savePageScrollPosition(): void {
|
||||
const page = getProductListPage();
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
|
||||
savedPageScrollTop = page.scrollTop;
|
||||
}
|
||||
|
||||
function restorePageScrollPosition(): void {
|
||||
if (savedPageScrollTop === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scrollTop = savedPageScrollTop;
|
||||
requestAnimationFrame(() => {
|
||||
const page = getProductListPage();
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
|
||||
page.scrollTop = scrollTop;
|
||||
savedPageScrollTop = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
function syncNavBar(): void {
|
||||
navBarStore.clearRight();
|
||||
navBarStore.setCustomRightVisible(route.name === "ProductList" && canCreate.value);
|
||||
}
|
||||
|
||||
const statusOptions = [
|
||||
{ label: "全部状态", value: "ALL" },
|
||||
@@ -152,20 +191,56 @@ async function loadCategories(): Promise<void> {
|
||||
categoryList.value = result.list || [];
|
||||
}
|
||||
|
||||
async function fetch(reset = false): Promise<void> {
|
||||
async function fetch(reset = false, preserveScroll = false): Promise<void> {
|
||||
if (!reset && (isLoading.value || isNoMore.value)) {
|
||||
return;
|
||||
}
|
||||
const loadedPageCount = reset && preserveScroll ? Math.max(pageIndex.value, 1) : 1;
|
||||
const preserveScrollTop = preserveScroll ? getProductListPage()?.scrollTop : undefined;
|
||||
if (reset) {
|
||||
pageIndex.value = 0;
|
||||
productList.value = [];
|
||||
total.value = 0;
|
||||
isNoMore.value = false;
|
||||
if (!preserveScroll) {
|
||||
const page = getProductListPage();
|
||||
if (page) {
|
||||
page.scrollTop = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
const token = ++requestToken;
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const pageSize = 15;
|
||||
if (reset && preserveScroll) {
|
||||
const nextList: Product[] = [];
|
||||
let nextTotal = 0;
|
||||
let nextPageIndex = 0;
|
||||
for (let index = 0; index < loadedPageCount; index += 1) {
|
||||
const result = await ProductAPI.list({
|
||||
index,
|
||||
size: pageSize,
|
||||
keyword: keyword.value || undefined,
|
||||
status: status.value === "ALL" ? undefined : status.value as ProductStatus,
|
||||
productType: productType.value === "ALL" ? undefined : productType.value as ProductType,
|
||||
categoryIdList: categoryIdList.value.includes("ALL") ? undefined : categoryIdList.value
|
||||
});
|
||||
if (token !== requestToken) {
|
||||
return;
|
||||
}
|
||||
const list = result.list || [];
|
||||
nextList.push(...list);
|
||||
nextTotal = result.total || 0;
|
||||
nextPageIndex += 1;
|
||||
if (list.length < pageSize || nextTotal <= nextList.length) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
productList.value = nextList;
|
||||
total.value = nextTotal;
|
||||
pageIndex.value = nextPageIndex;
|
||||
isNoMore.value = nextList.length < pageSize || nextList.length === nextTotal || nextTotal < nextList.length;
|
||||
} else {
|
||||
const result = await ProductAPI.list({
|
||||
index: pageIndex.value,
|
||||
size: pageSize,
|
||||
@@ -182,6 +257,15 @@ async function fetch(reset = false): Promise<void> {
|
||||
total.value = result.total || 0;
|
||||
pageIndex.value += 1;
|
||||
isNoMore.value = list.length < pageSize || productList.value.length === total.value || total.value < productList.value.length;
|
||||
}
|
||||
if (preserveScrollTop !== undefined) {
|
||||
requestAnimationFrame(() => {
|
||||
const page = getProductListPage();
|
||||
if (page) {
|
||||
page.scrollTop = preserveScrollTop;
|
||||
}
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (token === requestToken) {
|
||||
isLoading.value = false;
|
||||
@@ -189,6 +273,32 @@ async function fetch(reset = false): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function startEventRefresh(): void {
|
||||
if (isDisposed) {
|
||||
return;
|
||||
}
|
||||
eventRefreshPromise = fetch(true, true)
|
||||
.catch(error => Message.error(getErrorMessage(error, "产品列表加载失败")))
|
||||
.finally(() => {
|
||||
eventRefreshPromise = undefined;
|
||||
if (!isDisposed && hasPendingEventRefresh) {
|
||||
hasPendingEventRefresh = false;
|
||||
startEventRefresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function requestEventRefresh(payload?: ListDataChangedPayload): void {
|
||||
if (!isCurrentStoreEvent(payload)) {
|
||||
return;
|
||||
}
|
||||
if (eventRefreshPromise) {
|
||||
hasPendingEventRefresh = true;
|
||||
return;
|
||||
}
|
||||
startEventRefresh();
|
||||
}
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
try {
|
||||
await fetch(true);
|
||||
@@ -265,8 +375,8 @@ async function toDetail(item: Product): Promise<void> {
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
navBarStore.clearRight();
|
||||
navBarStore.setCustomRightVisible(canCreate.value);
|
||||
unregisterProductListEvent = events.register(listDataEventKeys.productChanged, (payload: ListDataChangedPayload) => requestEventRefresh(payload));
|
||||
syncNavBar();
|
||||
try {
|
||||
await Promise.all([loadCategories(), fetch(true)]);
|
||||
} catch (error) {
|
||||
@@ -274,6 +384,15 @@ onMounted(async () => {
|
||||
}
|
||||
});
|
||||
|
||||
onActivated(() => {
|
||||
restorePageScrollPosition();
|
||||
syncNavBar();
|
||||
});
|
||||
|
||||
onDeactivated(() => {
|
||||
savePageScrollPosition();
|
||||
});
|
||||
|
||||
watch(keyword, () => {
|
||||
window.clearTimeout(keywordTimer);
|
||||
keywordTimer = window.setTimeout(async () => {
|
||||
@@ -285,7 +404,15 @@ watch(keyword, () => {
|
||||
}, 300);
|
||||
});
|
||||
|
||||
onBeforeRouteLeave(() => {
|
||||
savePageScrollPosition();
|
||||
navBarStore.clearRight();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
isDisposed = true;
|
||||
unregisterProductListEvent?.();
|
||||
unregisterProductListEvent = undefined;
|
||||
navBarStore.clearRight();
|
||||
window.clearTimeout(keywordTimer);
|
||||
requestToken += 1;
|
||||
@@ -304,8 +431,6 @@ onUnmounted(() => {
|
||||
display: flex;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: #F5F5F8;
|
||||
box-shadow: var(--td-shadow-1);
|
||||
flex-direction: column;
|
||||
|
||||
.keyword {
|
||||
@@ -313,7 +438,6 @@ onUnmounted(() => {
|
||||
|
||||
border: 1px solid var(--td-component-border);
|
||||
z-index: 1;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
@@ -321,31 +445,15 @@ onUnmounted(() => {
|
||||
--td-spacer-1: 6px;
|
||||
|
||||
width: 100%;
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
overflow: hidden;
|
||||
margin-top: -1rem;
|
||||
padding-top: .8rem;
|
||||
background: #fff;
|
||||
border: 1px solid rgba(148, 163, 184, .18);
|
||||
border-radius: 0 0 1rem 1rem;
|
||||
|
||||
&:after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:deep(.t-dropdown-menu__item) {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
:deep(.t-dropdown-menu__title) {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
padding-top: .75rem;
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
|
||||
@@ -9,6 +9,24 @@
|
||||
</template>
|
||||
</product-profile>
|
||||
<t-cell-group theme="card" title="库存" v-entrance-transition="70">
|
||||
<t-cell v-if="1 < unitList.length" class="units" title="显示单位">
|
||||
<template #note>
|
||||
<div class="options" role="group" aria-label="选择库存展示单位">
|
||||
<t-button
|
||||
v-for="item in unitList"
|
||||
:key="item.id"
|
||||
size="extra-small"
|
||||
:theme="selectedUnit?.id === item.id ? 'primary' : 'default'"
|
||||
:variant="selectedUnit?.id === item.id ? 'base' : 'outline'"
|
||||
:aria-label="`切换到${item.name || '未命名单位'}`"
|
||||
:aria-pressed="selectedUnit?.id === item.id"
|
||||
@click="selectUnit(item.id || '')"
|
||||
>
|
||||
<span v-text="item.name || '未命名单位'" />
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell class="empty-cell-title-margin">
|
||||
<template #title>
|
||||
<span></span>
|
||||
@@ -18,27 +36,28 @@
|
||||
<div class="main">
|
||||
<span class="label">库存</span>
|
||||
<div class="value">
|
||||
<strong class="text" v-text="getProductQuantityText(stock.onHandQuantity)" />
|
||||
<span class="unit" v-text="getProductBaseUnitName(sku) || '基础单位'" />
|
||||
<strong class="text" v-text="displayStock.onHandQuantity" />
|
||||
<span class="unit" v-text="selectedUnitName" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<div class="available">
|
||||
<span class="label">可用</span>
|
||||
<strong class="value" v-text="getProductQuantityText(stock.availableQuantity)" />
|
||||
<span class="unit" v-text="getProductBaseUnitName(sku) || '基础单位'" />
|
||||
<strong class="value" v-text="displayStock.availableQuantity" />
|
||||
<span class="unit" v-text="selectedUnitName" />
|
||||
</div>
|
||||
<div class="reserved">
|
||||
<span class="label">预占</span>
|
||||
<strong class="value" v-text="getProductQuantityText(stock.reservedQuantity)" />
|
||||
<span class="unit" v-text="getProductBaseUnitName(sku) || '基础单位'" />
|
||||
<strong class="value" v-text="displayStock.reservedQuantity" />
|
||||
<span class="unit" v-text="selectedUnitName" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell v-if="0 < Number(stock.reservedQuantity || 0)" title="查看预占流水" arrow @click="openReservedRecordList" />
|
||||
<t-cell title="查看该产品 SKU 流水" arrow @click="openRecordList" />
|
||||
<product-stock-package-summary :sku="sku" :stock="stock" />
|
||||
<t-cell title="查看库存流水" arrow @click="openRecordList" />
|
||||
<t-cell v-if="0 < Number(stock.reservedQuantity || 0)" title="查看库存预占流水" arrow @click="openReservedRecordList" />
|
||||
</t-cell-group>
|
||||
<card-container
|
||||
v-if="canOperate && sku?.status === 'ACTIVE' && sku.stockEnabled"
|
||||
@@ -78,14 +97,16 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { shallowRef } from "vue";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import ProductProfile from "@/pages/product/component/ProductProfile.vue";
|
||||
import ProductStockPackageSummary from "@/pages/product/component/ProductStockPackageSummary.vue";
|
||||
import ProductStockOperationPopup from "@/pages/product/ProductStockOperationPopup.vue";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { Product, ProductSku, ProductStock, StockOperationType } from "@/types/Product";
|
||||
import type { Product, ProductSku, ProductStock, ProductSkuUnit, StockOperationType } from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { getProductBaseUnitName, getProductQuantityText } from "@/utils/product";
|
||||
import { convertBaseQuantityToPackageQuantity } from "@/utils/package";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
@@ -103,7 +124,18 @@ const stock = ref<ProductStock>();
|
||||
const isLoading = ref(false);
|
||||
const operationVisible = ref(false);
|
||||
const operationType = ref<ManualStockOperation>("MANUAL_IN");
|
||||
const selectedUnitId = shallowRef("");
|
||||
const canOperate = computed(() => userStore.hasPermissions(permissionCodes.productStock.create));
|
||||
const unitList = computed(() => (sku.value?.unitList || []).filter(unit => !!unit.id));
|
||||
const selectedUnit = computed<ProductSkuUnit | undefined>(() => unitList.value.find(unit => unit.id === selectedUnitId.value)
|
||||
|| unitList.value.find(unit => unit.isBase)
|
||||
|| unitList.value[0]);
|
||||
const selectedUnitName = computed(() => selectedUnit.value?.name || "基础单位");
|
||||
const displayStock = computed(() => ({
|
||||
onHandQuantity: getStockQuantityText(stock.value?.onHandQuantity),
|
||||
availableQuantity: getStockQuantityText(stock.value?.availableQuantity),
|
||||
reservedQuantity: getStockQuantityText(stock.value?.reservedQuantity)
|
||||
}));
|
||||
const operationList: Array<{ text: string; icon: string; type: ManualStockOperation; theme: "primary" | "danger" }> = [
|
||||
{ text: "手工入库", icon: "import", type: "MANUAL_IN", theme: "primary" },
|
||||
{ text: "手工出库", icon: "export", type: "MANUAL_OUT", theme: "danger" },
|
||||
@@ -129,6 +161,24 @@ function getStockTheme(item: ProductStock): "danger" | "success" | "default" {
|
||||
return 0 < min && available < min ? "danger" : "success";
|
||||
}
|
||||
|
||||
function getStockQuantityText(value?: number | string): string {
|
||||
return convertBaseQuantityToPackageQuantity(value ?? "0", selectedUnit.value?.baseQuantityPerUnit ?? "1") || "0";
|
||||
}
|
||||
|
||||
function setDefaultUnit(nextSku: ProductSku): void {
|
||||
const nextUnitList = nextSku.unitList || [];
|
||||
if (selectedUnitId.value && nextUnitList.some(unit => unit.id === selectedUnitId.value)) {
|
||||
return;
|
||||
}
|
||||
selectedUnitId.value = nextUnitList.find(unit => unit.isBase)?.id || nextUnitList[0]?.id || "";
|
||||
}
|
||||
|
||||
function selectUnit(unitId: string): void {
|
||||
if (unitList.value.some(unit => unit.id === unitId)) {
|
||||
selectedUnitId.value = unitId;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAll(): Promise<void> {
|
||||
const skuId = String(route.params.skuId || "");
|
||||
if (!skuId) {
|
||||
@@ -143,6 +193,7 @@ async function loadAll(): Promise<void> {
|
||||
]);
|
||||
product.value = productResult;
|
||||
sku.value = skuResult;
|
||||
setDefaultUnit(skuResult);
|
||||
stock.value = { ...stockResult, sku: skuResult };
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
@@ -150,11 +201,12 @@ async function loadAll(): Promise<void> {
|
||||
}
|
||||
|
||||
async function openRecordList(): Promise<void> {
|
||||
if (product.value?.id) {
|
||||
if (product.value?.id && sku.value?.id) {
|
||||
await router.push({
|
||||
name: "ProductStockRecordList",
|
||||
query: {
|
||||
productId: product.value.id,
|
||||
skuId: sku.value.id,
|
||||
transitionDepth: String(getCurrentRouteDepth() + 1)
|
||||
}
|
||||
});
|
||||
@@ -162,11 +214,12 @@ async function openRecordList(): Promise<void> {
|
||||
}
|
||||
|
||||
async function openReservedRecordList(): Promise<void> {
|
||||
if (product.value?.id) {
|
||||
if (product.value?.id && sku.value?.id) {
|
||||
await router.push({
|
||||
name: "ProductStockRecordList",
|
||||
query: {
|
||||
productId: product.value.id,
|
||||
skuId: sku.value.id,
|
||||
operationType: "ORDER_RESERVE",
|
||||
activeReservationOnly: "true",
|
||||
transitionDepth: String(getCurrentRouteDepth() + 1)
|
||||
@@ -280,6 +333,17 @@ onUnmounted(() => navBarStore.clearRight());
|
||||
}
|
||||
}
|
||||
|
||||
.units {
|
||||
|
||||
.options {
|
||||
--td-button-border-radius: .5rem;
|
||||
|
||||
gap: .5rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
.actions-wrap {
|
||||
|
||||
:deep(.content) {
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
<template>
|
||||
<div v-can="permissionCodes.productStock.read" class="product-stock-list">
|
||||
<div class="search bg-white">
|
||||
<div ref="productStockListRef" v-can="permissionCodes.productStock.read" class="product-stock-list">
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="keyword"
|
||||
class="keyword"
|
||||
type="search"
|
||||
borderless
|
||||
clearable
|
||||
placeholder="搜索产品名称或编码"
|
||||
placeholder="搜索产品名称(拼音)或编码"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<t-pull-down-refresh
|
||||
class="list-wrap empty-cell-title-margin"
|
||||
v-model="isRefreshing"
|
||||
@@ -20,22 +19,23 @@
|
||||
>
|
||||
<t-cell-group v-if="productList.length" theme="card" class="list fix-last-cell-line">
|
||||
<t-cell
|
||||
class="item"
|
||||
v-for="(item, index) in productList"
|
||||
:key="item.productId"
|
||||
:title="item.productName || '未命名产品'"
|
||||
arrow
|
||||
hover
|
||||
class="item"
|
||||
v-entrance-transition="index * 30"
|
||||
@click="toSkuList(item)"
|
||||
>
|
||||
<template #leftIcon>
|
||||
<div class="avatar fallback" v-text="(item.productName || '产').slice(0, 1)" />
|
||||
</template>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<strong v-text="item.productName || '未命名产品'" />
|
||||
<t-tag size="small" variant="outline" :content="item.productCode || '无产品编码'" />
|
||||
</div>
|
||||
<t-image
|
||||
v-if="getProductPhotoURL(item)"
|
||||
:src="getProductPhotoURL(item)"
|
||||
:alt="item.productName || '产品图片'"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
/>
|
||||
<div v-else class="avatar fallback" v-text="(item.productName || '产').slice(0, 1)" />
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="stock">
|
||||
@@ -63,11 +63,13 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import { onBeforeRouteLeave } from "vue-router";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import { useNavBarStore } from "@/store/navBarStore";
|
||||
import type { ProductStockProduct } from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { getProductQuantityText } from "@/utils/product";
|
||||
import { getProductPhotoURL, getProductQuantityText } from "@/utils/product";
|
||||
import { events, isCurrentStoreEvent, listDataEventKeys, type ListDataChangedPayload } from "@/utils/listDataEvents";
|
||||
import { Message } from "@/utils/message";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
|
||||
@@ -75,6 +77,7 @@ defineOptions({ name: "ProductStockList" });
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const productStockListRef = ref<HTMLElement | null>(null);
|
||||
const navBarStore = useNavBarStore();
|
||||
const userStore = useUserStore();
|
||||
const keyword = ref("");
|
||||
@@ -86,6 +89,41 @@ const isRefreshing = ref(false);
|
||||
const isNoMore = ref(false);
|
||||
let keywordTimer: number | undefined;
|
||||
let requestToken = 0;
|
||||
let savedPageScrollTop: number | undefined;
|
||||
let eventRefreshPromise: Promise<void> | undefined;
|
||||
let hasPendingEventRefresh = false;
|
||||
let unregisterProductStockListEvent: (() => void) | undefined;
|
||||
let isDisposed = false;
|
||||
|
||||
function getProductStockListPage(): HTMLElement | null {
|
||||
return productStockListRef.value?.closest<HTMLElement>(".page") || null;
|
||||
}
|
||||
|
||||
function savePageScrollPosition(): void {
|
||||
const page = getProductStockListPage();
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
|
||||
savedPageScrollTop = page.scrollTop;
|
||||
}
|
||||
|
||||
function restorePageScrollPosition(): void {
|
||||
if (savedPageScrollTop === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scrollTop = savedPageScrollTop;
|
||||
requestAnimationFrame(() => {
|
||||
const page = getProductStockListPage();
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
|
||||
page.scrollTop = scrollTop;
|
||||
savedPageScrollTop = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
const emptyText = computed(() => isLoading.value ? "正在加载产品" : keyword.value ? "未找到匹配产品" : "暂无启用库存管理的产品");
|
||||
|
||||
@@ -93,24 +131,57 @@ function getCurrentRouteDepth(): number {
|
||||
return Number(route.meta.depth ?? 0);
|
||||
}
|
||||
|
||||
async function fetch(reset = false): Promise<void> {
|
||||
async function fetch(reset = false, preserveScroll = false): Promise<void> {
|
||||
if (!reset && (isLoading.value || isNoMore.value)) {
|
||||
return;
|
||||
}
|
||||
const loadedPageCount = reset && preserveScroll ? Math.max(pageIndex.value, 1) : 1;
|
||||
const preserveScrollTop = preserveScroll ? getProductStockListPage()?.scrollTop : undefined;
|
||||
if (reset) {
|
||||
pageIndex.value = 0;
|
||||
productList.value = [];
|
||||
total.value = 0;
|
||||
isNoMore.value = false;
|
||||
if (!preserveScroll) {
|
||||
const page = getProductStockListPage();
|
||||
if (page) {
|
||||
page.scrollTop = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
const token = ++requestToken;
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const pageSize = 15;
|
||||
if (reset && preserveScroll) {
|
||||
const nextList: ProductStockProduct[] = [];
|
||||
let nextTotal = 0;
|
||||
let nextPageIndex = 0;
|
||||
for (let index = 0; index < loadedPageCount; index += 1) {
|
||||
const result = await ProductAPI.stockProductList({
|
||||
index,
|
||||
size: pageSize,
|
||||
keyword: keyword.value.trim() || undefined
|
||||
});
|
||||
if (token !== requestToken) {
|
||||
return;
|
||||
}
|
||||
const list = result.list || [];
|
||||
nextList.push(...list);
|
||||
nextTotal = result.total || 0;
|
||||
nextPageIndex += 1;
|
||||
if (list.length < pageSize || nextTotal <= nextList.length) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
productList.value = nextList;
|
||||
total.value = nextTotal;
|
||||
pageIndex.value = nextPageIndex;
|
||||
isNoMore.value = nextList.length < pageSize || nextList.length === nextTotal || nextTotal < nextList.length;
|
||||
} else {
|
||||
const result = await ProductAPI.stockProductList({
|
||||
index: pageIndex.value,
|
||||
size: pageSize,
|
||||
keyword: keyword.value || undefined
|
||||
keyword: keyword.value.trim() || undefined
|
||||
});
|
||||
if (token !== requestToken) {
|
||||
return;
|
||||
@@ -120,6 +191,15 @@ async function fetch(reset = false): Promise<void> {
|
||||
total.value = result.total || 0;
|
||||
pageIndex.value += 1;
|
||||
isNoMore.value = list.length < pageSize || productList.value.length === total.value || total.value < productList.value.length;
|
||||
}
|
||||
if (preserveScrollTop !== undefined) {
|
||||
requestAnimationFrame(() => {
|
||||
const page = getProductStockListPage();
|
||||
if (page) {
|
||||
page.scrollTop = preserveScrollTop;
|
||||
}
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (token === requestToken) {
|
||||
isLoading.value = false;
|
||||
@@ -127,6 +207,32 @@ async function fetch(reset = false): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function startEventRefresh(): void {
|
||||
if (isDisposed) {
|
||||
return;
|
||||
}
|
||||
eventRefreshPromise = fetch(true, true)
|
||||
.catch(error => Message.error(getErrorMessage(error, "产品列表加载失败")))
|
||||
.finally(() => {
|
||||
eventRefreshPromise = undefined;
|
||||
if (!isDisposed && hasPendingEventRefresh) {
|
||||
hasPendingEventRefresh = false;
|
||||
startEventRefresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function requestEventRefresh(payload?: ListDataChangedPayload): void {
|
||||
if (!isCurrentStoreEvent(payload)) {
|
||||
return;
|
||||
}
|
||||
if (eventRefreshPromise) {
|
||||
hasPendingEventRefresh = true;
|
||||
return;
|
||||
}
|
||||
startEventRefresh();
|
||||
}
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
try {
|
||||
await fetch(true);
|
||||
@@ -149,6 +255,14 @@ async function toSkuList(item: ProductStockProduct): Promise<void> {
|
||||
if (!item.productId) {
|
||||
return;
|
||||
}
|
||||
if (item.skuCount === 1 && item.skuId) {
|
||||
await router.push({
|
||||
name: "ProductStockDetail",
|
||||
params: { skuId: item.skuId },
|
||||
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
|
||||
});
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "ProductStockSkuList",
|
||||
params: { productId: item.productId },
|
||||
@@ -157,6 +271,7 @@ async function toSkuList(item: ProductStockProduct): Promise<void> {
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
unregisterProductStockListEvent = events.register(listDataEventKeys.productStockChanged, (payload: ListDataChangedPayload) => requestEventRefresh(payload));
|
||||
navBarStore.clearRight();
|
||||
if (!userStore.hasPermissions(permissionCodes.productStock.read)) {
|
||||
return;
|
||||
@@ -168,6 +283,14 @@ onMounted(async () => {
|
||||
}
|
||||
});
|
||||
|
||||
onActivated(() => {
|
||||
restorePageScrollPosition();
|
||||
});
|
||||
|
||||
onDeactivated(() => {
|
||||
savePageScrollPosition();
|
||||
});
|
||||
|
||||
watch(keyword, () => {
|
||||
window.clearTimeout(keywordTimer);
|
||||
keywordTimer = window.setTimeout(async () => {
|
||||
@@ -179,7 +302,15 @@ watch(keyword, () => {
|
||||
}, 300);
|
||||
});
|
||||
|
||||
onBeforeRouteLeave(() => {
|
||||
savePageScrollPosition();
|
||||
navBarStore.clearRight();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
isDisposed = true;
|
||||
unregisterProductStockListEvent?.();
|
||||
unregisterProductStockListEvent = undefined;
|
||||
navBarStore.clearRight();
|
||||
window.clearTimeout(keywordTimer);
|
||||
requestToken += 1;
|
||||
@@ -190,18 +321,15 @@ onUnmounted(() => {
|
||||
.product-stock-list {
|
||||
padding: var(--app-nav-height) 0 1rem;
|
||||
|
||||
.search {
|
||||
.filters {
|
||||
top: var(--app-nav-height);
|
||||
z-index: 10;
|
||||
padding: .75rem 1rem;
|
||||
position: sticky;
|
||||
background: var(--td-bg-color-page);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
|
||||
.keyword {
|
||||
border: 1px solid var(--td-component-border);
|
||||
padding: .5rem 1rem;
|
||||
background: var(--td-bg-color-container);
|
||||
border-radius: 1rem;
|
||||
}
|
||||
}
|
||||
@@ -210,7 +338,6 @@ onUnmounted(() => {
|
||||
min-height: 70vh;
|
||||
|
||||
.list {
|
||||
padding-top: .75rem;
|
||||
|
||||
.item {
|
||||
padding: 10px;
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
</div>
|
||||
</t-form-item>
|
||||
<t-form-item label-width="0">
|
||||
<photo-scroller
|
||||
<media-selector
|
||||
:model-value="photoUrlList"
|
||||
v-model:photo-items="photoItems"
|
||||
:upload="uploadPhotoList"
|
||||
@@ -99,7 +99,7 @@ import { watch } from "vue";
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { Time } from "timi-web";
|
||||
import ProductAPI from "@/api/ProductAPI";
|
||||
import PhotoScroller from "@/components/PhotoScroller.vue";
|
||||
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
|
||||
import type {
|
||||
Product,
|
||||
ProductSku,
|
||||
@@ -108,6 +108,7 @@ import type {
|
||||
StockOperationType
|
||||
} from "@/types/Product";
|
||||
import { getErrorMessage } from "@/utils/error";
|
||||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||||
import { createProductRequestNo, getStockOperationText } from "@/utils/product";
|
||||
import { Message } from "@/utils/message";
|
||||
import type { PhotoItem } from "@/types/Photo";
|
||||
@@ -260,6 +261,7 @@ async function submit(): Promise<void> {
|
||||
break;
|
||||
}
|
||||
visible.value = false;
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged, props.product.id);
|
||||
Message.success("库存操作已提交");
|
||||
emit("success");
|
||||
} catch (error) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user