add point redemption

This commit is contained in:
Timi
2026-09-15 10:44:29 +08:00
parent f7d144e440
commit 8a0f5b6775
11 changed files with 1752 additions and 9 deletions
+363
View File
@@ -0,0 +1,363 @@
<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 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>
<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">
<photo-scroller
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="`${item.sku?.specSummary || item.sku?.code || '默认 SKU'} · ${item.unit?.name || ''} · ${formatPoint(item.defaultPointCost)} / 单位`"
arrow
@click="selectSku(item)"
/>
<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 PhotoScroller from "@/components/PhotoScroller.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 { normalizePackageQuantity } from "@/utils/package";
import { 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 ? "正在加载" : `${(pointAccount.value?.balance ?? 0).toLocaleString("zh-CN")} 分`;
});
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 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 `${(value || 0).toLocaleString("zh-CN")} 分`;
}
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;
}
:global(html.theme-dark) {
.redemption-create {
.form {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
}
}
}
</style>