932 lines
30 KiB
Vue
932 lines
30 KiB
Vue
<template>
|
||
<div class="tui-page-layout tui-navbar recycle-exchange-create">
|
||
<t-navbar
|
||
fixed
|
||
:z-index="20"
|
||
title="创建回收兑换订单"
|
||
left-arrow
|
||
@left-click="exit"
|
||
>
|
||
<template #right>
|
||
<t-button
|
||
:loading="saving"
|
||
theme="primary"
|
||
variant="text"
|
||
size="small"
|
||
content="提交"
|
||
@click="save"
|
||
/>
|
||
</template>
|
||
</t-navbar>
|
||
<main class="tui-page-content scroll column" v-can="permissionCodes.salesOrder.create">
|
||
<t-form class="form card" label-width="7rem" v-entrance-transition>
|
||
<t-form-item label-width="0">
|
||
<span>兑换单会生成一张交易订单,商品按订单履约分批领取。回收物支付独立核销,不产生资金流水,也不支持与现金混付。</span>
|
||
</t-form-item>
|
||
<t-form-item label="兑换模板" arrow content-align="right" @click="openRulePicker">
|
||
<div class="template">
|
||
<span v-text="ruleDisplayText" />
|
||
<t-button v-if="selectedRule" size="extra-small" content="清除" @click.stop="clearRule" />
|
||
</div>
|
||
</t-form-item>
|
||
</t-form>
|
||
<t-form class="form card" label-width="7rem" v-entrance-transition>
|
||
<t-form-item label="客户" required-mark arrow content-align="right" @click="customerVisible = true">
|
||
<span v-text="customerName || '请选择'" />
|
||
</t-form-item>
|
||
<customer-profile-card v-if="customer" class="customer-profile" :customer="customer" />
|
||
<t-form-item v-if="canAdjust" label="回收物" arrow content-align="right" @click="itemPickerVisible = true">
|
||
<span v-text="recycleItemName || '请选择'" />
|
||
</t-form-item>
|
||
<t-form-item label="回收数量" required-mark content-align="right">
|
||
<div class="quantity">
|
||
<t-stepper
|
||
:model-value="Number(recycleQuantityText) || 0"
|
||
size="large"
|
||
theme="outline"
|
||
:min="0"
|
||
:max="Number.MAX_SAFE_INTEGER"
|
||
:step="selectedRecycleItem?.allowDecimalQuantity ? .05 : 1"
|
||
:integer="!selectedRecycleItem?.allowDecimalQuantity"
|
||
:disabled="!canAdjust"
|
||
@update:model-value="recycleQuantityText = String($event)"
|
||
/>
|
||
<t-tag :content="recycleUnitName || '单位'" />
|
||
</div>
|
||
</t-form-item>
|
||
<t-form-item
|
||
v-if="customerId && recycleItemId"
|
||
label="客户回收物数量"
|
||
label-width="9rem"
|
||
content-align="right"
|
||
>
|
||
<span :class="customerRecycleClass" v-text="customerRecycleText" />
|
||
</t-form-item>
|
||
<t-form-item v-if="selectedRule" label="兑换份数" required-mark content-align="right">
|
||
<t-stepper v-model="multiple" size="large" :min="1" :max="9999" :step="1" integer theme="outline" />
|
||
</t-form-item>
|
||
<t-form-item v-if="itemRows.length" class="detail" label-width="0">
|
||
<t-form class="items" label-width="0">
|
||
<t-form-item v-for="(row, index) in itemRows" :key="row.key" class="item">
|
||
<div class="item-content">
|
||
<div class="photo">
|
||
<t-image
|
||
v-if="skuMap[row.skuId] && getProductPhotoURL(skuMap[row.skuId])"
|
||
:src="getProductPhotoURL(skuMap[row.skuId])"
|
||
:alt="row.productName || '产品图片'"
|
||
fit="cover"
|
||
class="avatar"
|
||
/>
|
||
<div v-else class="avatar fallback" v-text="(row.productName || '产').slice(0, 1)" />
|
||
</div>
|
||
<div class="main">
|
||
<div class="head">
|
||
<div class="title">
|
||
<strong class="name clip-text" v-text="row.productName || '未命名产品'" />
|
||
<product-sku-tags :product-name="row.productName" :fallback="row.skuText" />
|
||
</div>
|
||
<t-button v-if="editableItems" size="extra-small" theme="danger" variant="text" content="移除" @click="removeItem(index)" />
|
||
</div>
|
||
<div class="quantity">
|
||
<t-stepper
|
||
:model-value="Number(row.quantityText) || 0"
|
||
size="large"
|
||
theme="outline"
|
||
:min="0"
|
||
:max="Number.MAX_SAFE_INTEGER"
|
||
:step="getProductQuantityStep({ allowDecimalQuantity: row.allowDecimalQuantity })"
|
||
:integer="!row.allowDecimalQuantity"
|
||
:disabled="!editableItems"
|
||
@update:model-value="row.quantityText = String($event)"
|
||
/>
|
||
<t-tag :content="row.unitName || '单位'" />
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</t-form-item>
|
||
</t-form>
|
||
</t-form-item>
|
||
<t-form-item v-if="editableItems" arrow content-align="right" @click="openProductPicker">
|
||
<span>添加兑换产品</span>
|
||
</t-form-item>
|
||
<t-form-item v-if="canVerifyOnCreate" :label="verifyPayment ? '回收和核销数量' : '已部分回收和核销'" label-width="9rem" content-align="right">
|
||
<t-input
|
||
:model-value="verifyPayment ? recycleQuantityText : partialPaymentText"
|
||
type="number"
|
||
align="right"
|
||
borderless
|
||
:disabled="verifyPayment"
|
||
:placeholder="`按${recycleUnitName || '回收单位'}填写`"
|
||
@update:model-value="partialPaymentText = String($event)"
|
||
/>
|
||
</t-form-item>
|
||
<t-form-item v-if="canVerifyOnCreate" label="已全部回收和核销" label-width="9rem" content-align="right">
|
||
<t-switch v-model="verifyPayment" size="small" />
|
||
</t-form-item>
|
||
<t-form-item v-if="canFulfillImmediately" label="已全部产品履约和核销" label-width="11rem" content-align="right">
|
||
<t-switch v-model="fulfillAll" size="small" :disabled="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="canVerifyOnCreate && (verifyPayment || (partialPaymentText.trim() && partialPaymentText.trim() !== '0'))" label-width="0">
|
||
<attachment-selector v-model:items="paymentPhotoItems" :upload="uploadPhotoList" title="回收凭证照片" required />
|
||
</t-form-item>
|
||
<t-form-item v-if="fulfillAll" label-width="0">
|
||
<attachment-selector v-model:items="fulfillmentPhotoItems" :upload="uploadPhotoList" title="履约凭证照片" required />
|
||
</t-form-item>
|
||
<t-form-item label="兑换时间" content-align="right">
|
||
<date-time-now-picker v-model="occurredAtText" title="兑换时间" />
|
||
</t-form-item>
|
||
<t-form-item label="备注">
|
||
<t-textarea v-model="remark" borderless autosize maxlength="500" placeholder="选填" />
|
||
</t-form-item>
|
||
<div class="photo-wrap">
|
||
<attachment-selector v-model:items="photoItems" :upload="uploadPhotoList" title="兑换单照片" />
|
||
</div>
|
||
</t-form>
|
||
</main>
|
||
<customer-selector
|
||
v-model="customerId"
|
||
v-model:visible="customerVisible"
|
||
@change="handleCustomerChange"
|
||
/>
|
||
<bottom-popup
|
||
v-model="ruleVisible"
|
||
title="选择兑换模板"
|
||
height="70vh"
|
||
right-button-text=""
|
||
@left-button-click="ruleVisible = false"
|
||
>
|
||
<div class="rule-picker">
|
||
<t-cell
|
||
v-for="item in ruleList"
|
||
:key="item.id"
|
||
class="item"
|
||
arrow
|
||
@click="selectRule(item)"
|
||
>
|
||
<template #leftIcon>
|
||
<t-image
|
||
v-if="getRulePhotoId(item)"
|
||
class="avatar"
|
||
:src="getAttachmentReadURL(getRulePhotoId(item), 96)"
|
||
:alt="item.recycleName || '回收物'"
|
||
fit="cover"
|
||
/>
|
||
<div v-else class="avatar fallback" v-text="(item.recycleName || '回').slice(0, 1)" />
|
||
</template>
|
||
<template #title>
|
||
<span class="clip-text" v-text="item.recycleName || '未命名回收物'" />
|
||
</template>
|
||
<template #note>
|
||
<span v-text="getRuleRatioText(item)" />
|
||
</template>
|
||
<template #description>
|
||
<span class="clip-text" v-text="getRuleProductText(item)" />
|
||
</template>
|
||
</t-cell>
|
||
<center-tips v-if="!ruleList.length" :content="ruleLoading ? '正在加载兑换模板' : '暂无启用的兑换模板'" />
|
||
</div>
|
||
</bottom-popup>
|
||
<recycle-item-picker-popup
|
||
v-model:visible="itemPickerVisible"
|
||
:items="recycleItemList"
|
||
:loading="itemLoading"
|
||
:selected-id="recycleItemId"
|
||
empty-text="暂无启用的回收物,请先在产品详情配置产出"
|
||
show-status
|
||
@select="selectRecycleItem"
|
||
/>
|
||
<product-select-popup
|
||
v-model="selection"
|
||
v-model:visible="productPopupVisible"
|
||
@select="handleProductSelection"
|
||
/>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import { DialogPlugin } from "tdesign-mobile-vue";
|
||
import { BottomPopup, useExpandToMaster, usePane } from "timi-tdesign-mobile";
|
||
import { Time } from "timi-web";
|
||
import { useUserStore } from "timi-web-api";
|
||
import CustomerAPI from "@/api/CustomerAPI";
|
||
import ProductAPI from "@/api/ProductAPI";
|
||
import RecycleAPI from "@/api/RecycleAPI";
|
||
import RecycleItemPickerPopup from "@/pages/recycle/components/RecycleItemPickerPopup.vue";
|
||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||
import ProductSkuTags from "@/components/ProductSkuTags.vue";
|
||
import ProductStockPreview from "@/components/ProductStockPreview.vue";
|
||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||
import DateTimeNowPicker from "@/components/DateTimeNowPicker.vue";
|
||
import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue";
|
||
import ProductSelectPopup from "@/components/productSelector/ProductSelectPopup.vue";
|
||
import type { Customer } from "@/types/Customer";
|
||
import type { PhotoItem } from "@/types/Photo";
|
||
import type { ProductSelection, ProductSku } from "@/types/Product";
|
||
import type { ProductSkuSelectionValue } from "@/types/ProductSkuSelection";
|
||
import type { RecycleExchangeItemRequest, RecycleExchangeRule, RecycleItem, RecycleRuleItem } from "@/types/Recycle";
|
||
import { getAttachmentReadURL } from "@/utils/attachment";
|
||
import { parseDateTime } from "@/utils/date";
|
||
import { getErrorMessage } from "@/utils/error";
|
||
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
|
||
import { Message } from "@/utils/message";
|
||
import { comparePackageQuantity, normalizePackageQuantity, toPackageBaseQuantity } from "@/utils/package";
|
||
import { permissionCodes } from "@/utils/permission";
|
||
import { getProductPhotoURL, getProductQuantityStep, getProductSkuSnapshotText } from "@/utils/product";
|
||
import {
|
||
buildProductStockPreview,
|
||
getProductStockShortageMessage,
|
||
mergeProductStockRequirements,
|
||
type ProductStockPreviewItem
|
||
} from "@/utils/productStock";
|
||
import { getRecycleAvailable, getRecycleQuantityText, multiplyRecycleQuantity } from "@/utils/recycle";
|
||
import { uploadPhotoList } from "@/utils/photo";
|
||
|
||
defineOptions({ name: "RecycleExchangeCreate" });
|
||
|
||
const router = useRouter();
|
||
const route = useRoute();
|
||
const pane = usePane();
|
||
const emit = defineEmits<{ created: [orderId: string] }>();
|
||
const userStore = useUserStore();
|
||
|
||
useExpandToMaster({
|
||
path: "/product/sales-orders",
|
||
id: () => route.query.source === "sales-orders" ? "__recycle_create__" : ""
|
||
});
|
||
|
||
function exit(): void {
|
||
if (pane) {
|
||
pane.close();
|
||
return;
|
||
}
|
||
void router.back();
|
||
}
|
||
|
||
// ---------- 客户 ----------
|
||
|
||
const customerId = ref("");
|
||
const customer = ref<Customer>();
|
||
const customerVisible = ref(false);
|
||
const customerName = computed(() => customer.value?.name || customer.value?.code || "");
|
||
|
||
async function handleCustomerChange(value: string | string[]): Promise<void> {
|
||
const id = Array.isArray(value) ? String(value[0] || "") : value;
|
||
customerId.value = id;
|
||
if (!id) {
|
||
customer.value = undefined;
|
||
return;
|
||
}
|
||
try {
|
||
customer.value = await CustomerAPI.detail(id);
|
||
} catch (error) {
|
||
customer.value = undefined;
|
||
Message.error(getErrorMessage(error, "客户资料加载失败"));
|
||
}
|
||
}
|
||
|
||
// ---------- 创建方式 ----------
|
||
|
||
const canAdjust = computed(() => userStore.hasPermissions(permissionCodes.salesOrder.priceOverride));
|
||
/** 创建即核销需要支付创建与核销两个权限,服务端同样双校验 */
|
||
const canVerifyOnCreate = computed(() => userStore.hasPermissions(permissionCodes.fundReceive.create)
|
||
&& userStore.hasPermissions(permissionCodes.fundReceive.verify));
|
||
const verifyPayment = ref(false);
|
||
const partialPaymentText = ref("");
|
||
const fulfillAll = ref(false);
|
||
const isStockChecking = ref(false);
|
||
const stockPreviewList = ref<ProductStockPreviewItem[]>([]);
|
||
const canFulfillImmediately = computed(() => canVerifyOnCreate.value
|
||
&& userStore.hasPermissions(permissionCodes.orderFulfillment.create)
|
||
&& userStore.hasPermissions(permissionCodes.orderFulfillment.verify)
|
||
&& userStore.hasPermissions(permissionCodes.productStock.read));
|
||
// ---------- 模板 ----------
|
||
|
||
const ruleVisible = ref(false);
|
||
const ruleLoading = ref(false);
|
||
const ruleList = ref<RecycleExchangeRule[]>([]);
|
||
const selectedRule = ref<RecycleExchangeRule>();
|
||
const multiple = ref(1);
|
||
|
||
const ruleDisplayText = computed(() => selectedRule.value?.recycleName || "选择可用模板");
|
||
const recycleItemName = computed(() => selectedRecycleItem.value?.name || selectedRule.value?.recycleName || "");
|
||
const recycleUnitName = computed(() => selectedRecycleItem.value?.unitName || selectedRule.value?.recycleUnit || "");
|
||
|
||
function getRuleRatioText(rule: RecycleExchangeRule): string {
|
||
const recycleText = getRecycleQuantityText(rule.recycleQuantity, rule.recycleUnit);
|
||
return `${recycleText} 换 ${(rule.itemList || []).length} 项`;
|
||
}
|
||
|
||
function getRulePhotoId(rule: RecycleExchangeRule): string {
|
||
return rule.recycleItemAttachments?.find(item => item.id && item.mimeType?.startsWith("image/"))?.id || "";
|
||
}
|
||
|
||
function getRuleProductText(rule: RecycleExchangeRule): string {
|
||
const names = (rule.itemList || []).map(item => item.productName || item.skuName || "未命名产品");
|
||
if (!names.length) {
|
||
return "未配置商品";
|
||
}
|
||
const suffix = 2 < names.length ? ` 等 ${names.length} 项` : "";
|
||
return names.slice(0, 2).join("、") + suffix;
|
||
}
|
||
|
||
/** 启用模板可能超过一页,创建时一次取完,避免被分页截断。 */
|
||
async function loadRules(): Promise<void> {
|
||
ruleLoading.value = true;
|
||
try {
|
||
const rules: RecycleExchangeRule[] = [];
|
||
let offset = 0;
|
||
const limit = 100;
|
||
let total = 0;
|
||
do {
|
||
const page = await RecycleAPI.activeRuleList({ offset, limit });
|
||
const rows = page.list || [];
|
||
rules.push(...rows);
|
||
total = page.total || 0;
|
||
offset += rows.length;
|
||
if (!rows.length) {
|
||
break;
|
||
}
|
||
} while (offset < total);
|
||
ruleList.value = rules;
|
||
} catch (error) {
|
||
Message.error(getErrorMessage(error, "启用兑换模板加载失败"));
|
||
} finally {
|
||
ruleLoading.value = false;
|
||
}
|
||
}
|
||
|
||
async function openRulePicker(): Promise<void> {
|
||
ruleVisible.value = true;
|
||
if (!ruleList.value.length && !ruleLoading.value) {
|
||
await loadRules();
|
||
}
|
||
}
|
||
|
||
function selectRule(rule: RecycleExchangeRule): void {
|
||
selectedRule.value = rule;
|
||
ruleVisible.value = false;
|
||
rebuildFromRule();
|
||
}
|
||
|
||
function clearRule(): void {
|
||
selectedRule.value = undefined;
|
||
}
|
||
|
||
// ---------- 回收物 ----------
|
||
|
||
const itemPickerVisible = ref(false);
|
||
const itemLoading = ref(false);
|
||
const recycleItemList = ref<RecycleItem[]>([]);
|
||
const recycleItemId = ref("");
|
||
const selectedRecycleItem = ref<RecycleItem>();
|
||
const recycleQuantityText = ref("");
|
||
const customerRecycleText = ref("正在加载");
|
||
const customerRecycleAvailable = ref<string>();
|
||
const customerRecycleClass = computed(() => {
|
||
const required = normalizePackageQuantity(recycleQuantityText.value || "0");
|
||
if (customerRecycleAvailable.value === undefined || required === undefined) return "";
|
||
return comparePackageQuantity(customerRecycleAvailable.value, required) < 0 ? "insufficient" : "sufficient";
|
||
});
|
||
|
||
watch([customerId, recycleItemId], async ([customer, item], _previous, onCleanup) => {
|
||
let active = true;
|
||
onCleanup(() => { active = false; });
|
||
customerRecycleAvailable.value = undefined;
|
||
if (!customer || !item) return;
|
||
if (!userStore.hasPermissions(permissionCodes.recycleAccount.read)) {
|
||
customerRecycleText.value = "无权限查看";
|
||
return;
|
||
}
|
||
customerRecycleText.value = "正在加载";
|
||
try {
|
||
const accounts = await RecycleAPI.accountList(customer);
|
||
if (!active) return;
|
||
const account = accounts.find(value => value.recycleItemId === item);
|
||
customerRecycleAvailable.value = getRecycleAvailable(account).toFixed(3);
|
||
customerRecycleText.value = `可用 ${getRecycleQuantityText(customerRecycleAvailable.value, recycleUnitName.value)}`;
|
||
} catch (error) {
|
||
if (!active) return;
|
||
customerRecycleText.value = "加载失败";
|
||
Message.error(getErrorMessage(error, "客户回收物数量加载失败"));
|
||
}
|
||
}, { immediate: true });
|
||
|
||
async function loadRecycleItems(): Promise<void> {
|
||
itemLoading.value = true;
|
||
try {
|
||
const items: RecycleItem[] = [];
|
||
let offset = 0;
|
||
const limit = 100;
|
||
let total = 0;
|
||
do {
|
||
const page = await RecycleAPI.itemList({ offset, limit, status: "ACTIVE" });
|
||
const rows = page.list || [];
|
||
items.push(...rows);
|
||
total = page.total || 0;
|
||
offset += rows.length;
|
||
if (!rows.length) {
|
||
break;
|
||
}
|
||
} while (offset < total);
|
||
recycleItemList.value = items;
|
||
selectedRecycleItem.value = items.find(item => item.id === recycleItemId.value);
|
||
} catch (error) {
|
||
Message.error(getErrorMessage(error, "回收物加载失败"));
|
||
} finally {
|
||
itemLoading.value = false;
|
||
}
|
||
}
|
||
|
||
function selectRecycleItem(item: RecycleItem): void {
|
||
recycleItemId.value = item.id || "";
|
||
selectedRecycleItem.value = item;
|
||
itemPickerVisible.value = false;
|
||
}
|
||
|
||
// ---------- 兑换明细 ----------
|
||
|
||
/** 明细行的编辑态。key 用于 v-for 稳定,不提交给服务端。 */
|
||
type ItemRow = {
|
||
key: number;
|
||
skuId: string;
|
||
skuUnitId: string;
|
||
productName: string;
|
||
skuText: string;
|
||
unitName: string;
|
||
quantityText: string;
|
||
allowDecimalQuantity: boolean;
|
||
};
|
||
const itemRows = ref<ItemRow[]>([]);
|
||
const skuMap = reactive<Record<string, ProductSku>>({});
|
||
const loadingSkuIds = new Set<string>();
|
||
const selection = ref<ProductSkuSelectionValue>();
|
||
const productPopupVisible = ref(false);
|
||
let rowSeed = 0;
|
||
|
||
/** 无调整权限时明细完全由模板决定,不可增删改 */
|
||
const editableItems = computed(() => canAdjust.value);
|
||
|
||
/**
|
||
* 按模板重建明细。
|
||
*
|
||
* 换模板、改份数都走这里:份数变了就是重新生成,用户自填的值不再保留。
|
||
*/
|
||
function rebuildFromRule(): void {
|
||
const rule = selectedRule.value;
|
||
if (!rule) {
|
||
itemRows.value = [];
|
||
return;
|
||
}
|
||
recycleItemId.value = rule.recycleItemId || "";
|
||
selectedRecycleItem.value = recycleItemList.value.find(item => item.id === rule.recycleItemId);
|
||
recycleQuantityText.value = multiplyRecycleQuantity(rule.recycleQuantity, multiple.value);
|
||
itemRows.value = (rule.itemList || []).map(source => createRowFromRule(source));
|
||
void loadSkuDetails(itemRows.value);
|
||
}
|
||
|
||
function createRowFromRule(source: RecycleRuleItem): ItemRow {
|
||
rowSeed += 1;
|
||
return {
|
||
key: rowSeed,
|
||
skuId: source.skuId,
|
||
skuUnitId: source.skuUnitId,
|
||
productName: source.productName || "",
|
||
skuText: getProductSkuSnapshotText(source.productName, source.skuName, source.specSummary),
|
||
unitName: source.unitName || "",
|
||
allowDecimalQuantity: source.allowDecimalQuantity ?? false,
|
||
quantityText: multiplyRecycleQuantity(source.exchangeQuantity, multiple.value)
|
||
};
|
||
}
|
||
|
||
function openProductPicker(): void {
|
||
productPopupVisible.value = true;
|
||
}
|
||
|
||
function handleProductSelection(value: ProductSelection): void {
|
||
const skuId = value.sku.id || "";
|
||
const skuUnitId = value.unit.id || "";
|
||
if (itemRows.value.some(row => row.skuId === skuId && row.skuUnitId === skuUnitId)) {
|
||
Message.warning("该商品的这个单位已在明细中");
|
||
return;
|
||
}
|
||
rowSeed += 1;
|
||
skuMap[skuId] = value.sku;
|
||
itemRows.value.push({
|
||
key: rowSeed,
|
||
skuId,
|
||
skuUnitId,
|
||
productName: value.product.name,
|
||
skuText: getProductSkuSnapshotText(value.product.name, value.sku.name, value.sku.specSummary),
|
||
unitName: value.unit.name,
|
||
allowDecimalQuantity: value.sku.allowDecimalQuantity,
|
||
quantityText: "1"
|
||
});
|
||
}
|
||
|
||
function removeItem(index: number): void {
|
||
itemRows.value.splice(index, 1);
|
||
}
|
||
|
||
/** 按 SKU 补充图片;份数变化时复用已加载的结果。 */
|
||
async function loadSkuDetails(rows: ItemRow[]): Promise<void> {
|
||
const ids = [...new Set(rows.map(row => row.skuId).filter(id => id && !skuMap[id] && !loadingSkuIds.has(id)))];
|
||
for (const id of ids) {
|
||
loadingSkuIds.add(id);
|
||
}
|
||
const results = await Promise.allSettled(ids.map(async id => await ProductAPI.skuDetail(id)));
|
||
results.forEach((result, index) => {
|
||
const id = ids[index];
|
||
loadingSkuIds.delete(id);
|
||
if (result.status === "fulfilled") {
|
||
skuMap[id] = result.value;
|
||
for (const row of itemRows.value) {
|
||
if (row.skuId === id) {
|
||
row.allowDecimalQuantity = result.value.allowDecimalQuantity;
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// 切换模板或份数时,按模板重新生成数量。
|
||
watch(multiple, rebuildFromRule);
|
||
|
||
// ---------- 其它字段 ----------
|
||
|
||
const occurredAtText = ref("");
|
||
const remark = ref("");
|
||
const photoItems = ref<PhotoItem[]>([]);
|
||
const fulfillmentPhotoItems = ref<PhotoItem[]>([]);
|
||
const paymentPhotoItems = ref<PhotoItem[]>([]);
|
||
const requestNo = ref("");
|
||
const saving = ref(false);
|
||
|
||
function buildAttachments(items: PhotoItem[]): Array<{ tempFileId: string; attachType: "PHOTO" }> {
|
||
return items.flatMap(item => item.tempFileId ? [{
|
||
tempFileId: item.tempFileId,
|
||
attachType: "PHOTO" as const
|
||
}] : []);
|
||
}
|
||
|
||
function buildOccurredAt(): number | undefined {
|
||
return occurredAtText.value ? Time.toTimestamp(parseDateTime(occurredAtText.value, false)) : undefined;
|
||
}
|
||
|
||
// 提交内容一变就要换请求号,服务端按请求号 + 内容摘要去重
|
||
watch([
|
||
customerId, () => selectedRule.value?.id, multiple, recycleItemId, recycleQuantityText, itemRows, verifyPayment, partialPaymentText,
|
||
fulfillAll, occurredAtText, remark, photoItems, fulfillmentPhotoItems, paymentPhotoItems
|
||
], () => {
|
||
requestNo.value = "";
|
||
}, { deep: true });
|
||
|
||
let stockCheckVersion = 0;
|
||
watch(fulfillAll, async value => {
|
||
const version = ++stockCheckVersion;
|
||
if (!value) {
|
||
isStockChecking.value = false;
|
||
return;
|
||
}
|
||
verifyPayment.value = true;
|
||
isStockChecking.value = true;
|
||
try {
|
||
if (!await validateDirectStock() && version === stockCheckVersion) {
|
||
fulfillAll.value = false;
|
||
}
|
||
} finally {
|
||
if (version === stockCheckVersion) {
|
||
isStockChecking.value = false;
|
||
}
|
||
}
|
||
});
|
||
|
||
watch(verifyPayment, value => {
|
||
if (!value) {
|
||
fulfillAll.value = false;
|
||
}
|
||
});
|
||
|
||
watch(() => itemRows.value.map(row => `${row.skuId}:${row.skuUnitId}:${row.quantityText}`).join("|"), () => {
|
||
fulfillAll.value = false;
|
||
stockPreviewList.value = [];
|
||
});
|
||
|
||
async function validateDirectStock(): Promise<boolean> {
|
||
stockPreviewList.value = [];
|
||
if (!itemRows.value.length) {
|
||
Message.warning("请先选择兑换商品");
|
||
return false;
|
||
}
|
||
const ids = [...new Set(itemRows.value.map(row => row.skuId))];
|
||
try {
|
||
await Promise.all(ids.map(async id => {
|
||
if (!skuMap[id]) {
|
||
skuMap[id] = await ProductAPI.skuDetail(id);
|
||
}
|
||
}));
|
||
const requirements = [];
|
||
for (const row of itemRows.value) {
|
||
const sku = skuMap[row.skuId];
|
||
const unit = sku?.unitList?.find(item => item.id === row.skuUnitId);
|
||
const quantity = normalizePackageQuantity(row.quantityText);
|
||
const baseQuantity = quantity && unit ? toPackageBaseQuantity(quantity, unit.baseQuantityPerUnit) : undefined;
|
||
if (!sku || !unit || !baseQuantity || baseQuantity === "0") {
|
||
Message.warning(`请检查「${row.productName || "未命名产品"}」的数量和单位`);
|
||
return false;
|
||
}
|
||
if (sku.stockEnabled) {
|
||
requirements.push({ skuId: row.skuId, baseQuantity, productName: row.productName || "未命名产品", unitName: "基础单位", stockEnabled: true });
|
||
}
|
||
}
|
||
const merged = mergeProductStockRequirements(requirements);
|
||
if (!merged.length) {
|
||
return true;
|
||
}
|
||
const stockList = await ProductAPI.stockBatchDetail({ skuIdList: merged.map(item => item.skuId) });
|
||
stockPreviewList.value = buildProductStockPreview(stockList, merged);
|
||
const shortage = getProductStockShortageMessage(stockList, merged);
|
||
if (shortage) {
|
||
Message.warning(`${shortage},不能直接履约`);
|
||
return false;
|
||
}
|
||
return true;
|
||
} catch (error) {
|
||
Message.error(getErrorMessage(error, "库存查询失败,暂不能直接履约"));
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// ---------- 提交 ----------
|
||
|
||
async function save(): Promise<void> {
|
||
if (saving.value) {
|
||
return;
|
||
}
|
||
if (isStockChecking.value) {
|
||
Message.warning("库存正在预检,请稍候再提交");
|
||
return;
|
||
}
|
||
if (!customerId.value) {
|
||
Message.warning("请选择客户");
|
||
return;
|
||
}
|
||
if (!selectedRule.value?.id && !canAdjust.value) {
|
||
Message.warning("无自由创建权限,请选择兑换模板");
|
||
return;
|
||
}
|
||
const multipleValue = selectedRule.value ? Number(multiple.value) : 1;
|
||
if (!Number.isSafeInteger(multipleValue) || multipleValue < 1) {
|
||
Message.warning("兑换份数必须为正整数");
|
||
return;
|
||
}
|
||
if (!recycleItemId.value) {
|
||
Message.warning("请选择回收物");
|
||
return;
|
||
}
|
||
const recycleQuantity = normalizePackageQuantity(recycleQuantityText.value);
|
||
if (!recycleQuantity || "0" === recycleQuantity) {
|
||
Message.warning("回收数量必须为大于 0 的数字,最多 3 位小数");
|
||
return;
|
||
}
|
||
const paymentQuantity = verifyPayment.value ? recycleQuantity : partialPaymentText.value.trim() ? normalizePackageQuantity(partialPaymentText.value) : "0";
|
||
if (!paymentQuantity || 0 < comparePackageQuantity(paymentQuantity, recycleQuantity)) {
|
||
Message.warning("已回收数量不能超过应回收数量,最多保留 3 位小数");
|
||
return;
|
||
}
|
||
const itemList: RecycleExchangeItemRequest[] = [];
|
||
const seen = new Set<string>();
|
||
for (const row of itemRows.value) {
|
||
const quantity = normalizePackageQuantity(row.quantityText);
|
||
if (!quantity || "0" === quantity) {
|
||
Message.warning(`请填写「${row.productName || "未命名产品"}」的兑换数量`);
|
||
return;
|
||
}
|
||
const uniqueKey = `${row.skuId}|${row.skuUnitId}`;
|
||
if (seen.has(uniqueKey)) {
|
||
Message.warning("同一商品和单位不能重复");
|
||
return;
|
||
}
|
||
seen.add(uniqueKey);
|
||
itemList.push({ skuId: row.skuId, skuUnitId: row.skuUnitId, quantity });
|
||
}
|
||
if (!itemList.length) {
|
||
Message.warning("请至少添加一个兑换商品");
|
||
return;
|
||
}
|
||
if (paymentQuantity !== "0" && !paymentPhotoItems.value.length) {
|
||
Message.warning("请上传回收凭证照片");
|
||
return;
|
||
}
|
||
if (fulfillAll.value && !fulfillmentPhotoItems.value.length) {
|
||
Message.warning("请上传履约凭证照片");
|
||
return;
|
||
}
|
||
if (paymentQuantity !== "0" || fulfillAll.value) {
|
||
const dialog = DialogPlugin.confirm({
|
||
title: "确认完成交易",
|
||
content: fulfillAll.value
|
||
? "将创建兑换订单、核销全部回收物并完成全部履约和库存扣减,提交后需通过冲正流程更正。"
|
||
: "将创建兑换订单并核销已回收的回收物,提交后需通过冲正流程更正。",
|
||
cancelBtn: "取消",
|
||
confirmBtn: "确认并提交",
|
||
onCancel() { dialog.destroy(); },
|
||
async onConfirm() {
|
||
dialog.destroy();
|
||
await submit(itemList, recycleQuantity, multipleValue, paymentQuantity);
|
||
}
|
||
});
|
||
return;
|
||
}
|
||
await submit(itemList, recycleQuantity, multipleValue, paymentQuantity);
|
||
}
|
||
|
||
async function submit(itemList: RecycleExchangeItemRequest[], recycleQuantity: string, multipleValue: number, paymentQuantity: string): Promise<void> {
|
||
if (saving.value) {
|
||
return;
|
||
}
|
||
saving.value = true;
|
||
if (fulfillAll.value && !await validateDirectStock()) {
|
||
saving.value = false;
|
||
return;
|
||
}
|
||
if (!requestNo.value) {
|
||
requestNo.value = window.crypto.randomUUID();
|
||
}
|
||
try {
|
||
const result = await RecycleAPI.create({
|
||
customerId: customerId.value,
|
||
ruleId: selectedRule.value?.id,
|
||
recycleItemId: recycleItemId.value,
|
||
// 有调整权限时明确提交,没权限时省略让服务端按模板生成
|
||
itemList: canAdjust.value ? itemList : undefined,
|
||
requestNo: requestNo.value,
|
||
multiple: multipleValue,
|
||
recycleQuantity: canAdjust.value ? recycleQuantity : undefined,
|
||
paymentQuantity: canVerifyOnCreate.value ? paymentQuantity : undefined,
|
||
paymentAttachmentList: paymentQuantity !== "0" ? buildAttachments(paymentPhotoItems.value) : undefined,
|
||
fulfillAll: canFulfillImmediately.value && fulfillAll.value,
|
||
fulfillmentAttachmentList: fulfillAll.value ? buildAttachments(fulfillmentPhotoItems.value) : undefined,
|
||
occurredAt: buildOccurredAt(),
|
||
remark: remark.value || null,
|
||
attachmentList: buildAttachments(photoItems.value)
|
||
});
|
||
Message.success("兑换单已创建");
|
||
emitListDataChanged(listDataEventKeys.salesOrderChanged, result.salesOrderId);
|
||
if (fulfillAll.value) {
|
||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||
}
|
||
if (pane) {
|
||
if (result.salesOrderId) {
|
||
emit("created", result.salesOrderId);
|
||
} else {
|
||
pane.close(true);
|
||
}
|
||
return;
|
||
}
|
||
const orderId = result.salesOrderId || "";
|
||
if (orderId) {
|
||
await router.replace({ name: "SalesOrderDetail", params: { id: orderId } });
|
||
return;
|
||
}
|
||
await router.replace({ name: "SalesOrderList", query: { orderType: "RECYCLE" } });
|
||
} catch (error) {
|
||
Message.error(getErrorMessage(error, "兑换单创建失败,重试会复用同一请求号"));
|
||
} finally {
|
||
saving.value = false;
|
||
}
|
||
}
|
||
|
||
onMounted(async () => {
|
||
await Promise.all([loadRules(), loadRecycleItems()]);
|
||
const ruleId = typeof route.query.ruleId === "string" ? route.query.ruleId : "";
|
||
if (ruleId) {
|
||
const rule = ruleList.value.find(item => String(item.id) === ruleId);
|
||
if (rule) {
|
||
selectRule(rule);
|
||
} else {
|
||
Message.warning("模板不存在或已停用,请重新选择");
|
||
}
|
||
}
|
||
});
|
||
</script>
|
||
|
||
<style scoped lang="less">
|
||
.rule-picker {
|
||
.avatar {
|
||
width: 3.5rem;
|
||
height: 3.5rem;
|
||
}
|
||
}
|
||
|
||
.recycle-exchange-create {
|
||
.sufficient {
|
||
color: var(--td-success-color);
|
||
}
|
||
|
||
.insufficient {
|
||
color: var(--td-warning-color);
|
||
}
|
||
|
||
.form {
|
||
|
||
.template {
|
||
--td-button-extra-small-height: 24px;
|
||
|
||
gap: .5rem;
|
||
display: flex;
|
||
align-items: center;
|
||
}
|
||
|
||
|
||
.customer-profile {
|
||
margin: 1rem;
|
||
}
|
||
|
||
.quantity {
|
||
gap: .5rem;
|
||
display: flex;
|
||
min-width: 0;
|
||
align-items: center;
|
||
justify-content: end;
|
||
}
|
||
|
||
.detail {
|
||
padding: 0;
|
||
|
||
.items {
|
||
width: 100%;
|
||
margin: 0;
|
||
|
||
.item-content {
|
||
gap: .5rem;
|
||
width: 100%;
|
||
display: flex;
|
||
min-width: 0;
|
||
}
|
||
|
||
.photo .avatar {
|
||
width: 3.5rem;
|
||
height: 3.5rem;
|
||
border-radius: .5rem;
|
||
}
|
||
|
||
.main {
|
||
gap: .5rem;
|
||
flex: 1;
|
||
display: flex;
|
||
min-width: 0;
|
||
flex-direction: column;
|
||
}
|
||
|
||
.head {
|
||
gap: .5rem;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
}
|
||
|
||
.title {
|
||
gap: .25rem;
|
||
display: flex;
|
||
min-width: 0;
|
||
overflow: hidden;
|
||
align-items: center;
|
||
|
||
.name {
|
||
flex: 0 1 auto;
|
||
min-width: 0;
|
||
}
|
||
|
||
:deep(.tags) {
|
||
flex: 0 0 auto;
|
||
flex-wrap: nowrap;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
.tips {
|
||
font-size: .875rem;
|
||
line-height: 1.6;
|
||
}
|
||
|
||
.photo-wrap {
|
||
padding: 1rem;
|
||
}
|
||
}
|
||
|
||
}
|
||
:global(html.theme-dark) {
|
||
|
||
.rule-picker .item.active {
|
||
background: rgba(15, 118, 110, .22);
|
||
}
|
||
}
|
||
</style>
|