rename notify

This commit is contained in:
Timi
2026-08-28 11:51:52 +08:00
parent bbca267242
commit acddc71430
9 changed files with 1154 additions and 1168 deletions
+433
View File
@@ -0,0 +1,433 @@
<template>
<div v-can="corePermissionCodes.notify.create" class="notify-management-create">
<t-empty v-if="!canCreate" description="暂无发送通知权限" />
<t-form v-else class="form" label-align="left" label-width="5rem">
<t-form-item label="通知标题" required-mark>
<t-input
v-model.trim="subject"
borderless
maxlength="100"
placeholder="请输入通知标题"
/>
</t-form-item>
<t-form-item
label="接收用户"
:description="selectedRecipientDescription"
required-mark
arrow
@click="openRecipientPicker"
/>
<t-form-item label="发送时间" arrow @click="openSchedulePicker">
<div class="schedule-value">
<span v-text="scheduleAtText || '立即发送'" />
<t-button
v-if="scheduleAtText"
size="extra-small"
content="立即发送"
@click.stop="clearSchedule"
/>
</div>
</t-form-item>
<section class="editor-wrapper">
<notify-editor
ref="notifyEditorRef"
class="editor"
v-model="draftDetail"
placeholder="请输入通知内容"
:upload-image="uploadImage"
:upload-video="uploadVideo"
/>
</section>
</t-form>
</div>
<notify-recipient-picker
v-model="selectedUserIdList"
v-model:visible="recipientPickerVisible"
:users="recipientList"
:stores="storeScopeOptions"
:self-user="selfRecipient"
:loading="isRecipientLoading"
/>
<t-popup v-model="schedulePickerVisible" placement="bottom">
<t-date-time-picker
v-model="scheduleDraftText"
:start="minimumScheduleText"
:mode="['date', 'minute']"
format="YYYY-MM-DD HH:mm"
title="选择发送时间"
@cancel="schedulePickerVisible = false"
@confirm="confirmSchedule"
/>
</t-popup>
</template>
<script setup lang="ts">
import { NotifyEditor, type NotifyEditorExpose } from "timi-tdesign-mobile";
import { Time } from "timi-web";
import { AttachmentAPI, type Attachment as ApiAttachment, type NotifyContentType, type NotifyDetail, useUserStore } from "timi-web-api";
import { Message } from "@/utils/message";
import { getErrorMessage } from "@/utils/error";
import GaoNotifyAPI from "@/api/GaoNotifyAPI";
import type { ManagedUser } from "@/types/ManagedUser";
import NotifyRecipientPicker, { type NotifyRecipientScopeOption } from "@/pages/notify/component/NotifyRecipientPicker.vue";
import { corePermissionCodes, coreRoleCodes, gaoRoleCodes, permissionCodes } from "@/utils/permission";
import { useNavBarStore } from "@/store/navBarStore";
import { useCurrentStoreStore } from "@/store/currentStoreStore";
defineOptions({
name: "NotifyCreate"
});
const router = useRouter();
const navBarStore = useNavBarStore();
const userStore = useUserStore();
const currentStoreStore = useCurrentStoreStore();
const notifyEditorRef = ref<NotifyEditorExpose>();
const isGlobalScope = computed(() => userStore.hasRoles([coreRoleCodes.admin, gaoRoleCodes.globalManager], "or"));
const canReadRecipients = computed(() => userStore.hasPermissions([permissionCodes.user.read, permissionCodes.store.read], "or"));
const canCreate = computed(() => userStore.hasPermissions(corePermissionCodes.notify.create) && canReadRecipients.value);
// ---------- 通知表单 ----------
const subject = ref("");
const draftDetail = ref<NotifyDetail>({
contentType: "TIP_TAP",
content: "",
attachmentList: []
});
const selectedUserIdList = ref<string[]>([]);
const isSaving = ref(false);
async function uploadMedia(file: File): Promise<{ id: string; url: string; name: string }> {
const [tempFile] = await AttachmentAPI.upload(file);
if (!tempFile?.id) {
throw new Error("媒体上传失败");
}
return {
id: tempFile.id,
url: AttachmentAPI.getTempReadURL(tempFile.id),
name: file.name
};
}
async function uploadImage(file: File) {
return await uploadMedia(file);
}
async function uploadVideo(file: File) {
return await uploadMedia(file);
}
// ---------- 接收用户 ----------
const isRecipientLoading = ref(false);
const recipientList = ref<ManagedUser[]>([]);
const recipientPickerVisible = ref(false);
const recipientStoreId = ref("");
const loginUserId = computed(() => userStore.loginUser.user?.id || userStore.loginUser.id || "");
const selfRecipient = computed<ManagedUser | undefined>(() => {
if (!loginUserId.value) {
return undefined;
}
const user = userStore.loginUser.user;
return {
userId: loginUserId.value,
user: user ? {
id: user.id,
name: user.name,
nick: user.nick,
phoneNo: user.phoneNo,
attachmentList: user.attachmentList as unknown as ApiAttachment[]
} : undefined
};
});
const storeScopeOptions = computed<NotifyRecipientScopeOption[]>(() => {
const storeList = currentStoreStore.storeList.length
? currentStoreStore.storeList
: currentStoreStore.currentStore
? [currentStoreStore.currentStore]
: [];
return storeList
.map(item => ({
label: item.name || item.code || "未命名门店",
value: item.id || ""
}))
.filter(item => item.value);
});
const availableRecipientList = computed(() => {
const selfUserId = selfRecipient.value?.userId;
const userList = selfUserId
? recipientList.value.filter(item => item.userId !== selfUserId)
: recipientList.value;
return selfRecipient.value ? [selfRecipient.value, ...userList] : userList;
});
const selectedRecipientDescription = computed(() => {
if (!selectedUserIdList.value.length) {
return "请选择接收用户";
}
const recipientMap = new Map(availableRecipientList.value.map(item => [item.userId, item]));
return selectedUserIdList.value
.map(userId => getRecipientName(recipientMap.get(userId) || { userId }))
.join("、");
});
// ---------- 定时发送 ----------
const schedulePickerVisible = ref(false);
const scheduleAtText = ref("");
const scheduleDraftText = ref("");
const minimumScheduleText = computed(() => Time.formatDateTime(new Date(Time.now() + Time.M)));
function getContentText(content: string): string {
const parser = new DOMParser();
return parser.parseFromString(content, "text/html").body.textContent?.trim() || "";
}
function hasMediaContent(content: string): boolean {
const parser = new DOMParser();
const doc = parser.parseFromString(content, "text/html");
return Boolean(doc.querySelector("img, video"));
}
function getScheduleTimestamp(): number | undefined {
if (!scheduleAtText.value) {
return undefined;
}
const timestamp = new Date(scheduleAtText.value.replace(" ", "T")).getTime();
return Number.isNaN(timestamp) ? undefined : timestamp;
}
function validateForm(): boolean {
if (!subject.value.trim()) {
Message.warning("请输入通知标题");
return false;
}
if (!selectedUserIdList.value.length) {
Message.warning("请选择至少一位接收用户");
return false;
}
const content = draftDetail.value.content || "";
if (!getContentText(content) && !hasMediaContent(content)) {
Message.warning("请输入通知内容");
return false;
}
const scheduleAt = getScheduleTimestamp();
if (scheduleAtText.value && (!scheduleAt || scheduleAt < Time.now())) {
Message.warning("定时发送时间必须晚于当前时间");
return false;
}
return true;
}
async function saveNotification(): Promise<void> {
if (isSaving.value || !validateForm()) {
return;
}
isSaving.value = true;
try {
const editorValue = await notifyEditorRef.value?.submit();
const detailValue = editorValue || draftDetail.value;
const sendAt = getScheduleTimestamp();
const contentType: NotifyContentType = detailValue.contentType === "TEXT" ? "TEXT" : "TIP_TAP";
const detailList: NotifyDetail[] = selectedUserIdList.value.map(sendTo => ({
msgType: "INTERNAL",
subject: subject.value.trim(),
content: detailValue.content || "",
contentType,
attachmentList: (detailValue.attachmentList || []) as unknown as ApiAttachment[],
sendTo,
...(sendAt ? { sendAt } : {})
}));
const result = await GaoNotifyAPI.create({ detailList });
Message.success(sendAt ? "定时通知已创建" : "通知已发送");
if (result.id) {
await router.replace({
name: "NotifyDetail",
params: { id: result.id }
});
return;
}
await router.replace({ name: "NotifyList" });
} catch (error) {
Message.error(getErrorMessage(error, "通知保存失败"));
} finally {
isSaving.value = false;
}
}
// ---------- 定时发送 ----------
function openSchedulePicker(): void {
scheduleDraftText.value = scheduleAtText.value || Time.formatDateTime(new Date(Time.now() + Time.M));
schedulePickerVisible.value = true;
}
function confirmSchedule(): void {
const timestamp = new Date(scheduleDraftText.value.replace(" ", "T")).getTime();
if (Number.isNaN(timestamp) || timestamp < Time.now()) {
Message.warning("定时发送时间必须晚于当前时间");
return;
}
scheduleAtText.value = scheduleDraftText.value;
schedulePickerVisible.value = false;
}
function clearSchedule(): void {
scheduleAtText.value = "";
scheduleDraftText.value = "";
}
// ---------- 接收用户选择 ----------
function openRecipientPicker(): void {
recipientPickerVisible.value = true;
}
function getRecipientName(item: ManagedUser): string {
if (item.userId === selfRecipient.value?.userId) {
return `自己(${item.user?.nick || item.user?.name || "当前账号"})`;
}
return item.user?.nick || item.user?.name || item.userId || "未命名用户";
}
// ---------- 接收用户 ----------
async function loadRecipients(): Promise<void> {
if (isRecipientLoading.value) {
return;
}
isRecipientLoading.value = true;
try {
const pageSize = 100;
const list: ManagedUser[] = [];
let pageIndex = 0;
let total = 0;
const storeId = recipientStoreId.value || undefined;
while (true) {
const result = await GaoNotifyAPI.listRecipients(
{ index: pageIndex, size: pageSize },
storeId ? { storeId } : undefined
);
const currentList = result.list || [];
list.push(...currentList);
total = result.total || 0;
pageIndex += 1;
if (!currentList.length || list.length >= total || currentList.length < pageSize) {
break;
}
}
const userMap = new Map<string, ManagedUser>();
for (const item of list) {
const userId = item.userId || item.user?.id;
if (userId && userId !== loginUserId.value) {
userMap.set(userId, { ...item, userId });
}
}
recipientList.value = Array.from(userMap.values());
} catch (error) {
Message.error(getErrorMessage(error, "接收用户加载失败"));
} finally {
isRecipientLoading.value = false;
}
}
// ---------- 生命周期 ----------
onMounted(async () => {
navBarStore.clearRight();
if (!canCreate.value) {
return;
}
if (isGlobalScope.value) {
await currentStoreStore.loadStoreList();
} else {
const loginStore = await currentStoreStore.loadLoginStore();
recipientStoreId.value = loginStore?.id || currentStoreStore.currentStoreId || "";
}
navBarStore.setRightText("发送", "var(--td-brand-color)", saveNotification);
await loadRecipients();
});
onUnmounted(() => navBarStore.clearRight());
</script>
<style scoped lang="less">
.notify-management-create {
min-height: 100%;
padding-top: var(--app-nav-height);
.form {
margin: 0;
display: grid;
.schedule-value {
gap: .5rem;
width: 100%;
display: flex;
align-items: center;
justify-content: flex-end;
}
.editor-wrapper {
width: 100%;
min-width: 0;
max-width: 100%;
overflow: visible;
.editor {
width: 100%;
min-width: 0;
max-width: 100%;
border: none;
border-radius: 0;
}
:deep(.tp-editor) {
width: 100%;
min-width: 0;
max-width: 100%;
height: auto;
overflow: visible;
}
:deep(.content) {
overflow: visible;
}
:deep(.toolbar) {
width: 100%;
min-width: 0;
max-width: 100%;
top: var(--app-nav-height);
z-index: 10;
position: sticky;
}
:deep(.toolbar .scroll) {
width: 100%;
min-width: 0;
max-width: 100%;
}
}
.tip {
color: #64748b;
margin: 0 1rem;
font-size: .8125rem;
line-height: 1.5;
}
}
}
:global(html.theme-dark) {
.notify-management-create {
.tip {
color: #94a3b8;
}
}
}
</style>