Files
gao-customer-h5/src/pages/home/QuickSignInPage.vue
T
2026-10-21 16:24:00 +08:00

604 lines
17 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()"
/>
<div v-can="permissionCodes.eventRecord.create" class="quick-sign-in-page">
<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>
<center-tips v-else-if="isEventLoading">正在加载登记事件</center-tips>
<center-tips v-else>登记事件加载失败</center-tips>
<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"
:status-text="scanStatus"
active-text="请将客户二维码移入取景框"
@decode="handleDecodedText"
@status-change="handleScanStatusChange"
/>
</div>
<t-button
class="cell-button"
theme="primary"
:disabled="!canSubmitRegister"
:loading="submitting"
v-entrance-transition
@click="doSubmit()"
>登记</t-button>
<customer-profile-card
v-if="matchedCustomer"
class="content-margin"
:customer="matchedCustomer"
/>
<t-form
v-if="selectedNumberEventList.length"
class="input-form"
label-align="left"
label-width="8rem"
>
<t-form-item
v-for="item in selectedNumberEventList"
:key="item.id"
:label="`${item.name || '未命名事件'}数值`"
:required-mark="item.requireValue === true"
>
<t-input
v-model.trim="numberValueTextMap[item.id || '']"
type="number"
align="right"
borderless
:placeholder="getNumberValuePlaceholder(item)"
/>
</t-form-item>
</t-form>
<div v-if="showRecordPhotoInput" class="input-form photo-form content-margin">
<attachment-selector
title="登记事件照片"
:required="selectedRequiredPhotoEventList.length > 0"
v-model:items="recordPhotoItemList"
:busy="recordPhotoUploading"
@select="handleRecordPhotoSelected($event.files)"
/>
</div>
<t-cell-group
v-if="recentRecordList.length"
title="最近登记记录"
theme="card"
>
<t-cell
v-for="item in recentRecordList"
:key="item.id"
:title="item.event?.name || '未知事件'"
:description="Time.toDateTime(item.registeredAt)"
:note="item.remark || '无备注'"
arrow
hover
@click="toRecordDetail(item.id || '')"
>
<template #leftIcon>
<t-image
v-if="getEventRecordPhotoURL(item, 64)"
:src="getEventRecordPhotoURL(item, 64)"
:alt="item.event?.name || '未知事件'"
fit="cover"
class="record-photo"
/>
</template>
</t-cell>
</t-cell-group>
</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"
/>
<center-tips v-else-if="isEventLoading">正在加载登记事件</center-tips>
<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">
import { Message } from "@/utils/message";
import CustomerAPI from "@/api/CustomerAPI";
import EventAPI from "@/api/EventAPI";
import EventRecordAPI from "@/api/EventRecordAPI";
import CodeScanner from "@/components/CodeScanner.vue";
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
import EventOptionSelector from "@/components/EventOptionSelector.vue";
import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue";
import { useSettingStore } from "@/store/settingStore";
import type { Customer } from "@/types/Customer";
import type { EventItem, EventOptionSelectionMap } from "@/types/EventItem";
import type { EventRecord } from "@/types/EventRecord";
import type { PhotoItem } from "@/types/Photo";
import { getEventNumberValuePlaceholder, resolveEventNumberValue } from "@/utils/eventValue";
import { isRetiredEvent } from "@/utils/event";
import { resolveSelectedOptionGroupList, validateEventOptionSelection } from "@/utils/eventOption";
import { permissionCodes } from "@/utils/permission";
import { getEventRecordPhotoURL, hasPhotoAttachment } from "@/utils/eventRecord";
import { compressUploadImageList } from "@/utils/imageCompression";
import { Storage, Time } from "timi-web";
import { type Attachment, AttachmentAPI } from "timi-web-api";
import EventSelector from "@/components/EventSelector.vue";
import { BottomPopup } from "timi-tdesign-mobile";
defineOptions({
name: "QuickSignInPage"
});
const router = useRouter();
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));
function normalizeEventId(item?: EventItem): string {
if (!item || item.id === undefined || item.id === null) {
return "";
}
return String(item.id);
}
async function loadActions(): Promise<void> {
if (isEventLoading.value) {
return;
}
isEventLoading.value = true;
eventLoadFailed.value = false;
try {
eventList.value = (await EventAPI.listValid()).filter(item => !isRetiredEvent(item));
selectedEventIdList.value = buildInitialSelectedEventIdList();
syncStoredEventId();
} catch (error) {
console.warn("登记事件加载失败", error);
eventLoadFailed.value = true;
eventList.value = [];
selectedEventIdList.value = [];
Message.error("登记事件加载失败");
} finally {
isEventLoading.value = false;
}
}
function buildInitialSelectedEventIdList(): string[] {
const selectedIdList = normalizeSelectedEventIdList(selectedEventIdList.value);
if (selectedIdList.length) {
return selectedIdList;
}
const storedEventId = Storage.getString(EventItemStorageKey);
const storedAction = eventList.value.find(item => normalizeEventId(item) === storedEventId);
const defaultEventId = normalizeEventId(storedAction || eventList.value[0]);
return defaultEventId ? [defaultEventId] : [];
}
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)).slice(0, 1);
}
async function handleEventSelectionChange(eventIdList: string[]): Promise<void> {
selectedEventIdList.value = normalizeSelectedEventIdList(eventIdList);
syncStoredEventId();
eventPopupVisible.value = false;
}
function resolveRecordOptionGroupList(eventId: string) {
const event = eventList.value.find(item => normalizeEventId(item) === eventId);
return event ? resolveSelectedOptionGroupList(event, selectedOptionSelectionMap) : [];
}
function validateEventOptionSelectionList(): boolean {
for (const eventId of selectedEventIdList.value) {
const event = eventList.value.find(item => normalizeEventId(item) === eventId);
if (!event) {
continue;
}
const optionError = validateEventOptionSelection(event, selectedOptionSelectionMap);
if (optionError) {
Message.warning(optionError);
return false;
}
}
return true;
}
function syncStoredEventId(): void {
const firstEventId = selectedEventIdList.value[0];
if (firstEventId) {
Storage.setString(EventItemStorageKey, firstEventId);
}
}
onMounted(loadActions);
// ---------- 扫码 ----------
const scanCode = ref("");
const scanStatus = ref("正在启动扫码预览");
const scannerSessionKey = ref(0);
const matchedCustomer = ref<Customer>();
const registeredCustomerIdSetByEvent = new Map<string, Set<string>>();
let latestDecodedText = "";
function isCustomerRegisteredForEvents(eventIdList: string[], customerId: string): boolean {
return eventIdList.some(eventId => registeredCustomerIdSetByEvent.get(eventId)?.has(customerId));
}
function markCustomerRegisteredForEvents(eventIdList: string[], customerId: string): void {
for (const eventId of eventIdList) {
const customerIdSet = registeredCustomerIdSetByEvent.get(eventId) || new Set<string>();
customerIdSet.add(customerId);
registeredCustomerIdSetByEvent.set(eventId, customerIdSet);
}
}
async function handleDecodedText(rawText: string): Promise<void> {
const normalizedText = rawText.trim();
if (!normalizedText || normalizedText === latestDecodedText) {
return;
}
latestDecodedText = normalizedText;
scanCode.value = normalizedText;
await settingStore.playScanSuccessSound();
await loadCustomer(normalizedText);
const customer = matchedCustomer.value;
if (customer) {
if (customer.id && isCustomerRegisteredForEvents(selectedEventIdList.value, customer.id)) {
scanStatus.value = `客户 ${customer.name || customer.code || normalizedText} 已在本页面登记`;
return;
}
scanStatus.value = `已识别 ${normalizedText},可直接登记`;
if (autoRegisterEnabled.value) {
await doSubmit(true);
}
return;
}
scanStatus.value = `已识别 ${normalizedText},但未匹配客户档案`;
}
function handleScanStatusChange(value: string): void {
scanStatus.value = value;
}
// ---------- 读取客户 ----------
const recentRecordList = ref<EventRecord[]>([]);
async function loadCustomer(code: string): Promise<void> {
const customer = await CustomerAPI.findByCode(code);
if (!customer) {
matchedCustomer.value = undefined;
recentRecordList.value = [];
return;
}
matchedCustomer.value = customer;
recentRecordList.value = (await EventRecordAPI.list({
index: 0,
size: 5,
customerId: matchedCustomer.value.id!
})).list;
}
async function toRecordDetail(id: string): Promise<void> {
if (!id) {
return;
}
await router.push(`/management/registration-event-records/${id}`);
}
// ---------- 表单 ----------
const submitting = ref(false);
const numberValueTextMap = reactive<Record<string, string>>({});
const canSubmitRegister = computed(() => !!matchedCustomer.value && !!selectedEventIdList.value.length);
function getNumberValuePlaceholder(event: EventItem): string {
return getEventNumberValuePlaceholder(event);
}
function resolveNumberValue(eventId: string): number | undefined {
const valueText = numberValueTextMap[eventId] || "";
if (!valueText.trim()) {
return undefined;
}
const event = eventList.value.find(item => normalizeEventId(item) === eventId);
return event ? resolveEventNumberValue(event, valueText) : undefined;
}
function validateNumberValueList(): boolean {
for (const eventId of selectedEventIdList.value) {
const event = eventList.value.find(item => item.id === eventId);
if (!event) {
continue;
}
const valueText = numberValueTextMap[eventId] || "";
if (event.valueType !== "NUMBER") {
if (valueText.trim()) {
Message.warning(`${event.name || "当前事件"}不能提交数值`);
return false;
}
continue;
}
const numberValue = resolveNumberValue(eventId);
if (valueText.trim() && numberValue === undefined) {
Message.warning(`${event.name || "当前事件"}数值格式不正确,请检查单位和小数位`);
return false;
}
if (event.requireValue && numberValue === undefined) {
Message.warning(`请填写${event.name || "当前事件"}数值`);
return false;
}
}
return true;
}
// ---------- 照片 ----------
const recordPhotoItemList = ref<PhotoItem[]>([]);
const recordPhotoUploading = ref(false);
const showRecordPhotoInput = computed(() => selectedRequiredPhotoEventList.value.length > 0 || recordPhotoItemList.value.length > 0);
async function handleRecordPhotoSelected(fileList: File[]): Promise<void> {
if (!fileList.length) {
return;
}
recordPhotoUploading.value = true;
try {
const compressedFileList = await compressUploadImageList(fileList);
const tempFileList = await AttachmentAPI.upload(compressedFileList);
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)
});
}
} finally {
recordPhotoUploading.value = false;
}
}
function validateRequiredPhotoList(): boolean {
const event = selectedRequiredPhotoEventList.value[0];
if (event && !hasPhotoAttachment(recordPhotoItemList.value)) {
Message.warning(`请上传${event.name || "当前事件"}照片`);
return false;
}
return true;
}
function buildPhotoAttachmentList(): Array<Partial<Attachment>> {
return recordPhotoItemList.value.map(item => ({
tempFileId: item.tempFileId,
attachType: item.attachType || "PHOTO"
}));
}
async function doSubmit(isAutoRegister = false): Promise<void> {
const customer = matchedCustomer.value;
if (!customer) {
return;
}
const customerId = customer.id;
if (!customerId) {
return;
}
const eventIdList = [...selectedEventIdList.value];
if (!eventIdList.length) {
Message.warning("请至少选择一个登记事件");
return;
}
if (isCustomerRegisteredForEvents(eventIdList, customerId)) {
Message.warning("该客户已在本页面登记,请勿重复登记");
return;
}
if (recordPhotoUploading.value) {
Message.warning("照片正在上传,请稍候");
return;
}
if (!validateRequiredPhotoList()) {
return;
}
if (!validateEventOptionSelectionList()) {
return;
}
if (!validateNumberValueList()) {
return;
}
submitting.value = true;
try {
await EventRecordAPI.createBatch(eventIdList.map(eventId => ({
eventId,
customerId,
selectedOptionGroupList: resolveRecordOptionGroupList(eventId),
numberValue: resolveNumberValue(eventId),
remark: "客户快速扫码登记",
attachmentList: buildPhotoAttachmentList()
})));
markCustomerRegisteredForEvents(eventIdList, 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;
await settingStore.playRegisterSuccessSound();
} finally {
submitting.value = false;
}
}
</script>
<style scoped lang="less">
.quick-sign-in-page {
gap: 1rem;
padding: calc(var(--app-nav-height) + 1rem) 0 1rem 0;
display: flex;
flex-direction: column;
.input-form {
padding: .5rem 0;
background: rgba(255, 255, 255, .94);
box-shadow: 0 .75rem 2rem rgba(15, 23, 42, .08);
border-radius: .875rem;
&.photo-form {
padding: 1rem;
}
.form-text {
color: #0f172a;
display: block;
text-align: right;
}
}
.file-input {
display: none;
}
.code-box {
padding: .875rem;
background: #f7faff;
border: 1px solid rgba(148, 163, 184, .2);
border-radius: 1rem;
}
.required-label::before {
color: #e34d59;
content: "*";
margin-right: .25rem;
}
.code-box {
display: grid;
margin-top: .875rem;
gap: .375rem;
span {
color: #52607a;
font-size: .8125rem;
}
strong {
font-size: 1.125rem;
line-height: 1.5;
word-break: break-all;
}
}
.record-photo {
width: 3.5rem;
height: 3.5rem;
border-radius: .875rem;
}
}
.event-popup {
padding: 1rem;
}
:global(html.theme-dark) {
.quick-sign-in-page {
.panel,
.bottom-bar,
.event-panel,
.input-form {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
}
.input-form .form-text {
color: #e2e8f0;
}
.code-box {
background: rgba(30, 41, 59, .9);
border-color: rgba(148, 163, 184, .16);
}
.code-box span {
color: #94a3b8;
}
}
}
</style>