Files
gao-customer-h5/src/pages/notify/NotifyCreate.vue
T
2026-10-22 17:58:35 +08:00

466 lines
12 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<t-navbar
fixed
:z-index="20"
title="发送通知"
left-arrow
@left-click="$router.back()"
>
<template #right>
<t-button
@click="saveNotification"
theme="primary"
variant="text"
size="small"
:content="scheduleAtText ? '提交' : '发送'"
/>
</template>
</t-navbar>
<div v-can="corePermissionCodes.notify.create" class="notify-management-create">
<t-empty v-if="!canCreate" description="暂无发送通知权限" />
<t-form v-else class="form card" label-width="5rem">
<t-form-item label="通知标题" required-mark>
<t-input
v-model="subject"
borderless
maxlength="100"
placeholder="请输入通知标题"
/>
</t-form-item>
<t-form-item
class="recipient-item"
label="接收用户"
required-mark
arrow
@click="openRecipientPicker"
content-align="right"
>
<span class="value clip-text" v-text="selectedRecipientDescription" />
</t-form-item>
<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 {
type Attachment as ApiAttachment,
AttachmentAPI,
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 { useCurrentStoreStore } from "@/store/currentStoreStore";
defineOptions({
name: "NotifyCreate"
});
const router = useRouter();
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.toDateTime(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.toDateTime(new Date(Time.now() + Time.M));
schedulePickerVisible.value = true;
}
function confirmSchedule(value?: string | number): void {
const scheduleText = String(value ?? scheduleDraftText.value);
const timestamp = new Date(scheduleText.replace(" ", "T")).getTime();
if (Number.isNaN(timestamp) || timestamp < Time.now()) {
Message.warning("定时发送时间必须晚于当前时间");
return;
}
scheduleAtText.value = scheduleText;
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 () => {
if (!canCreate.value) {
return;
}
if (isGlobalScope.value) {
await currentStoreStore.loadStoreList();
} else {
const loginStore = await currentStoreStore.loadLoginStore();
recipientStoreId.value = loginStore?.id || currentStoreStore.currentStoreId || "";
}
await loadRecipients();
});
</script>
<style scoped lang="less">
.notify-management-create {
min-height: 100%;
padding-top: var(--app-nav-height);
.form {
margin: 0;
border-radius: 0;
.recipient-item {
.value {
max-width: 12rem;
text-align: right;
}
}
.schedule-value {
--td-button-extra-small-height: 24px;
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) {
padding: 0;
overflow: visible;
.value {
border-radius: 0;
}
}
: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%;
}
}
}
}
</style>