add OrderFulfillmentQuick.vue

This commit is contained in:
Timi
2026-10-21 00:14:06 +08:00
parent 77e0e7a8e0
commit db0431fbd5
13 changed files with 1716 additions and 35 deletions
@@ -247,6 +247,13 @@ const filterMenuRef = ref<{ collapseMenu: () => void }>();
const userStore = useUserStore();
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.create));
const actions = computed<NavBarAction[]>(() => [
{
key: "quick-fulfillment",
text: "快速履约",
icon: "rocket",
theme: "primary",
action: toQuickFulfillment
},
{
key: "by-order",
text: "通过订单创建",
@@ -580,6 +587,13 @@ async function toPackageOrderList(): Promise<void> {
});
}
async function toQuickFulfillment(): Promise<void> {
await router.push({
name: "OrderFulfillmentQuick",
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
function getCurrentRouteDepth(): number {
const transitionDepth = Array.isArray(route.query.transitionDepth)
? route.query.transitionDepth[0]
@@ -0,0 +1,480 @@
<template>
<div class="page-layout navbar quick-fulfillment">
<t-navbar
fixed
:z-index="20"
title="快速履约"
left-arrow
@left-click="handleBack"
>
<template #right>
<button class="nav-action" type="button" :disabled="isSaving || isStockChecking || sourceOrderLoading" @click="save">
<span v-text="isSaving ? '提交中' : '提交'" />
</button>
</template>
</t-navbar>
<main v-can="permissionCodes.orderFulfillment.create" class="page-content scroll column content">
<customer-profile-card v-if="selectedCustomer" class="customer-profile" :customer="selectedCustomer" />
<t-cell-group theme="card">
<t-cell title="履约客户" arrow @click="customerSelectorVisible = true">
<template #note>
<span v-text="selectedCustomer?.name || '选择'" />
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="产品选择" theme="card">
<t-cell v-if="customerId" title="选择产品 SKU" arrow @click="productSelectorVisible = true" />
<t-cell v-else title="选择产品 SKU" note="请先选择履约客户" />
</t-cell-group>
<order-fulfillment-quick-quantity
ref="fulfillmentQuantityRef"
:sku-list="selectedSkuList"
:is-stock-checking="isStockChecking"
@change="handleFulfillmentChange"
/>
<order-fulfillment-quick-source-orders
ref="sourceOrdersRef"
:customer-id="customerId"
:fulfillment-item-list="fulfillmentItemList"
@loading-change="sourceOrderLoading = $event"
/>
<t-cell-group title="履约信息" theme="card">
<t-cell title="履约时间" content-align="right">
<template #note>
<div class="time-actions" @click.stop>
<t-button
theme="primary"
variant="outline"
size="extra-small"
:content="deliveredAtText || '此刻'"
@click="openDeliveredAtPicker"
/>
<t-button
v-if="deliveredAtText"
theme="primary"
variant="text"
size="extra-small"
content="此刻"
@click="resetDeliveredAt"
/>
</div>
</template>
</t-cell>
<t-cell v-if="canDirectVerify" title="直接核销履约" content-align="right">
<template #note>
<t-switch v-model="directVerify" size="small" :disabled="isSaving || isStockChecking" />
</template>
</t-cell>
<div v-if="directVerify || stockPreviewList.length" class="stock-wrap bg-white">
<center-tips>直接核销会立即扣减库存,缺货时整批提交失败</center-tips>
<product-stock-preview v-if="stockPreviewList.length" :items="stockPreviewList" />
<center-tips v-else-if="!isStockChecking" class="stock-hint">所选 SKU 无需扣减库存</center-tips>
<center-tips v-else class="stock-hint">正在检查库存…</center-tips>
</div>
<t-cell title="备注">
<template #note>
<t-textarea v-model="remark" borderless autosize maxlength="500" placeholder="选填" />
</template>
</t-cell>
</t-cell-group>
<t-cell-group class="attachment-group" theme="card">
<media-selector
:model-value="photoUrlList"
v-model:photo-items="photoItems"
:upload="uploadPhotoList"
:edit-mode="true"
required
title="履约凭证照片"
/>
</t-cell-group>
</main>
<customer-selector
v-model="customerId"
v-model:visible="customerSelectorVisible"
selection-mode="single"
@change="handleCustomerChange"
/>
<product-select-popup
v-model:visible="productSelectorVisible"
selection-mode="multiple"
:selectable-product-id-list="selectableProductIdList"
:selectable-sku-id-list="selectableSkuIdList"
:selected-sku-id-list="selectedSkuIdList"
@confirm="handleProductSkuSelectionChange"
/>
<t-popup v-model="timePickerVisible" placement="bottom">
<t-date-time-picker
v-if="timePickerVisible"
v-model="draftTime"
format="YYYY-MM-DD HH:mm"
:mode="['date', 'minute']"
title="履约时间"
@cancel="timePickerVisible = false"
@confirm="confirmTime"
/>
</t-popup>
</div>
</template>
<script setup lang="ts">
import { Time } from "timi-web";
import type { Attachment } from "timi-web-api";
import { useUserStore } from "timi-web-api";
import CustomerAPI from "@/api/CustomerAPI";
import FulfillmentAPI from "@/api/FulfillmentAPI";
import ProductAPI from "@/api/ProductAPI";
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
import CustomerSelector from "@/components/CustomerSelector.vue";
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
import ProductSelectPopup from "@/components/productSelector/ProductSelectPopup.vue";
import ProductStockPreview from "@/components/ProductStockPreview.vue";
import OrderFulfillmentQuickQuantity from "@/pages/fulfillment/components/OrderFulfillmentQuickQuantity.vue";
import OrderFulfillmentQuickSourceOrders from "@/pages/fulfillment/components/OrderFulfillmentQuickSourceOrders.vue";
import type {
QuickFulfillmentItem,
QuickFulfillmentQuantityExpose,
QuickFulfillmentSourceOrdersExpose
} from "@/pages/fulfillment/components/OrderFulfillmentQuickTypes";
import type { Customer } from "@/types/Customer";
import type { QuickFulfillmentSku } from "@/types/Fulfillment";
import type { PhotoItem } from "@/types/Photo";
import { comparePackageQuantity, createPackageRequestNo } from "@/utils/package";
import { getErrorMessage } from "@/utils/error";
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
import { Message } from "@/utils/message";
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
import type { ProductStockPreviewItem } from "@/utils/productStock";
import {
buildProductStockPreview,
getProductStockShortageMessage
} from "@/utils/productStock";
import { uploadPhotoList } from "@/utils/photo";
defineOptions({ name: "OrderFulfillmentQuick" });
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const customerId = ref("");
const selectedCustomer = ref<Customer>();
const customerSelectorVisible = ref(false);
const skuList = ref<QuickFulfillmentSku[]>([]);
const selectedSkuIdList = ref<string[]>([]);
const productSelectorVisible = ref(false);
const fulfillmentItemList = ref<QuickFulfillmentItem[]>([]);
const fulfillmentQuantityRef = ref<QuickFulfillmentQuantityExpose>();
const sourceOrdersRef = ref<QuickFulfillmentSourceOrdersExpose>();
const loadingSkuList = ref(false);
const sourceOrderLoading = ref(false);
const isSaving = ref(false);
const isStockChecking = ref(false);
const directVerify = ref(false);
const stockPreviewList = ref<ProductStockPreviewItem[]>([]);
const deliveredAtText = ref("");
const timePickerVisible = ref(false);
const draftTime = ref("");
const remark = ref("");
const photoItems = ref<PhotoItem[]>([]);
const requestNo = ref("");
let stockCheckToken = 0;
let stockPreviewTimer: number | undefined;
const selectedSkuList = computed(() => selectedSkuIdList.value
.map(id => skuList.value.find(sku => sku.skuId === id))
.filter((sku): sku is QuickFulfillmentSku => !!sku));
const selectableQuickSkuList = computed(() => skuList.value.filter(canSelectSku));
const selectableSkuIdList = computed(() => selectableQuickSkuList.value.map(sku => sku.skuId));
const selectableProductIdList = computed(() => [...new Set(selectableQuickSkuList.value
.flatMap(sku => sku.productId ? [sku.productId] : []))]);
const canDirectVerify = computed(() => userStore.hasRoles(gaoRoleCodes.storeManager)
&& userStore.hasPermissions(permissionCodes.orderFulfillment.create)
&& userStore.hasPermissions(permissionCodes.orderFulfillment.verify)
&& userStore.hasPermissions(permissionCodes.productStock.read));
const photoUrlList = computed(() => photoItems.value.map(item => item.previewUrl || item.url));
// ---------- SKU 选择 ----------
function canSelectSku(sku: QuickFulfillmentSku): boolean {
return !!sku.skuId
&& 0 < comparePackageQuantity(sku.availableBaseQuantity, "0")
&& sku.unitList.some(unit => !!unit.id);
}
function handleProductSkuSelectionChange(value: string[]): void {
const availableSkuMap = new Map(skuList.value
.filter(canSelectSku)
.map(sku => [sku.skuId, sku]));
const currentSkuIdSet = new Set(selectedSkuIdList.value);
const nextSkuIdList = [...new Set(value)].filter(id => availableSkuMap.has(id));
const rejectedCount = value.filter(id => !availableSkuMap.has(id) && !currentSkuIdSet.has(id)).length;
selectedSkuIdList.value = nextSkuIdList;
if (rejectedCount) {
Message.warning("部分 SKU 不在当前客户的可履约订单中,已忽略");
}
}
// ---------- 客户选择 ----------
async function handleCustomerChange(id: string): Promise<void> {
if (!id || id === customerId.value && selectedCustomer.value?.id === id) {
return;
}
customerId.value = id;
selectedCustomer.value = undefined;
productSelectorVisible.value = false;
skuList.value = [];
selectedSkuIdList.value = [];
stockPreviewList.value = [];
try {
const [customer] = await Promise.all([
CustomerAPI.detail(id),
loadSkuList(id)
]);
selectedCustomer.value = customer;
} catch (error) {
Message.error(getErrorMessage(error, "客户信息加载失败"));
}
}
async function loadSkuList(id: string): Promise<void> {
loadingSkuList.value = true;
try {
skuList.value = await FulfillmentAPI.quickSkuList(id);
} finally {
loadingSkuList.value = false;
}
}
// ---------- 履约数量状态 ----------
function handleFulfillmentChange(itemList: QuickFulfillmentItem[]): void {
fulfillmentItemList.value = itemList;
scheduleStockPreview();
}
// ---------- 来源订单状态由子组件管理 ----------
function openDeliveredAtPicker(): void {
draftTime.value = deliveredAtText.value || Time.formatDateTime(new Date());
timePickerVisible.value = true;
}
function confirmTime(value: string | number): void {
deliveredAtText.value = String(value);
timePickerVisible.value = false;
}
function resetDeliveredAt(): void {
deliveredAtText.value = "";
draftTime.value = "";
}
function resolveTimestamp(value: string): number | undefined {
if (!value) {
return undefined;
}
const timestamp = new Date(value.replace(" ", "T")).getTime();
return Number.isFinite(timestamp) ? timestamp : undefined;
}
function buildAttachments(): Partial<Attachment>[] {
return photoItems.value.flatMap(item => item.tempFileId ? [{ tempFileId: item.tempFileId, attachType: "PHOTO" }] : []);
}
// ---------- 库存预检 ----------
async function validateDirectStock(showShortageMessage = true): Promise<boolean> {
stockPreviewList.value = [];
const requirementList = fulfillmentQuantityRef.value?.buildStockRequirements() || [];
if (!requirementList.length) {
return true;
}
try {
const stockList = await ProductAPI.stockBatchDetail({ skuIdList: requirementList.map(item => item.skuId) });
stockPreviewList.value = buildProductStockPreview(stockList, requirementList);
const shortageMessage = getProductStockShortageMessage(stockList, requirementList);
if (shortageMessage) {
if (showShortageMessage) {
Message.warning(`${shortageMessage},不能直接核销履约`);
}
return false;
}
return true;
} catch (error) {
stockPreviewList.value = [];
Message.error(getErrorMessage(error, "库存查询失败,暂不能直接核销履约"));
return false;
}
}
async function refreshStockPreview(): Promise<void> {
if (!directVerify.value || isStockChecking.value) {
return;
}
stockCheckToken += 1;
const token = stockCheckToken;
isStockChecking.value = true;
try {
if (!await validateDirectStock(true) && token === stockCheckToken && directVerify.value) {
directVerify.value = false;
}
} finally {
if (token === stockCheckToken) {
isStockChecking.value = false;
}
}
}
function scheduleStockPreview(): void {
if (!directVerify.value) {
return;
}
window.clearTimeout(stockPreviewTimer);
stockPreviewTimer = window.setTimeout(() => {
void refreshStockPreview();
}, 250);
}
watch(directVerify, async value => {
stockCheckToken += 1;
const token = stockCheckToken;
if (!value) {
isStockChecking.value = false;
return;
}
isStockChecking.value = true;
try {
if (!await validateDirectStock() && token === stockCheckToken && directVerify.value) {
directVerify.value = false;
}
} finally {
if (token === stockCheckToken) {
isStockChecking.value = false;
}
}
});
function handleBack(): void {
void router.back();
}
// ---------- 提交履约 ----------
async function save(): Promise<void> {
if (isSaving.value || isStockChecking.value || sourceOrderLoading.value) {
return;
}
if (!customerId.value) {
Message.warning("请先选择客户");
return;
}
const quantityComponent = fulfillmentQuantityRef.value;
const sourceOrdersComponent = sourceOrdersRef.value;
if (!quantityComponent || !sourceOrdersComponent) {
return;
}
if (!quantityComponent.validate() || !sourceOrdersComponent.validate()) {
return;
}
if (!buildAttachments().length) {
Message.warning("履约必须上传至少一张照片");
return;
}
if (!requestNo.value) {
requestNo.value = createPackageRequestNo();
}
isSaving.value = true;
try {
if (directVerify.value) {
isStockChecking.value = true;
const hasEnoughStock = await validateDirectStock(true);
isStockChecking.value = false;
if (!hasEnoughStock) {
directVerify.value = false;
return;
}
}
const sourceOrderIdList = sourceOrdersComponent.getSelectedOrderIdList();
const request = {
requestNo: requestNo.value,
customerId: customerId.value,
sourceOrderIdList,
itemList: quantityComponent.getRequestItemList(),
directVerify: directVerify.value,
deliveredAt: resolveTimestamp(deliveredAtText.value),
attachmentList: buildAttachments(),
remark: remark.value.trim() || null
};
const resultList = await FulfillmentAPI.quickCreate(request);
for (const orderId of sourceOrderIdList) {
emitListDataChanged(listDataEventKeys.salesOrderChanged, orderId);
}
emitListDataChanged(listDataEventKeys.productStockChanged);
Message.success(directVerify.value
? `快速履约并核销成功,共生成 ${resultList.length} 张履约单`
: `快速履约提交成功,共生成 ${resultList.length} 张履约单`);
await router.replace({ name: "OrderFulfillmentList", query: { customerId: customerId.value } });
} catch (error) {
Message.error(getErrorMessage(error, "快速履约提交失败,重试会复用同一请求号"));
} finally {
isSaving.value = false;
isStockChecking.value = false;
}
}
onMounted(async () => {
const queryCustomerId = Array.isArray(route.query.customerId) ? route.query.customerId[0] : route.query.customerId;
if (!queryCustomerId) {
return;
}
customerId.value = String(queryCustomerId);
try {
const customer = await CustomerAPI.detail(customerId.value);
selectedCustomer.value = customer;
await loadSkuList(customerId.value);
} catch (error) {
Message.error(getErrorMessage(error, "客户可履约 SKU 加载失败"));
}
});
onUnmounted(() => {
window.clearTimeout(stockPreviewTimer);
});
</script>
<style scoped lang="less">
.quick-fulfillment {
.content {
padding: calc(var(--app-nav-height) + .75rem) 0 2rem;
}
.nav-action {
color: var(--td-brand-color, #0052d9);
border: 0;
padding: .25rem .5rem;
font-size: .95rem;
background: transparent;
font-weight: 600;
&:disabled {
color: var(--td-text-color-disabled, #bbb);
}
}
.customer-profile {
margin: .75rem 1rem;
}
.time-actions {
gap: .5rem;
display: flex;
align-items: center;
justify-content: flex-end;
}
.stock-wrap {
}
}
</style>
@@ -0,0 +1,424 @@
<template>
<card-container class="items" description="履约数量和单位">
<template v-if="skuList.length">
<div v-for="sku in skuList" :key="sku.skuId" class="item">
<div class="item-content">
<div class="photo">
<t-image
v-if="getProductPhotoURL(sku)"
:src="getProductPhotoURL(sku)"
:alt="sku.productName || '产品图片'"
fit="cover"
class="avatar"
/>
<div v-else class="avatar fallback" v-text="(sku.productName || '产').slice(0, 1)" />
</div>
<div class="main">
<div class="header">
<div class="name-tag">
<strong v-text="sku.productName || '未命名产品'" />
<t-tag
v-if="sku.skuName !== sku.productName"
size="small"
theme="primary"
variant="light-outline"
:content="sku.skuName"
/>
</div>
<span class="can-fulfill" v-text="getSkuDescription(sku)" />
</div>
<div class="input">
<t-stepper
:model-value="quantityMap[sku.skuId]"
size="large"
:min="0"
:max="Number.MAX_SAFE_INTEGER"
:step="getQuantityStep(sku)"
:integer="!allowsDecimalQuantity(sku)"
theme="outline"
@update:model-value="value => updateQuantity(sku.skuId, value)"
/>
<t-button
class="unit"
size="extra-small"
variant="outline"
:content="getSelectedUnit(sku)?.name || '选择实际单位'"
@click.stop="openUnitPicker(sku)"
/>
<t-button
size="extra-small"
variant="outline"
:disabled="isStockChecking"
@click.stop="fillAllQuantity(sku)"
>全部履约</t-button>
</div>
</div>
</div>
</div>
</template>
<template v-else>
<center-tips content="请先选择产品 SKU" />
</template>
</card-container>
<t-popup v-model="unitPickerVisible" placement="bottom">
<t-picker
v-model="unitPickerDraft"
:columns="unitPickerOptions"
title="选择实际履约单位"
@cancel="unitPickerVisible = false"
@confirm="confirmUnitPicker"
/>
</t-popup>
</template>
<script setup lang="ts">
import ProductAPI from "@/api/ProductAPI";
import type { QuickFulfillmentCreateRequest, QuickFulfillmentSku, QuickFulfillmentSkuUnit } from "@/types/Fulfillment";
import type { ProductSku } from "@/types/Product";
import type { QuickFulfillmentItem, QuickFulfillmentQuantityExpose } from "./OrderFulfillmentQuickTypes";
import {
comparePackageQuantity,
convertPackageQuantity,
getPackageQuantityText,
normalizePackageQuantity,
toPackageBaseQuantity
} from "@/utils/package";
import { Message } from "@/utils/message";
import { getProductPhotoURL, getProductQuantityStep } from "@/utils/product";
import type { ProductStockRequirement } from "@/utils/productStock";
import { mergeProductStockRequirements } from "@/utils/productStock";
defineOptions({ name: "OrderFulfillmentQuickQuantity" });
const props = defineProps<{
skuList: QuickFulfillmentSku[];
isStockChecking?: boolean;
}>();
const emit = defineEmits<{
change: [itemList: QuickFulfillmentItem[]];
}>();
const quantityMap = reactive<Record<string, string | number>>({});
const unitIdMap = reactive<Record<string, string>>({});
const skuDetailMap = reactive<Record<string, ProductSku>>({});
const unitPickerVisible = ref(false);
const unitPickerSkuId = ref("");
const unitPickerDraft = ref<Array<string | number>>([]);
const selectedSkuIdList = computed(() => props.skuList.map(sku => sku.skuId));
const unitPickerOptions = computed(() => {
const sku = getSku(unitPickerSkuId.value);
return sku ? getUnitList(sku).map(unit => ({ label: unit.name, value: unit.id })) : [];
});
// ---------- SKU 和单位 ----------
function getSku(skuId: string): QuickFulfillmentSku | undefined {
return props.skuList.find(sku => sku.skuId === skuId);
}
function getSkuDisplayName(sku: QuickFulfillmentSku): string {
return [sku.productName, sku.skuName || sku.skuCode].filter(Boolean).join(" · ") || "未命名 SKU";
}
function getUnitList(sku: QuickFulfillmentSku): QuickFulfillmentSkuUnit[] {
return (sku.unitList || []).filter(unit => !!unit.id);
}
function getBaseUnit(sku: QuickFulfillmentSku): QuickFulfillmentSkuUnit | undefined {
return getUnitList(sku).find(unit => unit.isBase) || getUnitList(sku)[0];
}
function getBaseUnitName(sku: QuickFulfillmentSku): string {
return getBaseUnit(sku)?.name || "基础单位";
}
function getSelectedUnit(sku: QuickFulfillmentSku): QuickFulfillmentSkuUnit | undefined {
return getUnitList(sku).find(unit => unit.id === unitIdMap[sku.skuId]);
}
function allowsDecimalQuantity(sku: QuickFulfillmentSku): boolean {
return skuDetailMap[sku.skuId]?.allowDecimalQuantity ?? false;
}
function getQuantityStep(sku: QuickFulfillmentSku): number {
return getProductQuantityStep({ allowDecimalQuantity: allowsDecimalQuantity(sku) });
}
function getAvailableQuantity(sku: QuickFulfillmentSku): string {
const unit = getSelectedUnit(sku);
const quantity = convertPackageQuantity(sku.availableBaseQuantity, "1", unit?.baseQuantityPerUnit ?? "1");
return getPackageQuantityText(quantity ?? sku.availableBaseQuantity);
}
function getSkuDescription(sku: QuickFulfillmentSku): string {
return `可履约 ${getAvailableQuantity(sku)} ${getSelectedUnit(sku)?.name || getBaseUnitName(sku)}`;
}
function getRequiredBaseQuantity(sku: QuickFulfillmentSku): string | undefined {
const quantity = normalizePackageQuantity(quantityMap[sku.skuId] ?? "");
const unit = getSelectedUnit(sku);
return quantity && unit ? toPackageBaseQuantity(quantity, unit.baseQuantityPerUnit) : undefined;
}
function getItemList(): QuickFulfillmentItem[] {
return props.skuList.map(sku => {
const unit = getSelectedUnit(sku);
return {
sku,
skuUnitId: unit?.id || "",
quantity: normalizePackageQuantity(quantityMap[sku.skuId] ?? "") || "",
unitName: getBaseUnitName(sku),
requiredBaseQuantity: getRequiredBaseQuantity(sku)
};
});
}
function publishChange(): void {
emit("change", getItemList());
}
async function loadSkuDetail(skuId: string): Promise<void> {
if (skuDetailMap[skuId]) {
return;
}
try {
const skuDetail = await ProductAPI.skuDetail(skuId);
if (props.skuList.some(sku => sku.skuId === skuId)) {
skuDetailMap[skuId] = skuDetail;
}
} catch {
// SKU 列表已包含单位和库存字段,详情仅补充数量是否允许小数
}
}
watch(selectedSkuIdList, async (skuIdList, previousSkuIdList = []) => {
const selectedSkuIdSet = new Set(skuIdList);
const previousSkuIdSet = new Set(previousSkuIdList);
const addedSkuIdList: string[] = [];
for (const skuId of Object.keys(quantityMap)) {
if (selectedSkuIdSet.has(skuId)) {
continue;
}
delete quantityMap[skuId];
delete unitIdMap[skuId];
}
for (const sku of props.skuList) {
if (previousSkuIdSet.has(sku.skuId)) {
continue;
}
quantityMap[sku.skuId] = 0;
unitIdMap[sku.skuId] = getBaseUnit(sku)?.id || "";
addedSkuIdList.push(sku.skuId);
}
publishChange();
await Promise.all(addedSkuIdList.map(loadSkuDetail));
}, { immediate: true });
// ---------- 数量填写和单位换算 ----------
function updateQuantity(skuId: string, value: string | number): void {
quantityMap[skuId] = value;
publishChange();
}
/** 将不支持小数的 SKU 数量按四舍五入取整。 */
function roundQuantityToInteger(quantity: string): string {
const [integerPart, fractionPart = ""] = quantity.split(".");
if (!fractionPart || fractionPart[0] < "5") {
return integerPart;
}
return (BigInt(integerPart) + 1n).toString();
}
function fillAllQuantity(sku: QuickFulfillmentSku): void {
const unit = getSelectedUnit(sku);
if (!unit) {
Message.warning("请先选择实际履约单位");
return;
}
const quantity = convertPackageQuantity(sku.availableBaseQuantity, "1", unit.baseQuantityPerUnit);
if (!quantity) {
Message.warning("当前单位不能精确履约全部剩余权益,请填写可精确换算的数量");
return;
}
quantityMap[sku.skuId] = quantity;
publishChange();
}
function openUnitPicker(sku: QuickFulfillmentSku): void {
const unitList = getUnitList(sku);
if (!unitList.length) {
Message.warning(`${getSkuDisplayName(sku)} 没有可选履约单位`);
return;
}
unitPickerSkuId.value = sku.skuId;
unitPickerDraft.value = [unitIdMap[sku.skuId] || getBaseUnit(sku)?.id || ""];
unitPickerVisible.value = true;
}
function confirmUnitPicker(value: Array<string | number>): void {
const sku = getSku(unitPickerSkuId.value);
if (!sku) {
unitPickerVisible.value = false;
return;
}
const nextUnitId = String(value[0] || "");
const nextUnit = getUnitList(sku).find(unit => unit.id === nextUnitId);
if (!nextUnit) {
unitPickerVisible.value = false;
return;
}
const oldUnit = getSelectedUnit(sku);
const currentQuantity = normalizePackageQuantity(quantityMap[sku.skuId] ?? "");
if (currentQuantity && oldUnit?.id !== nextUnit.id) {
const converted = oldUnit
? convertPackageQuantity(currentQuantity, oldUnit.baseQuantityPerUnit, nextUnit.baseQuantityPerUnit)
: undefined;
if (converted === undefined) {
quantityMap[sku.skuId] = "";
Message.warning("当前数量不能精确换算到所选单位,请重新填写");
} else {
quantityMap[sku.skuId] = allowsDecimalQuantity(sku) ? converted : roundQuantityToInteger(converted);
}
}
unitIdMap[sku.skuId] = nextUnitId;
unitPickerVisible.value = false;
publishChange();
}
// ---------- 履约数据和校验 ----------
function validate(): boolean {
if (!props.skuList.length) {
Message.warning("请至少选择一个 SKU");
return false;
}
for (const sku of props.skuList) {
const quantity = normalizePackageQuantity(quantityMap[sku.skuId] ?? "");
const unit = getSelectedUnit(sku);
if (!quantity || !unit || !(0 < comparePackageQuantity(quantity, "0"))) {
Message.warning(`${getSkuDisplayName(sku)} 的履约数量必须大于 0`);
return false;
}
if (!allowsDecimalQuantity(sku) && quantity.includes(".")) {
Message.warning(`${getSkuDisplayName(sku)} 不支持小数数量`);
return false;
}
const baseQuantity = toPackageBaseQuantity(quantity, unit.baseQuantityPerUnit);
if (!baseQuantity) {
Message.warning(`${getSkuDisplayName(sku)} 换算基础单位后最多只能保留三位小数`);
return false;
}
if (0 < comparePackageQuantity(baseQuantity, sku.availableBaseQuantity)) {
Message.warning(`${getSkuDisplayName(sku)} 的可履约数量不足`);
return false;
}
}
return true;
}
function getRequestItemList(): QuickFulfillmentCreateRequest["itemList"] {
return props.skuList.flatMap(sku => {
const unit = getSelectedUnit(sku);
const quantity = normalizePackageQuantity(quantityMap[sku.skuId] ?? "");
return unit && quantity ? [{ skuId: sku.skuId, skuUnitId: unit.id, quantity }] : [];
});
}
function buildStockRequirements(): ProductStockRequirement[] {
return mergeProductStockRequirements(props.skuList.flatMap(sku => {
const baseQuantity = getRequiredBaseQuantity(sku);
if (!sku.stockEnabled || !baseQuantity) {
return [];
}
return [{
skuId: sku.skuId,
baseQuantity,
productName: sku.productName || getSkuDisplayName(sku),
unitName: getBaseUnitName(sku),
stockEnabled: sku.stockEnabled
}];
}));
}
defineExpose<QuickFulfillmentQuantityExpose>({ validate, getRequestItemList, buildStockRequirements });
</script>
<style scoped lang="less">
.items {
.item {
padding: .625rem;
min-width: 0;
.item-content {
gap: .5rem;
flex: 1 1 auto;
width: 100%;
display: flex;
min-width: 0;
.photo {
gap: .5rem;
display: flex;
.avatar {
width: 3.5rem;
height: 3.5rem;
}
}
.main {
flex: 1;
display: flex;
min-width: 0;
flex-direction: column;
justify-content: space-between;
.header {
gap: .5rem;
display: flex;
min-width: 0;
align-items: baseline;
justify-content: space-between;
.name-tag {
gap: .5rem;
flex: 1 1 0;
display: flex;
overflow: hidden;
min-width: 0;
align-items: center;
justify-content: start;
strong {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.can-fulfill {
color: var(--td-text-color-secondary);
font-size: .75rem;
white-space: nowrap;
}
}
.input {
gap: .5rem;
display: flex;
min-width: 0;
align-items: center;
justify-content: end;
.unit {
font-size: .875rem;
max-width: 38%;
}
}
}
}
}
}
</style>
@@ -0,0 +1,436 @@
<template>
<t-cell-group
v-if="sourceOrderList.length"
title="选择赴约订单"
class="source-order-list empty-cell-title-margin"
theme="card"
>
<t-cell
v-for="order in sourceOrderList"
:key="order.id"
class="source-order-cell"
:class="{ selected: selectedSourceOrderIdList.includes(order.id) }"
@click="setSourceOrderSelected(order.id, !selectedSourceOrderIdList.includes(order.id))"
>
<template #title>
<div class="header">
<div class="check" @click.stop>
<t-checkbox
:model-value="selectedSourceOrderIdList.includes(order.id)"
:aria-label="`选择订单${order.orderNo || order.id}`"
borderless
@update:model-value="checked => setSourceOrderSelected(order.id, Boolean(checked))"
/>
</div>
<div class="main">
<div class="title">
<t-tag
size="small"
:theme="order.orderType === 'PACKAGE' ? 'warning' : 'primary'"
variant="light"
:content="getSalesOrderTypeText(order.orderType)"
/>
<strong v-if="order.orderType === 'PACKAGE'" class="package-name" v-text="order.packageName || '未命名套餐'" />
</div>
</div>
<span class="red text-bold keep-text" v-text="`¥${formatPackageAmount(order.saleAmount)}`" />
</div>
</template>
<template #description>
<div class="description">
<div class="row">
<span class="label">订单号</span>
<span class="value" v-text="order.orderNo || order.id" />
</div>
<div class="row">
<span class="label">时间</span>
<div>
<pass-time-label
v-if="toTimestamp(order.createdAt)"
class="value"
:timestamp="toTimestamp(order.createdAt)"
underline
/>
</div>
</div>
<div class="row payment">
<span class="label">收款</span>
<div class="tags">
<t-tag
v-if="order.paymentStatus === 'PAID'"
size="small"
theme="success"
variant="light"
:content="'已全额收款 ¥' + formatPackageAmount(order.paidAmount)"
/>
<template v-else>
<t-tag
size="small"
theme="success"
variant="light"
:content="'已收 ¥' + formatPackageAmount(order.paidAmount)"
/>
<t-tag
size="small"
theme="warning"
variant="light"
:content="'待收 ¥' + formatPackageAmount(order.unpaidAmount)"
/>
</template>
</div>
</div>
<div class="row available" @click.stop>
<span class="label">可履约</span>
<div v-if="getAvailableFulfillmentItemList(order).length" class="tags">
<t-tag
v-for="item in getAvailableFulfillmentItemList(order)"
:key="item.id"
size="small"
theme="primary"
variant="light-outline"
:content="getSourceOrderItemTagText(item)"
/>
</div>
<span v-else class="empty">暂无</span>
</div>
</div>
</template>
</t-cell>
</t-cell-group>
<card-container description="来源池数量校验">
<div class="coverage-table">
<t-table
v-if="fulfillmentItemList.length && !loadingSourceOrders"
class="table"
:columns="coverageColumns"
:data="coverageList"
row-key="skuId"
table-layout="fixed"
vertical-align="middle"
>
<template #product="{ row }">
<div class="product">
<span v-text="row.productName" />
<t-tag
v-if="row.sku.skuName !== row.productName"
size="small"
theme="primary"
variant="light-outline"
:content="row.sku.skuName"
/>
</div>
</template>
<template #source="{ row }">
<span v-text="row.poolBaseQuantity + ' ' + row.unitName" />
</template>
<template #required="{ row }">
<span :class="row.sufficient ? 'covered' : 'short'" v-text="row.requiredBaseQuantity + ' ' + row.unitName" />
</template>
</t-table>
<center-tips v-else :content="loadingSourceOrders ? '正在加载来源订单' : '请先选择产品 SKU'" />
</div>
</card-container>
</template>
<script setup lang="ts">
import { PassTimeLabel } from "timi-web";
import FulfillmentAPI from "@/api/FulfillmentAPI";
import type { QuickFulfillmentSku, QuickFulfillmentSourceOrder, QuickFulfillmentSourceOrderItem } from "@/types/Fulfillment";
import type { QuickFulfillmentItem, QuickFulfillmentSourceOrdersExpose } from "./OrderFulfillmentQuickTypes";
import { addPackageQuantity, comparePackageQuantity, formatPackageAmount, getPackageQuantityText } from "@/utils/package";
import { getProductSkuSnapshotText } from "@/utils/product";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { getSalesOrderTypeText } from "@/utils/salesOrder";
defineOptions({ name: "OrderFulfillmentQuickSourceOrders" });
const props = defineProps<{
customerId: string;
fulfillmentItemList: QuickFulfillmentItem[];
}>();
const emit = defineEmits<{
"loading-change": [loading: boolean];
}>();
const fulfillmentItemList = computed(() => props.fulfillmentItemList);
const sourceSkuIdList = computed(() => props.fulfillmentItemList.map(item => item.sku.skuId));
const sourceSkuIdKey = computed(() => JSON.stringify(sourceSkuIdList.value));
const sourceOrderList = ref<QuickFulfillmentSourceOrder[]>([]);
const selectedSourceOrderIdList = ref<string[]>([]);
const loadingSourceOrders = ref(false);
const coverageColumns = [
{ colKey: "product", title: "产品名", width: "40%", ellipsis: true },
{ colKey: "source", title: "来源", width: "30%", align: "right" },
{ colKey: "required", title: "需要", width: "30%", align: "right" }
];
const coverageList = computed(() => props.fulfillmentItemList.map(item => {
const requiredBaseQuantity = item.requiredBaseQuantity || "0";
const poolBaseQuantity = getSelectedPoolBaseQuantity(item.sku.skuId);
return {
skuId: item.sku.skuId,
productName: item.sku.productName || "未命名产品",
unitName: item.unitName,
requiredBaseQuantity,
poolBaseQuantity,
sufficient: 0 <= comparePackageQuantity(poolBaseQuantity, requiredBaseQuantity),
sku: item.sku
};
}));
let sourceOrderLoadToken = 0;
let currentCustomerId = props.customerId;
// ---------- 赴约订单加载和选择 ----------
function setLoading(value: boolean): void {
if (loadingSourceOrders.value === value) {
return;
}
loadingSourceOrders.value = value;
emit("loading-change", value);
}
function toTimestamp(value?: number | string): number {
if (value === undefined || value === null || value === "") {
return 0;
}
const numericValue = Number(value);
if (Number.isFinite(numericValue)) {
return numericValue;
}
const timestamp = new Date(String(value)).getTime();
return Number.isFinite(timestamp) ? timestamp : 0;
}
function getSelectedPoolBaseQuantity(skuId: string): string {
let total = "0";
const selectedOrderSet = new Set(selectedSourceOrderIdList.value);
for (const order of sourceOrderList.value) {
if (!selectedOrderSet.has(order.id)) {
continue;
}
for (const item of order.itemList || []) {
if (item.skuId !== skuId) {
continue;
}
total = addPackageQuantity(total, item.availableBaseQuantity) || total;
}
}
return total;
}
function getAvailableFulfillmentItemList(order: QuickFulfillmentSourceOrder): QuickFulfillmentSourceOrderItem[] {
return (order.itemList || []).filter(item => 0 < comparePackageQuantity(item.availableBaseQuantity, "0"));
}
function getSourceOrderItemTagText(item: QuickFulfillmentSourceOrderItem): string {
const fulfillmentItem = fulfillmentItemList.value.find(currentItem => currentItem.sku.skuId === item.skuId);
const productName = item.productNameSnapshot || fulfillmentItem?.sku.productName || "未命名产品";
const skuName = item.skuNameSnapshot || fulfillmentItem?.sku.skuName || fulfillmentItem?.sku.skuCode;
const skuText = getProductSkuSnapshotText(productName, skuName);
const productSkuText = skuText ? `${productName} · ${skuText}` : productName;
return `${productSkuText} × ${getPackageQuantityText(item.availableBaseQuantity)}`;
}
function getSkuDisplayName(sku: QuickFulfillmentSku): string {
return [sku.productName, sku.skuName || sku.skuCode].filter(Boolean).join(" · ") || "未命名 SKU";
}
async function loadSourceOrders(): Promise<void> {
const requestToken = ++sourceOrderLoadToken;
const customerChanged = currentCustomerId !== props.customerId;
const previousSelection = customerChanged ? new Set<string>() : new Set(selectedSourceOrderIdList.value);
currentCustomerId = props.customerId;
const skuIdList = [...sourceSkuIdList.value];
if (!props.customerId || !skuIdList.length) {
sourceOrderList.value = [];
selectedSourceOrderIdList.value = [];
setLoading(false);
return;
}
sourceOrderList.value = [];
setLoading(true);
try {
const orderList = await FulfillmentAPI.quickSourceOrderList(props.customerId, skuIdList);
if (requestToken !== sourceOrderLoadToken) {
return;
}
sourceOrderList.value = [...orderList].sort((left, right) => toTimestamp(left.createdAt) - toTimestamp(right.createdAt));
const availableIdSet = new Set(sourceOrderList.value.map(order => order.id));
selectedSourceOrderIdList.value = [...previousSelection].filter(id => availableIdSet.has(id));
if (!orderList.length) {
Message.warning("当前 SKU 没有可选赴约订单");
}
} catch (error) {
if (requestToken === sourceOrderLoadToken) {
Message.error(getErrorMessage(error, "可选订单加载失败"));
}
} finally {
if (requestToken === sourceOrderLoadToken) {
setLoading(false);
}
}
}
function setSourceOrderSelected(orderId: string, checked: boolean): void {
if (checked && !selectedSourceOrderIdList.value.includes(orderId)) {
selectedSourceOrderIdList.value = [...selectedSourceOrderIdList.value, orderId];
return;
}
if (!checked) {
selectedSourceOrderIdList.value = selectedSourceOrderIdList.value.filter(id => id !== orderId);
}
}
watch([() => props.customerId, sourceSkuIdKey], async () => {
await loadSourceOrders();
}, { immediate: true });
// ---------- 履约来源校验 ----------
function validate(): boolean {
if (!selectedSourceOrderIdList.value.length) {
Message.warning("请至少选择一个赴约订单");
return false;
}
for (const coverage of coverageList.value) {
if (!coverage.sufficient) {
Message.warning(`${getSkuDisplayName(coverage.sku)} 的所选订单可履约数量不足`);
return false;
}
}
return true;
}
function getSelectedOrderIdList(): string[] {
return [...selectedSourceOrderIdList.value];
}
defineExpose<QuickFulfillmentSourceOrdersExpose>({ validate, getSelectedOrderIdList });
onUnmounted(() => {
sourceOrderLoadToken += 1;
});
</script>
<style scoped lang="less">
.source-order-cell {
--td-checkbox-vertical-padding: 0;
:deep(.t-checkbox__icon) {
margin: 0;
display: flex;
align-items: center;
}
.header {
gap: .5rem;
flex: 1;
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
.main {
flex: 1;
min-width: 0;
.title {
gap: .5rem;
display: flex;
min-width: 0;
align-items: center;
.package-name {
flex: 1;
overflow: hidden;
font-size: .875rem;
min-width: 0;
white-space: nowrap;
text-overflow: ellipsis;
}
}
}
}
.description {
width: 100%;
display: flex;
flex-direction: column;
.row {
gap: .5rem;
display: grid;
font-size: .75rem;
min-width: 0;
align-items: center;
grid-template-columns: 3rem minmax(0, 1fr);
&.available {
.tags {
min-width: 0;
flex-wrap: nowrap;
overflow-x: auto;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
:deep(.t-tag) {
flex: none;
white-space: nowrap;
}
}
}
&.payment {
.tags {
gap: .375rem;
display: flex;
min-width: 0;
flex-wrap: wrap;
}
}
.label {
color: var(--td-text-color-secondary);
}
.value {
color: var(--td-text-color-primary);
min-width: 0;
overflow-wrap: anywhere;
}
}
}
}
.coverage-table {
--td-component-border: transparent;
padding: .25rem .5rem;
:deep(th),
:deep(td) {
padding: .25rem .5rem;
}
.product {
gap: .5rem;
display: flex;
align-items: center;
justify-content: start;
}
.covered {
color: var(--td-success-color, #00a870);
}
.short {
color: var(--td-warning-color);
}
}
</style>
@@ -0,0 +1,21 @@
import type { QuickFulfillmentCreateRequest, QuickFulfillmentSku } from "@/types/Fulfillment";
import type { ProductStockRequirement } from "@/utils/productStock";
export type QuickFulfillmentItem = {
sku: QuickFulfillmentSku;
skuUnitId: string;
quantity: string;
unitName: string;
requiredBaseQuantity?: string;
};
export type QuickFulfillmentQuantityExpose = {
validate: () => boolean;
getRequestItemList: () => QuickFulfillmentCreateRequest["itemList"];
buildStockRequirements: () => ProductStockRequirement[];
};
export type QuickFulfillmentSourceOrdersExpose = {
validate: () => boolean;
getSelectedOrderIdList: () => string[];
};
+13 -7
View File
@@ -58,7 +58,7 @@
>
<t-button
class="item"
:class="{ quick: item.path === '/customer/quick-sign-in' }"
:class="{ quick: item.path === '/customer/quick-sign-in' || item.path === '/management/order-fulfillments/quick' }"
variant="text"
@click="router.push(item.path)"
>
@@ -188,12 +188,6 @@ const entryGroupList: HomeEntryGroup[] = [
{
title: "订单管理",
entryList: [
{
path: "/management/sales-orders",
permission: permissionCodes.salesOrder.read,
icon: "task",
title: "订单列表"
},
{
path: "/management/sales-orders/create",
permission: permissionCodes.salesOrder.create,
@@ -206,6 +200,18 @@ const entryGroupList: HomeEntryGroup[] = [
icon: "layers",
title: "创建套餐订单"
},
{
path: "/management/order-fulfillments/quick",
permission: permissionCodes.orderFulfillment.create,
icon: "undertake-delivery",
title: "快速履约"
},
{
path: "/management/sales-orders",
permission: permissionCodes.salesOrder.read,
icon: "task",
title: "订单列表"
},
{
path: "/management/points/redemptions",
permission: permissionCodes.pointRedemption.create,