add ProductStockBatchSelect.vue

This commit is contained in:
Timi
2026-10-15 15:29:56 +08:00
parent d8ac19baa7
commit a5ac6c5e69
14 changed files with 1605 additions and 352 deletions
+6
View File
@@ -12,6 +12,7 @@ import type {
ProductStockBatchRequest,
ProductStockProduct,
ProductStockChangeRequest,
ProductStockManualInBatchRequest,
ProductStockManualRevokeRequest,
ProductStockPage,
StockRecord,
@@ -132,6 +133,10 @@ async function manualIn(request: ProductStockChangeRequest): Promise<ProductStoc
return await axios.post(`${STOCK_URI}/manual-in`, withCurrentStoreId(request));
}
async function manualInBatch(request: ProductStockManualInBatchRequest): Promise<ProductStock[]> {
return await axios.post(`${STOCK_URI}/manual-in/batch`, withCurrentStoreId(request));
}
async function manualOut(request: ProductStockChangeRequest): Promise<ProductStock> {
return await axios.post(`${STOCK_URI}/manual-out`, withCurrentStoreId(request));
}
@@ -184,6 +189,7 @@ export default {
stockBatchDetail,
initialIn,
manualIn,
manualInBatch,
manualOut,
manualRevoke,
stocktakeGain,
-349
View File
@@ -1,349 +0,0 @@
<template>
<t-form-item
class="product-selector"
:label="props.label"
:required-mark="props.requiredMark"
content-align="right"
arrow
@click="open"
>
<span class="picker-text" v-text="selectedProductName || props.placeholder" />
</t-form-item>
<product-sku-form-item :sku="selectedSku" :unit="selectedUnit" />
<bottom-popup
v-model="visible"
title="选择产品 SKU"
height="80vh"
right-button-text=""
@left-button-click="close"
>
<div class="popup">
<div class="search-wrap">
<t-input v-model="keyword" class="search" borderless placeholder="搜索产品名称或编码" />
</div>
<div class="items">
<t-collapse
v-if="visibleProductList.length"
v-model="expandedProductKeyList"
class="collapse"
theme="card"
:expand-mutex="true"
@change="handleProductChange"
>
<t-collapse-panel
class="item"
v-for="(product, productIndex) in visibleProductList"
:key="getProductKey(product, productIndex)"
:value="getProductKey(product, productIndex)"
placement="bottom"
>
<template #header>
<div class="header">
<t-image
v-if="getProductPhotoURL(product)"
:src="getProductPhotoURL(product)"
:alt="product.name || '产品图片'"
fit="cover"
class="avatar"
/>
<div v-else class="avatar fallback" v-text="(product.name || product.code || '产').slice(0, 1)" />
<strong class="clip-text" v-text="product.name || '未命名产品'" />
</div>
</template>
<div v-if="isExpandedProduct(product, productIndex)" class="selection">
<div v-if="specList.length" class="specs">
<div v-for="spec in specList" :key="spec.id || spec.name" class="spec">
<strong v-text="spec.name" />
<div class="values">
<t-button
v-for="value in enabledValues(spec)"
:key="value.id"
size="extra-small"
:theme="selectedSpecValueMap[spec.id || ''] === value.id ? 'primary' : 'default'"
:variant="selectedSpecValueMap[spec.id || ''] === value.id ? 'base' : 'outline'"
:content="value.name"
@click="selectSpecValue(spec.id || '', value.id || '')"
/>
</div>
</div>
</div>
<div v-if="matchedSku" class="sku-card">
<div class="units">
<t-button
v-for="unit in saleableUnits(matchedSku)"
:key="unit.id"
size="small"
:theme="props.modelValue?.skuId === matchedSku.id && props.modelValue?.skuUnitId === unit.id ? 'primary' : 'default'"
:variant="props.modelValue?.skuId === matchedSku.id && props.modelValue?.skuUnitId === unit.id ? 'base' : 'outline'"
@click="selectUnit(matchedSku, unit.id || '')"
>
<span v-text="unit.name" />
<span v-if="unit.salePrice !== null && unit.salePrice !== undefined" class="price" v-text="`¥${formatProductAmount(unit.salePrice)}`" />
</t-button>
</div>
</div>
<div v-else class="empty" v-text="specList.length ? '请选择每个规格项的规格值' : '暂无可售 SKU'" />
</div>
</t-collapse-panel>
</t-collapse>
<div v-else class="empty" v-text="loading ? '正在加载可售产品' : '暂无可售产品'" />
</div>
</div>
</bottom-popup>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import ProductAPI from "@/api/ProductAPI";
import ProductSkuFormItem from "@/components/ProductSkuFormItem.vue";
import type {
Product,
ProductSelection,
ProductSku,
ProductSkuUnit,
ProductSpec,
ProductSpecValue
} from "@/types/Product";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { formatProductAmount, getProductPhotoURL } from "@/utils/product";
interface Props {
modelValue: { skuId: string; skuUnitId: string } | undefined;
selectedProduct?: Product;
label?: string;
requiredMark?: boolean;
placeholder?: string;
}
const props = withDefaults(defineProps<Props>(), { label: "产品", requiredMark: false, placeholder: "请选择产品 SKU" });
const emit = defineEmits<{
"update:modelValue": [value: Props["modelValue"]];
select: [selection: ProductSelection];
}>();
const visible = ref(false);
const loading = ref(false);
const keyword = ref("");
const productList = ref<Product[]>([]);
const activeProduct = ref<Product>();
const expandedProductKeyList = ref<Array<string | number>>([]);
const selectedSpecValueMap = reactive<Record<string, string>>({});
const selectedProduct = computed(() => {
if (!props.modelValue?.skuId) {
return undefined;
}
return props.selectedProduct || productList.value.find(item => item.skuList?.some(sku => sku.id === props.modelValue?.skuId));
});
const selectedProductName = computed(() => selectedProduct.value?.name || "");
const selectedSku = computed(() => selectedProduct.value?.skuList?.find(sku => sku.id === props.modelValue?.skuId));
const selectedUnit = computed(() => selectedSku.value?.unitList?.find(unit => unit.id === props.modelValue?.skuUnitId));
const filteredProductList = computed(() => {
const text = keyword.value.toLocaleLowerCase();
return productList.value.filter(item => !text || `${item.name}${item.code}`.toLocaleLowerCase().includes(text));
});
const visibleProductList = computed(() => filteredProductList.value);
const specList = computed(() => activeProduct.value?.specList || []);
const matchedSku = computed(() => {
const product = activeProduct.value;
if (!product) {
return undefined;
}
return (product.skuList || []).find(sku => specList.value.every(spec => sku.specValueIdList?.includes(selectedSpecValueMap[spec.id || ""] || "")));
});
async function open(): Promise<void> {
visible.value = true;
activeProduct.value = undefined;
expandedProductKeyList.value = [];
if (productList.value.length) {
return;
}
loading.value = true;
try {
productList.value = await ProductAPI.sellableList({ index: 0, size: 1000 });
} catch (error) {
Message.error(getErrorMessage(error, "可售产品加载失败"));
} finally {
loading.value = false;
}
}
function close(): void {
visible.value = false;
activeProduct.value = undefined;
expandedProductKeyList.value = [];
}
function enabledValues(spec: ProductSpec): ProductSpecValue[] {
return (spec.valueList || []).filter(value => value.enabled !== false && value.id);
}
function saleableUnits(sku: ProductSku): ProductSkuUnit[] {
return (sku.unitList || []).filter(unit => unit.allowSale !== false && unit.id);
}
function getProductKey(product: Product, index: number): string {
return product.id || product.code || `product-${index}`;
}
function isExpandedProduct(product: Product, index: number): boolean {
return expandedProductKeyList.value.includes(getProductKey(product, index));
}
function handleProductChange(value: Array<string | number>): void {
const productIndex = visibleProductList.value.findIndex((product, index) => getProductKey(product, index) === value[0]);
const product = visibleProductList.value[productIndex];
if (product) {
selectProduct(product);
return;
}
activeProduct.value = undefined;
}
function selectProduct(product: Product): void {
activeProduct.value = product;
Object.keys(selectedSpecValueMap).forEach(key => delete selectedSpecValueMap[key]);
const selectedSku = product.skuList?.find(sku => sku.id === props.modelValue?.skuId);
for (const spec of product.specList || []) {
const valueId = selectedSku?.specValueIdList?.find(id => (spec.valueList || []).some(value => value.id === id))
|| enabledValues(spec)[0]?.id;
if (spec.id && valueId) {
selectedSpecValueMap[spec.id] = valueId;
}
}
}
function selectSpecValue(specId: string, valueId: string): void {
if (specId && valueId) {
selectedSpecValueMap[specId] = valueId;
}
}
function selectUnit(sku: ProductSku, skuUnitId: string): void {
if (!sku.id || !skuUnitId) {
return;
}
const product = activeProduct.value;
const unit = sku.unitList?.find(item => item.id === skuUnitId);
if (product && unit) {
emit("select", { product, sku, unit });
}
emit("update:modelValue", { skuId: sku.id, skuUnitId });
close();
}
</script>
<style scoped lang="less">
.product-selector {
.picker-text {
color: var(--td-text-color-primary);
}
}
.popup {
height: 100%;
padding: 1rem 0;
display: flex;
overflow: hidden;
min-height: 0;
flex-direction: column;
.search-wrap {
z-index: 1;
padding: 0 0 .75rem;
.search {
--td-input-vertical-padding: 8px 14px;
margin: 0 1rem;
border: 1px solid var(--td-component-border);
border-radius: .875rem;
}
}
.items {
flex: 1;
min-height: 0;
overflow-y: auto;
padding-bottom: env(safe-area-inset-bottom, 0);
.collapse {
margin: 0;
.item {
--td-collapse-content-padding: .25rem 1rem .75rem 1rem;
.header {
gap: .75rem;
display: flex;
min-width: 0;
align-items: center;
.avatar {
flex: 0 0 auto;
width: 2.5rem;
height: 2.5rem;
border-radius: .75rem !important;
}
}
.selection {
overflow-y: auto;
.specs {
gap: .5rem;
display: flex;
flex-direction: column;
.spec {
gap: .5rem;
display: flex;
flex-direction: column;
.values,
.units {
gap: .5rem;
display: flex;
flex-wrap: wrap;
}
}
}
.sku-card {
padding: .5rem;
border: 1px dashed var(--td-brand-color);
margin-top: .5rem;
border-radius: .875rem;
.units {
gap: .5rem;
display: flex;
flex-wrap: wrap;
.price {
margin-left: .25rem;
font-size: .75rem;
}
}
}
}
}
}
}
.empty {
color: var(--td-text-color-secondary);
padding: 2rem 1rem;
text-align: center;
}
}
:deep(.avatar .t-image__img) {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: inherit;
}
</style>
@@ -0,0 +1,174 @@
<template>
<t-form-item
class="product-selector"
:label="props.label"
:required-mark="props.requiredMark"
content-align="right"
arrow
@click="open"
>
<span class="picker-text" v-text="selectedProductName || props.placeholder" />
</t-form-item>
<product-sku-form-item :sku="selectedSku" :unit="selectedUnit" />
<bottom-popup
v-model="visible"
title="选择产品 SKU"
height="80vh"
right-button-text=""
@left-button-click="close"
>
<div class="popup">
<div class="search-wrap">
<t-input v-model="keyword" class="search" borderless placeholder="搜索产品名称或编码" />
</div>
<div class="items">
<product-sku-selector
v-if="selectorItemList.length"
v-model:expanded-product-key-list="expandedProductKeyList"
:items="selectorItemList"
:selected-sku-id-list="selectedSkuIdList"
:selected-unit-id="props.modelValue?.skuUnitId"
@select="selectUnit"
/>
<div v-else class="empty" v-text="loading ? '正在加载可售产品' : '暂无可售产品'" />
</div>
</div>
</bottom-popup>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import ProductAPI from "@/api/ProductAPI";
import type { Product, ProductSelection } from "@/types/Product";
import type { ProductSkuSelectionValue, ProductSkuSelectorItem } from "@/types/ProductSkuSelection";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { getProductPhotoURL } from "@/utils/product";
interface Props {
modelValue: ProductSkuSelectionValue | undefined;
selectedProduct?: Product;
label?: string;
requiredMark?: boolean;
placeholder?: string;
}
const props = withDefaults(defineProps<Props>(), { label: "产品", requiredMark: false, placeholder: "请选择产品 SKU" });
const emit = defineEmits<{
"update:modelValue": [value: Props["modelValue"]];
select: [selection: ProductSelection];
}>();
// ---------- 表单回显 ----------
const productList = ref<Product[]>([]);
const selectedProduct = computed(() => {
const skuId = props.modelValue?.skuId;
if (!skuId) {
return undefined;
}
if (props.selectedProduct?.skuList?.some(sku => sku.id === skuId)) {
return props.selectedProduct;
}
return productList.value.find(product => product.skuList?.some(sku => sku.id === skuId));
});
const selectedProductName = computed(() => selectedProduct.value?.name || "");
const selectedSku = computed(() => selectedProduct.value?.skuList?.find(sku => sku.id === props.modelValue?.skuId));
const selectedUnit = computed(() => selectedSku.value?.unitList?.find(unit => unit.id === props.modelValue?.skuUnitId));
const selectedSkuIdList = computed(() => props.modelValue?.skuId ? [props.modelValue.skuId] : []);
// ---------- 弹窗与产品列表 ----------
const visible = ref(false);
const loading = ref(false);
const keyword = ref("");
const expandedProductKeyList = ref<Array<string | number>>([]);
const visibleProductList = computed(() => {
const text = keyword.value.trim().toLocaleLowerCase();
return productList.value.filter(item => !text || `${item.name}${item.code}`.toLocaleLowerCase().includes(text));
});
const selectorItemList = computed<ProductSkuSelectorItem[]>(() => visibleProductList.value.map((product, index) => ({
key: getProductKey(product, index),
name: product.name || product.code || "未命名产品",
photoUrl: getProductPhotoURL(product),
product
})));
async function open(): Promise<void> {
visible.value = true;
expandedProductKeyList.value = [];
if (loading.value || productList.value.length) {
return;
}
loading.value = true;
try {
productList.value = await ProductAPI.sellableList({ index: 0, size: 1000 });
} catch (error) {
Message.error(getErrorMessage(error, "可售产品加载失败"));
} finally {
loading.value = false;
}
}
function close(): void {
visible.value = false;
expandedProductKeyList.value = [];
}
function getProductKey(product: Product, index: number): string {
return product.id || product.code || `product-${index}`;
}
function selectUnit(selection: ProductSelection): void {
if (!selection.sku.id || !selection.unit.id) {
return;
}
emit("select", selection);
emit("update:modelValue", { skuId: selection.sku.id, skuUnitId: selection.unit.id });
close();
}
</script>
<style scoped lang="less">
.product-selector {
.picker-text {
color: var(--td-text-color-primary);
}
}
.popup {
height: 100%;
display: flex;
padding: 1rem 0;
overflow: hidden;
min-height: 0;
flex-direction: column;
.search-wrap {
z-index: 1;
padding: 0 0 .75rem;
.search {
--td-input-vertical-padding: .5rem .875rem;
margin: 0 1rem;
border: .0625rem solid var(--td-component-border);
border-radius: .875rem;
}
}
.items {
flex: 1;
min-height: 0;
overflow-y: auto;
padding-bottom: env(safe-area-inset-bottom, 0);
}
.empty {
color: var(--td-text-color-secondary);
padding: 2rem 1rem;
text-align: center;
}
}
</style>
@@ -0,0 +1,284 @@
<template>
<div class="product-sku-selector">
<div v-if="specList.length && selectableSkuList.length" class="specs">
<div v-for="spec in specList" :key="spec.id || spec.name" class="spec">
<strong v-text="spec.name" />
<div class="values">
<t-button
v-for="value in enabledValues(spec)"
:key="value.id"
size="extra-small"
:theme="isSelectedSpecValue(spec.id || '', value.id || '') ? 'primary' : 'default'"
:variant="isSelectedSpecValue(spec.id || '', value.id || '') ? 'base' : 'outline'"
:content="value.name"
@click="selectSpecValue(spec.id || '', value.id || '')"
/>
</div>
</div>
</div>
<template v-if="isMultiple">
<t-cell-group v-if="!specList.length && selectableSkuList.length" theme="card" class="sku-list">
<t-cell
v-for="sku in selectableSkuList"
:key="sku.id"
:title="sku.name || '未命名 SKU'"
:description="getSkuNote(sku)"
@click="toggleSku(sku)"
>
<template #leftIcon>
<t-checkbox
:model-value="isSelectedSku(sku)"
borderless
@click.stop
@change="toggleSku(sku)"
/>
</template>
</t-cell>
</t-cell-group>
<div v-else-if="!selectableSkuList.length || isSpecSelectionComplete && !matchedSkuList.length" class="empty" v-text="multipleEmptyText" />
</template>
<template v-else>
<div v-if="matchedSku" class="sku-card">
<div class="units">
<t-button
v-for="unit in saleableUnits(matchedSku)"
:key="unit.id"
size="small"
:theme="isSelectedUnit(matchedSku, unit) ? 'primary' : 'default'"
:variant="isSelectedUnit(matchedSku, unit) ? 'base' : 'outline'"
@click="selectUnit(matchedSku, unit)"
>
<span v-text="unit.name" />
<span v-if="unit.salePrice !== null && unit.salePrice !== undefined" class="price" v-text="`¥${formatProductAmount(unit.salePrice)}`" />
</t-button>
</div>
</div>
<div v-else class="empty" v-text="specList.length && selectableSkuList.length ? '请选择每个规格项的规格值' : '暂无可售 SKU'" />
</template>
</div>
</template>
<script setup lang="ts">
import type { Product, ProductSelection, ProductSku, ProductSkuUnit, ProductSpec, ProductSpecValue } from "@/types/Product";
import type { ProductSkuSelectionMode } from "@/types/ProductSkuSelection";
import { formatProductAmount } from "@/utils/product";
interface Props {
product: Product;
/** 多选时可传入已过滤的 SKU 列表。 */
skuList?: ProductSku[];
selectedSkuIdList: string[];
selectedUnitId?: string;
selectionMode?: ProductSkuSelectionMode;
emptyText?: string;
}
const props = withDefaults(defineProps<Props>(), { selectionMode: "single", emptyText: "暂无可选 SKU" });
const emit = defineEmits<{
select: [selection: ProductSelection];
toggle: [sku: ProductSku];
}>();
// ---------- SKU 多选 ----------
const isMultiple = computed(() => props.selectionMode === "multiple");
const selectableSkuList = computed(() => (props.skuList || props.product.skuList || [])
.filter(sku => sku.status === "ACTIVE"));
function getSkuNote(sku: ProductSku): string {
return [sku.code, sku.specSummary].filter(Boolean).join(" · ");
}
function isSelectedSku(sku: ProductSku): boolean {
return !!sku.id && props.selectedSkuIdList.includes(sku.id);
}
function toggleSku(sku: ProductSku): void {
if (isMultiple.value && sku.id) {
emit("toggle", sku);
}
}
// ---------- 规格和销售单位单选 ----------
const selectedSpecValueMap = reactive<Record<string, string>>({});
const selectedSpecValueIdMap = reactive<Record<string, string[]>>({});
const specList = computed(() => props.product.specList || []);
const isSpecSelectionComplete = computed(() => specList.value.every(spec => !!spec.id && !!selectedSpecValueIdMap[spec.id]?.length));
const multipleEmptyText = computed(() => {
if (!specList.value.length || !selectableSkuList.value.length) {
return props.emptyText;
}
return isSpecSelectionComplete.value ? "当前规格组合暂无可选 SKU" : "请为每个规格项至少选择一个规格值";
});
const matchedSkuList = computed(() => selectableSkuList.value.filter(sku =>
isSpecSelectionComplete.value && specList.value.every(spec =>
sku.specValueIdList?.some(valueId => selectedSpecValueIdMap[spec.id || ""]?.includes(valueId))
)
));
const matchedSku = computed(() => selectableSkuList.value.find(sku =>
specList.value.every(spec => sku.specValueIdList?.includes(selectedSpecValueMap[spec.id || ""] || ""))
));
function enabledValues(spec: ProductSpec): ProductSpecValue[] {
const precedingSelectedValueIdList: string[][] = [];
for (const precedingSpec of specList.value) {
if (precedingSpec === spec) {
break;
}
const selectedValueIdList = isMultiple.value
? selectedSpecValueIdMap[precedingSpec.id || ""] || []
: [selectedSpecValueMap[precedingSpec.id || ""] || ""].filter(Boolean);
if (selectedValueIdList.length) {
precedingSelectedValueIdList.push(selectedValueIdList);
}
}
return (spec.valueList || []).filter(value => value.enabled !== false && !!value.id && selectableSkuList.value.some(sku => {
const skuValueIdList = sku.specValueIdList || [];
return skuValueIdList.includes(value.id || "")
&& precedingSelectedValueIdList.every(selectedValueIdList => skuValueIdList.some(id => selectedValueIdList.includes(id)));
}));
}
function clearUnavailableFollowingValues(specId: string): void {
const specIndex = specList.value.findIndex(spec => spec.id === specId);
if (specIndex < 0) {
return;
}
for (const spec of specList.value.slice(specIndex + 1)) {
if (!spec.id) {
continue;
}
const availableValueList = enabledValues(spec);
const availableValueIdSet = new Set(availableValueList.map(value => value.id));
if (isMultiple.value) {
selectedSpecValueIdMap[spec.id] = (selectedSpecValueIdMap[spec.id] || []).filter(id => availableValueIdSet.has(id));
} else if (!availableValueIdSet.has(selectedSpecValueMap[spec.id])) {
const firstValueId = availableValueList[0]?.id;
if (firstValueId) {
selectedSpecValueMap[spec.id] = firstValueId;
} else {
delete selectedSpecValueMap[spec.id];
}
}
}
}
function saleableUnits(sku: ProductSku): ProductSkuUnit[] {
return (sku.unitList || []).filter(unit => unit.allowSale !== false && unit.id);
}
function isSelectedSpecValue(specId: string, valueId: string): boolean {
return isMultiple.value
? !!valueId && !!selectedSpecValueIdMap[specId]?.includes(valueId)
: selectedSpecValueMap[specId] === valueId;
}
function selectSpecValue(specId: string, valueId: string): void {
if (!specId || !valueId) {
return;
}
if (!isMultiple.value) {
selectedSpecValueMap[specId] = valueId;
clearUnavailableFollowingValues(specId);
return;
}
const selectedValueIdList = selectedSpecValueIdMap[specId] || [];
selectedSpecValueIdMap[specId] = selectedValueIdList.includes(valueId)
? selectedValueIdList.filter(id => id !== valueId)
: [...selectedValueIdList, valueId];
clearUnavailableFollowingValues(specId);
const matchedSkuIdSet = new Set(matchedSkuList.value.map(sku => sku.id));
const selectedSkuIdSet = new Set(props.selectedSkuIdList);
for (const sku of selectableSkuList.value) {
if (sku.id && selectedSkuIdSet.has(sku.id) !== matchedSkuIdSet.has(sku.id)) {
emit("toggle", sku);
}
}
}
function isSelectedUnit(sku: ProductSku, unit: ProductSkuUnit): boolean {
return !!sku.id && !!unit.id && props.selectedSkuIdList.includes(sku.id) && props.selectedUnitId === unit.id;
}
function selectUnit(sku: ProductSku, unit: ProductSkuUnit): void {
if (!isMultiple.value && sku.id && unit.id) {
emit("select", { product: props.product, sku, unit });
}
}
watch([() => props.product, () => props.skuList], ([product]) => {
Object.keys(selectedSpecValueMap).forEach(key => delete selectedSpecValueMap[key]);
Object.keys(selectedSpecValueIdMap).forEach(key => delete selectedSpecValueIdMap[key]);
if (isMultiple.value) {
const selectedSkuList = selectableSkuList.value.filter(isSelectedSku);
const selectedValueIdSet = new Set(selectedSkuList.flatMap(sku => sku.specValueIdList || []));
for (const spec of product.specList || []) {
if (spec.id) {
selectedSpecValueIdMap[spec.id] = enabledValues(spec)
.map(value => value.id || "")
.filter(id => selectedValueIdSet.has(id));
}
}
return;
}
const selectedSku = selectableSkuList.value.find(sku => sku.id && props.selectedSkuIdList.includes(sku.id));
for (const spec of product.specList || []) {
const valueId = selectedSku?.specValueIdList?.find(id => spec.valueList?.some(value => value.id === id))
|| enabledValues(spec)[0]?.id;
if (spec.id && valueId) {
selectedSpecValueMap[spec.id] = valueId;
}
}
}, { immediate: true });
</script>
<style scoped lang="less">
.product-sku-selector {
.specs {
gap: .5rem;
display: flex;
flex-direction: column;
.spec {
gap: .5rem;
display: flex;
flex-direction: column;
.values {
gap: .5rem;
display: flex;
flex-wrap: wrap;
}
}
}
.sku-card {
border: .0625rem dashed var(--td-brand-color);
padding: .5rem;
margin-top: .5rem;
border-radius: .875rem;
.units {
gap: .5rem;
display: flex;
flex-wrap: wrap;
.price {
font-size: .75rem;
margin-left: .25rem;
}
}
}
.sku-list {
margin: 0;
}
.empty {
color: var(--td-text-color-secondary);
padding: 2rem 1rem;
text-align: center;
}
}
</style>
@@ -0,0 +1,183 @@
<template>
<t-collapse
v-model="expandedProductKeyList"
class="product-sku-selector"
theme="card"
:expand-mutex="true"
@change="handleChange"
>
<t-collapse-panel
v-for="item in props.items"
:key="item.key"
:value="item.key"
class="item"
:class="{ direct: isDirectSelect(item) }"
:disabled="isDirectSelect(item)"
:expand-icon="isDirectSelect(item) ? false : undefined"
v-entrance-transition="{ step: 30 }"
placement="bottom"
@click.capture="handlePanelClick($event, item)"
>
<template #header>
<div class="header">
<t-checkbox
v-if="props.selectionMode === 'multiple'"
class="check"
icon="line"
:model-value="isProductChecked(item) || isProductPartiallyChecked(item)"
:indeterminate="isProductPartiallyChecked(item)"
:disabled="item.checkLoading || !getSkuCount(item)"
:aria-label="`选择${item.name}`"
:aria-checked="isProductPartiallyChecked(item) ? 'mixed' : isProductChecked(item)"
borderless
@change="toggleProduct(item)"
/>
<t-image
v-if="item.photoUrl"
:src="item.photoUrl"
:alt="item.name || '产品图片'"
fit="cover"
class="avatar"
/>
<div v-else class="avatar fallback" v-text="(item.name || '产').slice(0, 1)" />
<strong class="clip-text" v-text="item.name || '未命名产品'" />
</div>
</template>
<div v-if="item.message" class="message" v-text="item.message" />
<product-sku-options
v-else-if="item.product && openedProductKeySet.has(item.key)"
:product="item.product"
:sku-list="item.skuList"
:selected-sku-id-list="props.selectedSkuIdList"
:selected-unit-id="props.selectedUnitId"
:selection-mode="props.selectionMode"
@select="emit('select', $event)"
@toggle="emit('toggle', item.key, $event)"
/>
</t-collapse-panel>
</t-collapse>
</template>
<script setup lang="ts">
import type { ProductSelection, ProductSku } from "@/types/Product";
import type { ProductSkuSelectionMode, ProductSkuSelectorItem } from "@/types/ProductSkuSelection";
import ProductSkuOptions from "./ProductSkuOptions.vue";
interface Props {
items: ProductSkuSelectorItem[];
selectedSkuIdList: string[];
selectedUnitId?: string;
selectionMode?: ProductSkuSelectionMode;
}
const props = withDefaults(defineProps<Props>(), { selectionMode: "single" });
const expandedProductKeyList = defineModel<Array<string | number>>("expandedProductKeyList", { default: () => [] });
// 首次展开后保留选项内容,供面板收起时计算动画高度。
const openedProductKeySet = reactive(new Set<string>());
const emit = defineEmits<{
change: [value: Array<string | number>];
select: [selection: ProductSelection];
toggle: [productId: string, sku: ProductSku];
check: [productId: string];
}>();
function isDirectSelect(item: ProductSkuSelectorItem): boolean {
return props.selectionMode === "multiple" && !!item.singleSkuId;
}
function getSkuCount(item: ProductSkuSelectorItem): number {
return item.skuList?.length ?? item.skuCount ?? 0;
}
function getSelectedSkuCount(item: ProductSkuSelectorItem): number {
if (!item.skuList) {
return item.selectedSkuCount || 0;
}
return item.skuList.filter(sku => !!sku.id && props.selectedSkuIdList.includes(sku.id)).length;
}
function isProductChecked(item: ProductSkuSelectorItem): boolean {
const skuCount = getSkuCount(item);
return 0 < skuCount && getSelectedSkuCount(item) === skuCount;
}
function isProductPartiallyChecked(item: ProductSkuSelectorItem): boolean {
const selectedCount = getSelectedSkuCount(item);
return 0 < selectedCount && selectedCount < getSkuCount(item);
}
function toggleProduct(item: ProductSkuSelectorItem): void {
if (props.selectionMode === "multiple" && !item.checkLoading && getSkuCount(item)) {
emit("check", item.key);
}
}
function handlePanelClick(event: MouseEvent, item: ProductSkuSelectorItem): void {
const target = event.target as Element | null;
if (!isDirectSelect(item) || !target?.closest(".t-collapse-panel__header") || target.closest(".check")) {
return;
}
event.stopPropagation();
toggleProduct(item);
}
function handleChange(value: Array<string | number>): void {
emit("change", value);
}
watch(expandedProductKeyList, (keyList) => {
for (const key of keyList) {
openedProductKeySet.add(String(key));
}
}, { immediate: true });
</script>
<style scoped lang="less">
.product-sku-selector {
margin: 0;
.item {
--td-collapse-content-padding: .25rem 1rem .75rem 1rem;
&.direct {
pointer-events: auto;
--td-collapse-header-text-disabled-color: var(--td-text-color-primary);
}
.header {
gap: .75rem;
display: flex;
min-width: 0;
align-items: center;
.check {
flex: 0 0 auto;
:deep(.t-checkbox__icon) {
margin-right: 0;
}
}
.avatar {
flex: 0 0 auto;
width: 2.5rem;
height: 2.5rem;
border-radius: .75rem !important;
}
}
.message {
color: var(--td-text-color-secondary);
padding: 2rem 1rem;
text-align: center;
}
}
}
:deep(.avatar .t-image__img) {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: inherit;
}
</style>
+1 -1
View File
@@ -51,7 +51,7 @@ const globalUIStore = useGlobalUIStore();
const tabBarStore = useTabBarStore();
const userStore = useUserStore();
const cachedRouteNames = new Set(["SalesOrderList", "ProductList", "ProductStockList"]);
const cachedRouteNames = new Set(["SalesOrderList", "ProductList", "ProductStockList", "ProductStockBatchSelect", "ProductStockBatchConfigure"]);
function shouldKeepAlive(sourceRoute: RouteLocationNormalizedLoaded): boolean {
return cachedRouteNames.has(String(sourceRoute.name));
+1 -1
View File
@@ -57,7 +57,7 @@
<script setup lang="ts">
import PointAPI from "@/api/PointAPI";
import ProductSelector from "@/components/ProductSelector.vue";
import ProductSelector from "@/components/productSelector/ProductSelector.vue";
import { useNavBarStore } from "@/store/navBarStore";
import type { PointRedeemSku, PointRedeemSkuStatus } from "@/types/Point";
import type { ProductSelection } from "@/types/Product";
@@ -0,0 +1,400 @@
<template>
<div v-can="permissionCodes.productStock.create" class="product-stock-batch-configure">
<t-cell-group theme="card" class="batch-info">
<t-form class="form" label-width="5rem">
<t-form-item label="入库备注" required-mark>
<t-textarea
v-model="productStockBatchStore.remark"
:disabled="isSaving"
borderless
maxlength="500"
autosize
placeholder="请输入本批次入库备注"
@update:model-value="invalidateRequestNo"
/>
</t-form-item>
<t-form-item label-width="0">
<media-selector
:model-value="globalAttachmentUrlList"
v-model:photo-items="productStockBatchStore.attachmentItems"
:upload="uploadPhotos"
:edit-mode="true"
:loading="isSaving"
:show-remove="!isSaving"
title="共用附件(未单独添加时使用)"
@update:photo-items="invalidateRequestNo"
/>
<div class="attachment-tip" v-text="'每个 SKU 都必须有附件;未单独添加时使用共用附件'" />
</t-form-item>
</t-form>
</t-cell-group>
<div v-if="productStockBatchStore.selectedItemList.length" class="item-list">
<article
v-for="item in productStockBatchStore.selectedItemList"
:key="item.sku.id"
class="sku-item"
>
<header class="sku-header">
<div class="sku-title">
<strong v-text="item.sku.name || '未命名 SKU'" />
<span class="sku-note" v-text="getSkuNote(item)" />
</div>
<t-button
theme="danger"
variant="text"
size="small"
content="移除"
:disabled="isSaving"
@click.stop="removeItem(item.sku.id || '')"
/>
</header>
<div class="unit-selection">
<strong v-text="'入库单位'" />
<div class="unit-list" role="group" :aria-label="`选择${item.sku.name || 'SKU'}入库单位`">
<t-button
v-for="unit in getSelectableUnits(item)"
:key="unit.id"
size="small"
:theme="item.skuUnitId === unit.id ? 'primary' : 'default'"
:variant="item.skuUnitId === unit.id ? 'base' : 'outline'"
:disabled="isSaving"
:aria-pressed="item.skuUnitId === unit.id"
@click="selectUnit(item, unit)"
>
<span v-text="unit.name || '未命名单位'" />
</t-button>
</div>
</div>
<t-form class="form" label-width="5rem">
<t-form-item label="数量" required-mark>
<t-input
v-model="item.quantity"
:disabled="isSaving"
type="number"
align="right"
borderless
:placeholder="item.sku.allowDecimalQuantity ? '最多三位小数' : '请输入整数'"
@update:model-value="invalidateRequestNo"
/>
</t-form-item>
<t-form-item label-width="0">
<media-selector
:model-value="getAttachmentUrlList(item.attachmentItems)"
v-model:photo-items="item.attachmentItems"
:upload="uploadPhotos"
:edit-mode="true"
:loading="isSaving"
:show-remove="!isSaving"
title="SKU 附件(可选)"
@update:photo-items="invalidateRequestNo"
/>
<div class="attachment-tip" v-text="'添加 SKU 附件后,该 SKU 不使用共用附件'" />
</t-form-item>
</t-form>
</article>
</div>
<t-empty v-else description="没有已选 SKU,请返回重新选择" />
</div>
</template>
<script setup lang="ts">
import { onBeforeRouteLeave } from "vue-router";
import { useUserStore } from "timi-web-api";
import { useCurrentStoreStore } from "@/store/currentStoreStore";
import { useNavBarStore } from "@/store/navBarStore";
import { useProductStockBatchStore, type ProductStockBatchSelection } from "@/store/productStockBatchStore";
import MediaSelector from "@/components/mediaSelector/MediaSelector.vue";
import ProductAPI from "@/api/ProductAPI";
import type { ProductStockManualInBatchItem, ProductStockManualInBatchRequest, ProductSkuUnit } from "@/types/Product";
import type { PhotoItem } from "@/types/Photo";
import { getErrorMessage } from "@/utils/error";
import { createProductRequestNo } from "@/utils/product";
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { getCurrentStoreId } from "@/utils/store";
import { uploadPhotoList } from "@/utils/photo";
defineOptions({ name: "ProductStockBatchConfigure" });
const router = useRouter();
const navBarStore = useNavBarStore();
const currentStoreStore = useCurrentStoreStore();
const productStockBatchStore = useProductStockBatchStore();
const userStore = useUserStore();
const activeStoreId = ref("");
const isSaving = ref(false);
const uploadCount = ref(0);
const globalAttachmentUrlList = computed(() => productStockBatchStore.attachmentItems.map(item => item.url));
const canSubmit = computed(() => {
const itemList = productStockBatchStore.selectedItemList;
return !isSaving.value
&& uploadCount.value === 0
&& !!productStockBatchStore.remark.trim()
&& 0 < itemList.length
&& itemList.every(item => isItemValid(item));
});
function getSelectableUnits(item?: ProductStockBatchSelection): ProductSkuUnit[] {
return (item?.sku.unitList || []).filter(unit => unit.allowPurchase && !!unit.id);
}
function getSkuNote(item: ProductStockBatchSelection): string {
return [item.productName || "未命名产品", item.sku.specSummary].filter(Boolean).join(" · ");
}
function getAttachmentUrlList(itemList: PhotoItem[]): string[] {
return itemList.map(item => item.url);
}
function getAttachmentList(itemList: PhotoItem[]): NonNullable<ProductStockManualInBatchItem["attachmentList"]> {
return itemList.flatMap(item => item.tempFileId ? [{
tempFileId: item.tempFileId,
attachType: item.attachType || "PHOTO",
name: item.attachment?.name
}] : []);
}
function invalidateRequestNo(): void {
productStockBatchStore.requestNo = "";
}
function isQuantityValid(item: ProductStockBatchSelection): boolean {
if (!/^\d+(?:\.\d{1,3})?$/.test(item.quantity) || !(0 < Number(item.quantity))) {
return false;
}
return item.sku.allowDecimalQuantity || /^\d+$/.test(item.quantity);
}
function isItemValid(item: ProductStockBatchSelection): boolean {
const unitList = getSelectableUnits(item);
const hasUnit = unitList.some(unit => unit.id === item.skuUnitId);
const itemAttachmentList = getAttachmentList(item.attachmentItems);
const globalAttachmentList = getAttachmentList(productStockBatchStore.attachmentItems);
return hasUnit
&& isQuantityValid(item)
&& 0 < (itemAttachmentList.length || globalAttachmentList.length);
}
function updateNavBar(): void {
navBarStore.clearRight();
if (!userStore.hasPermissions(permissionCodes.productStock.create)) {
return;
}
navBarStore.setRightText(isSaving.value ? "提交中" : "提交", "var(--td-brand-color)", submit);
navBarStore.setRightDisabled(!canSubmit.value);
}
function selectUnit(item: ProductStockBatchSelection, unit: ProductSkuUnit): void {
if (isSaving.value) {
return;
}
if (unit.id && getSelectableUnits(item).some(candidate => candidate.id === unit.id)) {
if (item.skuUnitId !== unit.id) {
invalidateRequestNo();
}
item.skuUnitId = unit.id;
}
}
function removeItem(skuId: string): void {
if (isSaving.value) {
return;
}
const itemIndex = productStockBatchStore.selectedItemList.findIndex(item => item.sku.id === skuId);
if (-1 < itemIndex) {
invalidateRequestNo();
productStockBatchStore.selectedItemList.splice(itemIndex, 1);
}
}
async function uploadPhotos(fileList: File[]): Promise<PhotoItem[]> {
uploadCount.value += 1;
try {
return await uploadPhotoList(fileList);
} finally {
uploadCount.value -= 1;
}
}
function validate(): boolean {
if (!productStockBatchStore.remark.trim()) {
Message.warning("入库备注不能为空");
return false;
}
if (!productStockBatchStore.selectedItemList.length) {
Message.warning("请至少选择一个 SKU");
return false;
}
for (const item of productStockBatchStore.selectedItemList) {
if (!getSelectableUnits(item).some(unit => unit.id === item.skuUnitId)) {
Message.warning((item.sku.name || "SKU") + ":请选择入库单位");
return false;
}
if (!isQuantityValid(item)) {
const quantityTip = item.sku.allowDecimalQuantity
? "数量必须大于 0,最多三位小数"
: "数量必须是大于 0 的整数";
Message.warning((item.sku.name || "SKU") + ":" + quantityTip);
return false;
}
if (!getAttachmentList(item.attachmentItems).length && !getAttachmentList(productStockBatchStore.attachmentItems).length) {
Message.warning((item.sku.name || "SKU") + ":请添加 SKU 附件或共用附件");
return false;
}
}
if (0 < uploadCount.value) {
Message.warning("附件上传完成后再提交");
return false;
}
return true;
}
function buildRequest(): ProductStockManualInBatchRequest {
const itemList: ProductStockManualInBatchItem[] = productStockBatchStore.selectedItemList.map(item => {
const attachmentList = getAttachmentList(item.attachmentItems);
return {
skuId: item.sku.id || "",
skuUnitId: item.skuUnitId,
quantity: item.quantity,
...(attachmentList.length ? { attachmentList } : {})
};
});
const attachmentList = getAttachmentList(productStockBatchStore.attachmentItems);
return {
requestNo: productStockBatchStore.requestNo || (productStockBatchStore.requestNo = createProductRequestNo()),
storeId: productStockBatchStore.storeId,
remark: productStockBatchStore.remark.trim(),
...(attachmentList.length ? { attachmentList } : {}),
itemList
};
}
async function submit(): Promise<void> {
if (isSaving.value || !validate()) {
return;
}
isSaving.value = true;
updateNavBar();
try {
await ProductAPI.manualInBatch(buildRequest());
emitListDataChanged(listDataEventKeys.productStockChanged);
Message.success("批量入库已提交");
productStockBatchStore.reset();
await router.replace({ name: "ProductStockList" });
} catch (error) {
Message.error(getErrorMessage(error, "批量入库失败,请确认请求号后重试"));
} finally {
isSaving.value = false;
updateNavBar();
}
}
watch([canSubmit, isSaving], updateNavBar);
onMounted(() => {
const storeId = currentStoreStore.currentStoreId || getCurrentStoreId();
productStockBatchStore.ensureStore(storeId);
activeStoreId.value = storeId;
if (!productStockBatchStore.selectedItemList.length) {
void router.replace({ name: "ProductStockBatchSelect" });
}
updateNavBar();
});
onActivated(() => {
const storeId = currentStoreStore.currentStoreId || getCurrentStoreId();
if (activeStoreId.value && activeStoreId.value !== storeId) {
productStockBatchStore.ensureStore(storeId);
activeStoreId.value = storeId;
void router.replace({ name: "ProductStockBatchSelect" });
return;
}
activeStoreId.value = storeId;
updateNavBar();
});
onBeforeRouteLeave(() => navBarStore.clearRight());
onUnmounted(() => navBarStore.clearRight());
</script>
<style scoped lang="less">
.product-stock-batch-configure {
gap: 1rem;
padding: var(--app-nav-height) 0 1rem;
display: flex;
flex-direction: column;
.form {
margin: 0;
}
.batch-info {
padding: .25rem .75rem;
}
.item-list {
gap: 1rem;
margin: 0 1rem;
display: flex;
flex-direction: column;
}
.sku-item {
gap: 1rem;
border: 1px solid var(--td-component-border);
padding: 1rem;
display: flex;
background: var(--td-bg-color-container);
border-radius: 1rem;
flex-direction: column;
}
.sku-header {
gap: .75rem;
display: flex;
align-items: flex-start;
justify-content: space-between;
}
.sku-title {
gap: .25rem;
display: flex;
flex-direction: column;
strong {
color: var(--td-text-color-primary);
font-size: 1rem;
}
}
.sku-note {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
.unit-list {
gap: .5rem;
display: flex;
flex-wrap: wrap;
}
.unit-selection {
gap: .5rem;
display: flex;
flex-direction: column;
strong {
color: var(--td-text-color-primary);
font-size: .875rem;
}
}
.attachment-tip {
color: var(--td-text-color-secondary);
margin-top: .25rem;
font-size: .75rem;
}
}
</style>
@@ -0,0 +1,398 @@
<template>
<div v-can="permissionCodes.productStock.create" class="product-stock-batch-select">
<div class="filters glass">
<t-input
v-model="keyword"
class="keyword"
type="search"
borderless
clearable
placeholder="搜索产品名称或编码"
/>
</div>
<t-pull-down-refresh
class="list-wrap empty-cell-title-margin"
v-model="isRefreshing"
:refresh-timeout="30000"
@refresh="refresh"
@scrolltolower="loadMore"
>
<product-sku-selector
class="selector"
v-if="productList.length"
v-model:expanded-product-key-list="expandedProductKeyList"
:items="selectorItemList"
:selected-sku-id-list="selectedSkuIdList"
selection-mode="multiple"
@change="handleProductChange"
@toggle="toggleSku"
@check="toggleProductSkus"
/>
<div v-else class="center-tips" v-text="emptyText" />
<div v-if="productList.length" class="center-tips" v-text="isLoading ? '正在加载更多' : isNoMore ? '已经到底了' : '上拉加载更多'" />
</t-pull-down-refresh>
</div>
</template>
<script setup lang="ts">
import { onBeforeRouteLeave } from "vue-router";
import { useUserStore } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI";
import { useCurrentStoreStore } from "@/store/currentStoreStore";
import { useNavBarStore } from "@/store/navBarStore";
import { useProductStockBatchStore } from "@/store/productStockBatchStore";
import type { Product, ProductSku, ProductStockProduct } from "@/types/Product";
import type { ProductSkuSelectorItem } from "@/types/ProductSkuSelection";
import { getErrorMessage } from "@/utils/error";
import { getProductPhotoURL } from "@/utils/product";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { getCurrentStoreId } from "@/utils/store";
defineOptions({ name: "ProductStockBatchSelect" });
const router = useRouter();
const route = useRoute();
const navBarStore = useNavBarStore();
const userStore = useUserStore();
const currentStoreStore = useCurrentStoreStore();
const productStockBatchStore = useProductStockBatchStore();
const keyword = ref("");
const productList = ref<ProductStockProduct[]>([]);
const productDetailMap = ref<Record<string, Product>>({});
const checkingProductIdSet = reactive(new Set<string>());
const expandedProductKeyList = ref<Array<string | number>>([]);
const loadingProductId = ref("");
const pageIndex = ref(0);
const total = ref(0);
const isLoading = ref(false);
const isRefreshing = ref(false);
const isNoMore = ref(false);
const selectedSkuIdList = computed(() => productStockBatchStore.selectedItemList
.map(item => item.sku.id)
.filter((id): id is string => !!id));
const canContinue = computed(() => 0 < productStockBatchStore.selectedItemList.length);
const canReadAndCreate = computed(() =>
userStore.hasPermissions(permissionCodes.productStock.read)
&& userStore.hasPermissions(permissionCodes.productStock.create)
);
const emptyText = computed(() => {
if (isLoading.value) {
return "正在加载产品";
}
return keyword.value ? "未找到匹配产品" : "暂无可入库产品";
});
const selectorItemList = computed<ProductSkuSelectorItem[]>(() => {
const selectedCountByProduct = new Map<string, number>();
for (const selectedItem of productStockBatchStore.selectedItemList) {
selectedCountByProduct.set(selectedItem.productId, (selectedCountByProduct.get(selectedItem.productId) || 0) + 1);
}
return productList.value.map(item => {
const selectorItem: ProductSkuSelectorItem = {
key: item.productId,
name: item.productName || "未命名产品",
photoUrl: getProductPhotoURL(item),
singleSkuId: item.skuCount === 1 ? item.skuId : undefined,
skuCount: item.skuCount || 0,
selectedSkuCount: selectedCountByProduct.get(item.productId) || 0,
checkLoading: checkingProductIdSet.has(item.productId) || loadingProductId.value === item.productId
};
const product = getProduct(item.productId);
if (loadingProductId.value === item.productId || checkingProductIdSet.has(item.productId) && !product) {
return { ...selectorItem, message: "正在加载 SKU" };
}
if (!product) {
const message = expandedProductKeyList.value.includes(item.productId)
? "产品详情不可用,请重新展开"
: "正在加载 SKU";
return { ...selectorItem, message };
}
if (product.status !== "ACTIVE") {
return { ...selectorItem, singleSkuId: undefined, skuCount: 0, message: "该产品已停用,不能入库" };
}
const skuList = getSelectableSkuList(item.productId);
return skuList.length
? { ...selectorItem, product, skuList, singleSkuId: skuList.length === 1 ? skuList[0].id : undefined }
: { ...selectorItem, singleSkuId: undefined, skuCount: 0, message: "该产品没有可入库的 SKU" };
});
});
let keywordTimer: number | undefined;
let requestToken = 0;
let productDetailToken = 0;
let activeStoreId = "";
function getCurrentRouteDepth(): number {
const transitionDepth = Array.isArray(route.query.transitionDepth)
? route.query.transitionDepth[0]
: route.query.transitionDepth;
const depth = Number(transitionDepth);
if (transitionDepth && Number.isInteger(depth) && -1 < depth && depth < 21) {
return depth;
}
return Number(route.meta.depth ?? 0);
}
function updateNavBar(): void {
navBarStore.clearRight();
if (canReadAndCreate.value) {
navBarStore.setRightText("下一步", "var(--td-brand-color)", toConfigure);
navBarStore.setRightDisabled(!canContinue.value);
}
}
function getProduct(productId: string): Product | undefined {
return productDetailMap.value[productId];
}
function getSelectableSkuList(productId: string): ProductSku[] {
const product = getProduct(productId);
if (!product || product.status !== "ACTIVE" || !product.stockEnabled) {
return [];
}
return (product.skuList || []).filter(sku =>
!!sku.id
&& sku.status === "ACTIVE"
&& sku.stockEnabled
&& (sku.unitList || []).some(unit => unit.allowPurchase && unit.id)
);
}
async function handleProductChange(value: Array<string | number>): Promise<void> {
const productId = String(value[0] || "");
const token = ++productDetailToken;
loadingProductId.value = "";
if (!productId) {
return;
}
const cachedProduct = getProduct(productId);
if (cachedProduct || checkingProductIdSet.has(productId)) {
return;
}
loadingProductId.value = productId;
try {
const product = await ProductAPI.detail(productId);
if (token !== productDetailToken) {
return;
}
productDetailMap.value = { ...productDetailMap.value, [productId]: product };
if (product.status !== "ACTIVE") {
Message.warning("该产品已停用,不能入库");
} else if (getSelectableSkuList(productId).length === 1) {
expandedProductKeyList.value = expandedProductKeyList.value.filter(key => key !== productId);
}
} catch (error) {
Message.error(getErrorMessage(error, "产品详情加载失败"));
} finally {
if (token === productDetailToken) {
loadingProductId.value = "";
}
}
}
function toggleSku(productId: string, sku: ProductSku): boolean {
const item = productList.value.find(product => product.productId === productId);
if (!item || !sku.id || !getSelectableSkuList(productId).some(candidate => candidate.id === sku.id)) {
return false;
}
const isSelected = productStockBatchStore.hasSku(sku.id);
productStockBatchStore.requestNo = "";
productStockBatchStore.toggleSelection({
productId: item.productId,
productName: item.productName,
sku
});
return !isSelected;
}
async function toggleProductSkus(productId: string): Promise<void> {
if (checkingProductIdSet.has(productId)) {
return;
}
checkingProductIdSet.add(productId);
const requestedStoreId = activeStoreId;
try {
if (!getProduct(productId)) {
const product = await ProductAPI.detail(productId);
if (requestedStoreId !== activeStoreId) {
return;
}
productDetailMap.value = { ...productDetailMap.value, [productId]: product };
}
if (getProduct(productId)?.status !== "ACTIVE") {
Message.warning("该产品已停用,不能入库");
return;
}
const skuList = getSelectableSkuList(productId);
if (!skuList.length) {
Message.warning("该产品没有可入库的 SKU");
return;
}
if (skuList.length === 1) {
expandedProductKeyList.value = expandedProductKeyList.value.filter(key => key !== productId);
}
const item = productList.value.find(product => product.productId === productId);
if (!item) {
return;
}
const selectedSkuIdSet = new Set(selectedSkuIdList.value);
const allSelected = skuList.every(sku => selectedSkuIdSet.has(sku.id || ""));
productStockBatchStore.requestNo = "";
for (const sku of skuList) {
if (allSelected || !selectedSkuIdSet.has(sku.id || "")) {
productStockBatchStore.toggleSelection({
productId: item.productId,
productName: item.productName,
sku
});
}
}
} catch (error) {
Message.error(getErrorMessage(error, "产品详情加载失败"));
} finally {
checkingProductIdSet.delete(productId);
}
}
async function toConfigure(): Promise<void> {
if (!canContinue.value) {
Message.warning("请至少选择一个 SKU");
return;
}
await router.push({
name: "ProductStockBatchConfigure",
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
async function fetch(reset = false): Promise<void> {
if (!reset && (isLoading.value || isNoMore.value)) {
return;
}
if (reset) {
pageIndex.value = 0;
total.value = 0;
isNoMore.value = false;
expandedProductKeyList.value = [];
productDetailToken += 1;
}
const token = ++requestToken;
isLoading.value = true;
try {
const pageSize = 15;
const result = await ProductAPI.stockProductList({
index: pageIndex.value,
size: pageSize,
keyword: keyword.value.trim() || undefined
});
if (token !== requestToken) {
return;
}
const list = result.list || [];
productList.value = reset ? list : productList.value.concat(list);
total.value = result.total || 0;
pageIndex.value += 1;
isNoMore.value = list.length < pageSize
|| productList.value.length === total.value
|| total.value < productList.value.length;
} finally {
if (token === requestToken) {
isLoading.value = false;
}
}
}
async function refresh(): Promise<void> {
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "产品列表加载失败"));
} finally {
isRefreshing.value = false;
}
}
async function loadMore(): Promise<void> {
try {
await fetch();
} catch (error) {
Message.error(getErrorMessage(error, "产品列表加载失败"));
}
}
watch(canContinue, updateNavBar);
watch(keyword, () => {
window.clearTimeout(keywordTimer);
keywordTimer = window.setTimeout(async () => {
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "产品列表加载失败"));
}
}, 300);
});
onMounted(async () => {
const storeId = currentStoreStore.currentStoreId || getCurrentStoreId();
productStockBatchStore.ensureStore(storeId);
activeStoreId = storeId;
updateNavBar();
if (!canReadAndCreate.value) {
return;
}
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "产品列表加载失败"));
}
});
onActivated(async () => {
const storeId = currentStoreStore.currentStoreId || getCurrentStoreId();
productStockBatchStore.ensureStore(storeId);
if (activeStoreId && activeStoreId !== storeId) {
productDetailMap.value = {};
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "产品列表加载失败"));
}
}
activeStoreId = storeId;
updateNavBar();
});
onBeforeRouteLeave(() => navBarStore.clearRight());
onUnmounted(() => {
navBarStore.clearRight();
window.clearTimeout(keywordTimer);
requestToken += 1;
productDetailToken += 1;
});
</script>
<style scoped lang="less">
.product-stock-batch-select {
padding: var(--app-nav-height) 0 1rem;
.filters {
top: var(--app-nav-height);
z-index: 10;
padding: .75rem 1rem;
position: sticky;
.keyword {
border: 1px solid var(--td-component-border);
padding: .5rem 1rem;
border-radius: 1rem;
}
}
.list-wrap {
.selector {
margin: 0 1rem;
}
}
}
</style>
+31 -1
View File
@@ -65,13 +65,16 @@
import { useUserStore } from "timi-web-api";
import { onBeforeRouteLeave } from "vue-router";
import ProductAPI from "@/api/ProductAPI";
import { useCurrentStoreStore } from "@/store/currentStoreStore";
import { useNavBarStore } from "@/store/navBarStore";
import { useProductStockBatchStore } from "@/store/productStockBatchStore";
import type { ProductStockProduct } from "@/types/Product";
import { getErrorMessage } from "@/utils/error";
import { getProductPhotoURL, getProductQuantityText } from "@/utils/product";
import { events, isCurrentStoreEvent, listDataEventKeys, type ListDataChangedPayload } from "@/utils/listDataEvents";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { getCurrentStoreId } from "@/utils/store";
defineOptions({ name: "ProductStockList" });
@@ -80,6 +83,8 @@ const route = useRoute();
const productStockListRef = ref<HTMLElement | null>(null);
const navBarStore = useNavBarStore();
const userStore = useUserStore();
const currentStoreStore = useCurrentStoreStore();
const productStockBatchStore = useProductStockBatchStore();
const keyword = ref("");
const productList = ref<ProductStockProduct[]>([]);
const pageIndex = ref(0);
@@ -126,11 +131,35 @@ function restorePageScrollPosition(): void {
}
const emptyText = computed(() => isLoading.value ? "正在加载产品" : keyword.value ? "未找到匹配产品" : "暂无启用库存管理的产品");
const canBatchIn = computed(() =>
userStore.hasPermissions(permissionCodes.productStock.read)
&& userStore.hasPermissions(permissionCodes.productStock.create)
);
function getCurrentRouteDepth(): number {
return Number(route.meta.depth ?? 0);
}
function updateNavBar(): void {
navBarStore.clearRight();
if (canBatchIn.value) {
navBarStore.setRightText("批量入库", "var(--td-brand-color)", openBatchIn);
}
}
async function openBatchIn(): Promise<void> {
const storeId = currentStoreStore.currentStoreId || getCurrentStoreId();
if (!storeId) {
Message.warning("请先选择门店");
return;
}
productStockBatchStore.start(storeId);
await router.push({
name: "ProductStockBatchSelect",
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
async function fetch(reset = false, preserveScroll = false): Promise<void> {
if (!reset && (isLoading.value || isNoMore.value)) {
return;
@@ -272,7 +301,7 @@ async function toSkuList(item: ProductStockProduct): Promise<void> {
onMounted(async () => {
unregisterProductStockListEvent = events.register(listDataEventKeys.productStockChanged, (payload: ListDataChangedPayload) => requestEventRefresh(payload));
navBarStore.clearRight();
updateNavBar();
if (!userStore.hasPermissions(permissionCodes.productStock.read)) {
return;
}
@@ -285,6 +314,7 @@ onMounted(async () => {
onActivated(() => {
restorePageScrollPosition();
updateNavBar();
});
onDeactivated(() => {
+12
View File
@@ -61,6 +61,18 @@ const productRoutes: RouteRecordRaw[] = [
component: () => import("@/pages/product/ProductStockSkuList.vue"),
meta: pageMeta("选择 SKU", 4)
},
{
path: "/management/product-stocks/batch/select",
name: "ProductStockBatchSelect",
component: () => import("@/pages/product/ProductStockBatchSelect.vue"),
meta: pageMeta("选择入库 SKU", 4)
},
{
path: "/management/product-stocks/batch/configure",
name: "ProductStockBatchConfigure",
component: () => import("@/pages/product/ProductStockBatchConfigure.vue"),
meta: pageMeta("批量入库", 5)
},
{
path: "/management/product-stock-records",
name: "ProductStockRecordList",
+75
View File
@@ -0,0 +1,75 @@
import type { ProductSku } from "@/types/Product";
import type { PhotoItem } from "@/types/Photo";
export type ProductStockBatchSelection = {
productId: string;
productName: string;
sku: ProductSku;
quantity: string;
skuUnitId: string;
attachmentItems: PhotoItem[];
};
export const useProductStockBatchStore = defineStore("product-stock-batch", () => {
const storeId = ref("");
const selectedItemList = ref<ProductStockBatchSelection[]>([]);
const remark = ref("");
const attachmentItems = ref<PhotoItem[]>([]);
const requestNo = ref("");
function reset(): void {
storeId.value = "";
selectedItemList.value = [];
remark.value = "";
attachmentItems.value = [];
requestNo.value = "";
}
function start(storeIdValue: string): void {
reset();
storeId.value = storeIdValue;
}
function ensureStore(storeIdValue: string): void {
if (storeId.value === storeIdValue) {
return;
}
start(storeIdValue);
}
function hasSku(skuId: string): boolean {
return selectedItemList.value.some(item => item.sku.id === skuId);
}
function toggleSelection(item: Omit<ProductStockBatchSelection, "quantity" | "skuUnitId" | "attachmentItems">): void {
const skuId = item.sku.id;
if (!skuId) {
return;
}
const itemIndex = selectedItemList.value.findIndex(selectedItem => selectedItem.sku.id === skuId);
if (0 <= itemIndex) {
selectedItemList.value.splice(itemIndex, 1);
return;
}
const defaultUnit = item.sku.unitList?.find(unit => unit.allowPurchase && unit.id);
selectedItemList.value.push({
...item,
quantity: "",
skuUnitId: defaultUnit?.id || "",
attachmentItems: []
});
}
return {
storeId,
selectedItemList,
remark,
attachmentItems,
requestNo,
reset,
start,
ensureStore,
hasSku,
toggleSelection
};
});
+15
View File
@@ -226,6 +226,21 @@ export type ProductStockChangeRequest = {
attachmentList: Partial<Attachment>[];
};
export type ProductStockManualInBatchItem = {
skuId: string;
skuUnitId: string;
quantity: number | string;
attachmentList?: Partial<Attachment>[];
};
export type ProductStockManualInBatchRequest = {
requestNo: string;
storeId?: string;
remark: string;
attachmentList?: Partial<Attachment>[];
itemList: ProductStockManualInBatchItem[];
};
export type ProductStockManualRevokeRequest = {
requestNo: string;
sourceRecordId: string;
+25
View File
@@ -0,0 +1,25 @@
import type { Product, ProductSku } from "./Product";
/** SKU 与销售单位共同确定一项选择。 */
export type ProductSkuSelectionValue = {
skuId: string;
skuUnitId: string;
};
/** SKU 选择模式。 */
export type ProductSkuSelectionMode = "single" | "multiple";
/** 产品 SKU 选择器中的产品面板。 */
export interface ProductSkuSelectorItem {
key: string;
name: string;
photoUrl?: string;
product?: Product;
skuList?: ProductSku[];
/** 多选模式下可直接切换的唯一 SKU。 */
singleSkuId?: string;
skuCount?: number;
selectedSkuCount?: number;
checkLoading?: boolean;
message?: string;
}