add product sku

This commit is contained in:
Timi
2026-09-07 12:59:27 +08:00
parent 9841723177
commit 1d70aebd83
49 changed files with 3700 additions and 756 deletions
+45 -37
View File
@@ -27,43 +27,50 @@
</div>
<customer-profile-card v-entrance-transition class="customer" :customer="selectedCustomer" />
<div class="charts">
<customer-chart-summary
v-entrance-transition="70"
v-if="selectedCustomer"
:customer="selectedCustomer"
:month-cursor="monthCursor"
:selected-event-id-list="selectedEventIdList"
/>
<customer-event-record-calendar-section
v-entrance-transition="140"
v-if="selectedCustomer"
v-model="monthCursor"
v-model:selected-event-id-list="selectedEventIdList"
:customer-id="selectedCustomer.id || ''"
:customer-name="selectedCustomer.name"
:store-id="selectedCustomer.storeId"
@list="toEventRecordList"
/>
<customer-record-trend-chart
v-entrance-transition="210"
v-if="selectedCustomer"
:customer-id="selectedCustomer.id || ''"
:date-text-list="chartDateTextList"
:selected-event-id-list="selectedEventIdList"
/>
<customer-event-structure-chart
v-entrance-transition="280"
v-if="selectedCustomer"
:customer-id="selectedCustomer.id || ''"
:date-text-list="monthDateTextList"
:selected-event-id-list="selectedEventIdList"
/>
<customer-selector
v-entrance-transition="350"
v-model="selectedCustomerId"
v-model:visible="selectorVisible"
@change="handleCustomerSelected"
/>
<customer-order-charts
v-entrance-transition="35"
v-if="selectedCustomer"
:customer-id="selectedCustomer.id || ''"
:date-text-list="chartDateTextList"
:store-id="selectedCustomer.storeId"
/>
<customer-chart-summary
v-entrance-transition="70"
v-if="selectedCustomer"
:customer="selectedCustomer"
:month-cursor="monthCursor"
:selected-event-id-list="selectedEventIdList"
/>
<customer-event-record-calendar-section
v-entrance-transition="140"
v-if="selectedCustomer"
v-model="monthCursor"
v-model:selected-event-id-list="selectedEventIdList"
:customer-id="selectedCustomer.id || ''"
:customer-name="selectedCustomer.name"
:store-id="selectedCustomer.storeId"
@list="toEventRecordList"
/>
<customer-record-trend-chart
v-entrance-transition="210"
v-if="selectedCustomer"
:customer-id="selectedCustomer.id || ''"
:date-text-list="chartDateTextList"
:selected-event-id-list="selectedEventIdList"
/>
<customer-event-structure-chart
v-entrance-transition="280"
v-if="selectedCustomer"
:customer-id="selectedCustomer.id || ''"
:date-text-list="monthDateTextList"
:selected-event-id-list="selectedEventIdList"
/>
<customer-selector
v-entrance-transition="350"
v-model="selectedCustomerId"
v-model:visible="selectorVisible"
@change="handleCustomerSelected"
/>
</div>
</div>
</template>
@@ -77,6 +84,7 @@ import type { EventRecordCalendarListPayload } from "@/components/EventRecordCal
import CustomerChartSummary from "@/pages/customer/component/CustomerChartSummary.vue";
import CustomerEventRecordCalendarSection from "@/pages/customer/component/CustomerEventRecordCalendarSection.vue";
import CustomerEventStructureChart from "@/pages/customer/component/CustomerEventStructureChart.vue";
import CustomerOrderCharts from "@/pages/customer/component/CustomerOrderCharts.vue";
import CustomerRecordTrendChart from "@/pages/customer/component/CustomerRecordTrendChart.vue";
import { useSettingStore } from "@/store/settingStore";
import type { Customer } from "@/types/Customer";
@@ -0,0 +1,77 @@
<template>
<gao-chart-card
title="有效消费趋势"
caption="金额已换算为元"
:date-text-list="dateTextList"
:option="buildOption"
:loading="loading"
:has-data="list.length > 0"
height="18rem"
/>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import GaoChartCard from "@/pages/product/component/GaoChartCard.vue";
import type { GaoSalesOrderConsumptionDailyStatView } from "@/types/GaoChart";
import { buildAxisChartOption, getDailyItem, getNumber } from "@/pages/product/component/chartUtils";
defineOptions({
name: "CustomerConsumptionDailyChart"
});
const props = defineProps<{
dateTextList: string[];
list: GaoSalesOrderConsumptionDailyStatView[];
loading: boolean;
}>();
function buildOption(visibleDateTextList: string[]): EChartsOption {
const labelList = visibleDateTextList.map(item => item.slice(5));
return {
...buildAxisChartOption(labelList),
xAxis: {
type: "category",
data: labelList,
axisTick: { show: false },
axisLabel: { color: "#52607a", interval: "auto", hideOverlap: true }
},
yAxis: [
{
type: "value",
name: "记录",
axisLabel: { color: "#52607a" },
splitLine: { lineStyle: { color: "rgba(148, 163, 184, .2)" } }
},
{
type: "value",
name: "元",
axisLabel: { color: "#52607a" },
splitLine: { show: false }
}
],
series: [
{
name: "消费记录",
type: "bar",
yAxisIndex: 0,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.recordCount))
},
{
name: "当日消费",
type: "line",
yAxisIndex: 1,
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.amount) / 100)
},
{
name: "累计消费",
type: "line",
yAxisIndex: 1,
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.cumulativeAmount) / 100)
}
]
};
}
</script>
@@ -0,0 +1,77 @@
<template>
<gao-chart-card
title="订单日历"
caption="按下单日期统计"
:date-text-list="dateTextList"
:option="buildOption"
:loading="loading"
:has-data="list.length > 0"
height="18rem"
/>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import GaoChartCard from "@/pages/product/component/GaoChartCard.vue";
import type { GaoSalesOrderCalendarStatView } from "@/types/GaoChart";
import { buildAxisChartOption, getDailyItem, getNumber } from "@/pages/product/component/chartUtils";
defineOptions({
name: "CustomerOrderCalendarChart"
});
const props = defineProps<{
dateTextList: string[];
list: GaoSalesOrderCalendarStatView[];
loading: boolean;
}>();
function buildOption(visibleDateTextList: string[]): EChartsOption {
const labelList = visibleDateTextList.map(item => item.slice(5));
return {
...buildAxisChartOption(labelList),
xAxis: {
type: "category",
data: labelList,
axisTick: { show: false },
axisLabel: { color: "#52607a", interval: "auto", hideOverlap: true }
},
yAxis: [
{
type: "value",
name: "订单",
axisLabel: { color: "#52607a" },
splitLine: { lineStyle: { color: "rgba(148, 163, 184, .2)" } }
},
{
type: "value",
name: "元",
axisLabel: { color: "#52607a" },
splitLine: { show: false }
}
],
series: [
{
name: "订单数",
type: "bar",
yAxisIndex: 0,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.orderCount))
},
{
name: "成交金额",
type: "line",
yAxisIndex: 1,
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.saleAmount) / 100)
},
{
name: "净收款",
type: "line",
yAxisIndex: 1,
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.netPaidAmount) / 100)
}
]
};
}
</script>
@@ -0,0 +1,223 @@
<template>
<section class="order-charts">
<div class="section-heading">
<div>
<div class="eyebrow" v-text="'订单经营分析'" />
<h2 v-text="'客户订单看板'" />
</div>
<span v-text="'金额单位:元,数量单位:基础单位'" />
</div>
<order-daily-chart
:date-text-list="dateTextList"
:list="dailyList"
:loading="isLoading"
/>
<div class="two-columns">
<customer-order-product-rank-chart
:list="productRankList"
:loading="isLoading"
/>
<customer-order-sku-rank-chart
:list="skuRankList"
:loading="isLoading"
/>
</div>
<customer-consumption-daily-chart
:date-text-list="dateTextList"
:list="consumptionDailyList"
:loading="isLoading"
/>
<customer-order-calendar-chart
:date-text-list="dateTextList"
:list="calendarList"
:loading="isLoading"
/>
<div class="two-columns">
<customer-repeat-daily-chart
:date-text-list="dateTextList"
:list="repeatDailyList"
:loading="isLoading"
/>
<customer-repeat-interval-chart
:list="repeatIntervalList"
:loading="isLoading"
/>
</div>
</section>
</template>
<script setup lang="ts">
import GaoSalesOrderChartAPI from "@/api/GaoSalesOrderChartAPI";
import CustomerConsumptionDailyChart from "@/pages/customer/component/CustomerConsumptionDailyChart.vue";
import CustomerOrderCalendarChart from "@/pages/customer/component/CustomerOrderCalendarChart.vue";
import CustomerOrderProductRankChart from "@/pages/customer/component/CustomerOrderProductRankChart.vue";
import CustomerOrderSkuRankChart from "@/pages/customer/component/CustomerOrderSkuRankChart.vue";
import CustomerRepeatDailyChart from "@/pages/customer/component/CustomerRepeatDailyChart.vue";
import CustomerRepeatIntervalChart from "@/pages/customer/component/CustomerRepeatIntervalChart.vue";
import OrderDailyChart from "@/pages/product/component/OrderDailyChart.vue";
import type {
GaoCustomerOrderProductRankView,
GaoCustomerOrderSkuRankView,
GaoCustomerRepeatDailyStatView,
GaoCustomerRepeatIntervalStatView,
GaoSalesOrderCalendarStatView,
GaoSalesOrderConsumptionDailyStatView,
GaoSalesOrderDailyStatView
} from "@/types/GaoChart";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
defineOptions({
name: "CustomerOrderCharts"
});
const props = defineProps<{
customerId: string;
dateTextList: string[];
storeId?: string;
}>();
const dailyList = ref<GaoSalesOrderDailyStatView[]>([]);
const productRankList = ref<GaoCustomerOrderProductRankView[]>([]);
const skuRankList = ref<GaoCustomerOrderSkuRankView[]>([]);
const consumptionDailyList = ref<GaoSalesOrderConsumptionDailyStatView[]>([]);
const calendarList = ref<GaoSalesOrderCalendarStatView[]>([]);
const repeatDailyList = ref<GaoCustomerRepeatDailyStatView[]>([]);
const repeatIntervalList = ref<GaoCustomerRepeatIntervalStatView[]>([]);
const isLoading = ref(false);
let requestId = 0;
watch([
() => props.customerId,
() => props.storeId,
() => props.dateTextList
], async () => {
await loadCharts();
}, {
deep: true,
immediate: true
});
async function loadCharts(): Promise<void> {
if (!props.customerId || !props.dateTextList.length) {
clearData();
return;
}
const currentRequestId = ++requestId;
isLoading.value = true;
try {
const request = {
storeId: props.storeId,
customerId: props.customerId,
beginAt: getDateStart(props.dateTextList[0]),
endAt: getDateEnd(props.dateTextList[props.dateTextList.length - 1]),
topN: 10
};
const [daily, productRank, skuRank, consumptionDaily, calendar, repeatDaily, repeatInterval] = await Promise.all([
GaoSalesOrderChartAPI.daily(request),
GaoSalesOrderChartAPI.customerProductRank(request),
GaoSalesOrderChartAPI.customerSkuRank(request),
GaoSalesOrderChartAPI.consumptionDaily(request),
GaoSalesOrderChartAPI.calendar(request),
GaoSalesOrderChartAPI.repeatDaily(request),
GaoSalesOrderChartAPI.repeatInterval(request)
]);
if (currentRequestId !== requestId) {
return;
}
dailyList.value = daily || [];
productRankList.value = productRank || [];
skuRankList.value = skuRank || [];
consumptionDailyList.value = consumptionDaily || [];
calendarList.value = calendar || [];
repeatDailyList.value = repeatDaily || [];
repeatIntervalList.value = repeatInterval || [];
} catch (error) {
if (currentRequestId === requestId) {
Message.error(getErrorMessage(error, "客户订单图表加载失败"));
}
} finally {
if (currentRequestId === requestId) {
isLoading.value = false;
}
}
}
function clearData(): void {
isLoading.value = false;
dailyList.value = [];
productRankList.value = [];
skuRankList.value = [];
consumptionDailyList.value = [];
calendarList.value = [];
repeatDailyList.value = [];
repeatIntervalList.value = [];
}
function getDateStart(dateText: string): number {
const [year, month, day] = dateText.split("-").map(Number);
return new Date(year, month - 1, day, 0, 0, 0, 0).getTime();
}
function getDateEnd(dateText: string): number {
const [year, month, day] = dateText.split("-").map(Number);
return new Date(year, month - 1, day, 23, 59, 59, 999).getTime();
}
</script>
<style scoped lang="less">
.order-charts {
gap: 1rem;
display: flex;
flex-direction: column;
.section-heading {
gap: .5rem;
padding: 0 .25rem;
display: flex;
align-items: flex-end;
justify-content: space-between;
}
.eyebrow {
color: var(--td-brand-color);
font-size: .6875rem;
font-weight: 700;
letter-spacing: .12em;
}
h2 {
color: #0f172a;
margin: .25rem 0 0;
font-size: 1.125rem;
}
.section-heading > span {
color: #94a3b8;
font-size: .6875rem;
}
.two-columns {
gap: 1rem;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
:global(html.theme-dark) {
.order-charts {
h2 {
color: #e2e8f0;
}
}
}
@media (max-width: 42rem) {
.order-charts {
.two-columns {
grid-template-columns: 1fr;
}
}
}
</style>
@@ -0,0 +1,81 @@
<template>
<gao-chart-card
title="客户产品购买排行"
caption="基础单位购买及履约进度,前 10"
:option="chartOption"
:loading="loading"
:has-data="list.length > 0"
height="20rem"
/>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import GaoChartCard from "@/pages/product/component/GaoChartCard.vue";
import type { GaoCustomerOrderProductRankView } from "@/types/GaoChart";
import { buildHorizontalBarOption, getNumber } from "@/pages/product/component/chartUtils";
defineOptions({
name: "CustomerOrderProductRankChart"
});
const props = defineProps<{
list: GaoCustomerOrderProductRankView[];
loading: boolean;
}>();
const chartOption = computed<EChartsOption>(() => {
const list = props.list.slice(0, 10);
return {
...buildHorizontalBarOption(list.map(getProductName)),
legend: {
top: 0,
icon: "roundRect",
textStyle: { color: "#52607a" }
},
grid: {
top: 32,
left: 8,
right: 18,
bottom: 12,
containLabel: true
},
series: [
{
name: "直接购买",
type: "bar",
stack: "quantity",
data: list.map(item => getNumber(item.directBaseQuantity))
},
{
name: "套餐权益",
type: "bar",
stack: "quantity",
data: list.map(item => getNumber(item.packageBaseQuantity))
},
{
name: "待履约",
type: "bar",
stack: "fulfillment",
data: list.map(item => getNumber(item.reservedBaseQuantity))
},
{
name: "已履约",
type: "bar",
stack: "fulfillment",
data: list.map(item => getNumber(item.fulfilledBaseQuantity))
},
{
name: "可履约",
type: "bar",
stack: "fulfillment",
data: list.map(item => getNumber(item.availableBaseQuantity))
}
]
};
});
function getProductName(item: GaoCustomerOrderProductRankView): string {
return item.productName || "未命名产品";
}
</script>
@@ -0,0 +1,81 @@
<template>
<gao-chart-card
title="客户 SKU 购买排行"
caption="基础单位购买及履约进度,前 10"
:option="chartOption"
:loading="loading"
:has-data="list.length > 0"
height="20rem"
/>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import GaoChartCard from "@/pages/product/component/GaoChartCard.vue";
import type { GaoCustomerOrderSkuRankView } from "@/types/GaoChart";
import { buildHorizontalBarOption, getNumber } from "@/pages/product/component/chartUtils";
defineOptions({
name: "CustomerOrderSkuRankChart"
});
const props = defineProps<{
list: GaoCustomerOrderSkuRankView[];
loading: boolean;
}>();
const chartOption = computed<EChartsOption>(() => {
const list = props.list.slice(0, 10);
return {
...buildHorizontalBarOption(list.map(getSkuName)),
legend: {
top: 0,
icon: "roundRect",
textStyle: { color: "#52607a" }
},
grid: {
top: 32,
left: 8,
right: 18,
bottom: 12,
containLabel: true
},
series: [
{
name: "直接购买",
type: "bar",
stack: "quantity",
data: list.map(item => getNumber(item.directBaseQuantity))
},
{
name: "套餐权益",
type: "bar",
stack: "quantity",
data: list.map(item => getNumber(item.packageBaseQuantity))
},
{
name: "待履约",
type: "bar",
stack: "fulfillment",
data: list.map(item => getNumber(item.reservedBaseQuantity))
},
{
name: "已履约",
type: "bar",
stack: "fulfillment",
data: list.map(item => getNumber(item.fulfilledBaseQuantity))
},
{
name: "可履约",
type: "bar",
stack: "fulfillment",
data: list.map(item => getNumber(item.availableBaseQuantity))
}
]
};
});
function getSkuName(item: GaoCustomerOrderSkuRankView): string {
return [item.skuName || item.skuCode || "未命名规格", item.specSummary].filter(Boolean).join(" · ");
}
</script>
@@ -0,0 +1,61 @@
<template>
<gao-chart-card
title="复购趋势"
caption="缺失日期按 0 展示"
:date-text-list="dateTextList"
:option="buildOption"
:loading="loading"
:has-data="list.length > 0"
height="18rem"
/>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import GaoChartCard from "@/pages/product/component/GaoChartCard.vue";
import type { GaoCustomerRepeatDailyStatView } from "@/types/GaoChart";
import { buildAxisChartOption, getDailyItem, getNumber } from "@/pages/product/component/chartUtils";
defineOptions({
name: "CustomerRepeatDailyChart"
});
const props = defineProps<{
dateTextList: string[];
list: GaoCustomerRepeatDailyStatView[];
loading: boolean;
}>();
function buildOption(visibleDateTextList: string[]): EChartsOption {
const labelList = visibleDateTextList.map(item => item.slice(5));
return {
...buildAxisChartOption(labelList),
xAxis: {
type: "category",
data: labelList,
axisTick: { show: false },
axisLabel: { color: "#52607a", interval: "auto", hideOverlap: true }
},
series: [
{
name: "客户数",
type: "line",
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.customerCount))
},
{
name: "复购客户",
type: "line",
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.repeatCustomerCount))
},
{
name: "复购订单",
type: "line",
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.repeatOrderCount))
}
]
};
}
</script>
@@ -0,0 +1,43 @@
<template>
<gao-chart-card
title="复购间隔"
caption="按间隔天数统计订单数"
:option="chartOption"
:loading="loading"
:has-data="list.length > 0"
height="18rem"
/>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import GaoChartCard from "@/pages/product/component/GaoChartCard.vue";
import type { GaoCustomerRepeatIntervalStatView } from "@/types/GaoChart";
import { buildHorizontalBarOption, getNumber } from "@/pages/product/component/chartUtils";
defineOptions({
name: "CustomerRepeatIntervalChart"
});
const props = defineProps<{
list: GaoCustomerRepeatIntervalStatView[];
loading: boolean;
}>();
const chartOption = computed<EChartsOption>(() => {
const list = [...props.list].sort((left, right) => getNumber(left.intervalDays) - getNumber(right.intervalDays));
return {
...buildHorizontalBarOption(list.map(getIntervalText)),
legend: { show: false },
series: [{
name: "复购订单",
type: "bar",
data: list.map(item => getNumber(item.orderCount))
}]
};
});
function getIntervalText(item: GaoCustomerRepeatIntervalStatView): string {
return `${getNumber(item.intervalDays)} 天`;
}
</script>
@@ -24,7 +24,7 @@
</div>
<div class="main">
<div class="title">
<strong v-text="item.productNameSnapshot" />
<strong v-text="getItemTitle(item)" />
<span v-text="getItemDescription(item)" />
</div>
<div class="input">
@@ -140,7 +140,12 @@ function getAvailableQuantity(item: GaoSalesOrderItem): string {
}
function getItemDescription(item: GaoSalesOrderItem): string {
return ` · 剩余 ${getAvailableQuantity(item)}`;
return ` · ${item.unitSnapshot || "业务单位"} · 剩余 ${getAvailableQuantity(item)}`;
}
function getItemTitle(item: GaoSalesOrderItem): string {
const skuText = item.skuNameSnapshot || item.specSummarySnapshot;
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""}`;
}
function fillAllQuantity(item: GaoSalesOrderItem): void {
@@ -30,7 +30,7 @@
class="item"
v-for="item in fulfillment.itemList || []"
:key="item.id"
:title="item.productNameSnapshot"
:title="getItemTitle(item)"
:description="`${item.quantity} ${item.unitSnapshot}`"
:note="`待履约 ${item.reservedBefore || 0} → ${item.reservedAfter || 0}`"
>
@@ -174,6 +174,11 @@ const sourceItemType = computed<GaoSalesOrderItemType | undefined>(() => {
const sourceOrderItemId = fulfillment.value?.itemList?.[0]?.sourceOrderItemId;
return order.value?.itemList?.find(item => item.id === sourceOrderItemId)?.itemType;
});
function getItemTitle(item: NonNullable<OrderFulfillment["itemList"]>[number]): string {
const skuText = item.skuNameSnapshot || item.specSummarySnapshot;
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""}`;
}
async function loadData(): Promise<void> {
const id = String(route.params.id || "");
if (!id) return;
@@ -31,7 +31,7 @@
<div class="items">
<t-tag
v-for="(item, index) in itemList"
:key="item.id || `${item.productId}-${index}`"
:key="item.id || `${item.skuId}-${item.skuUnitId}-${index}`"
:content="getProductText(item)"
theme="primary"
variant="light"
@@ -101,9 +101,10 @@ const productSummaryText = computed(() => `共 ${itemList.value.length} 项 ·
function getProductText(item: OrderFulfillmentItem): string {
const productName = item.productNameSnapshot || "未命名产品";
const skuText = item.skuNameSnapshot || item.specSummarySnapshot;
const quantity = getPackageQuantityText(item.quantity);
const unit = item.unitSnapshot ? ` ${item.unitSnapshot}` : "";
return `${productName} × ${quantity}${unit}`;
return `${productName}${skuText ? ` · ${skuText}` : ""} × ${quantity}${unit}`;
}
function getUserName(user: OrderFulfillment["operator"], userId: string | undefined, fallback: string): string {
+10 -5
View File
@@ -30,8 +30,8 @@
<t-cell
class="item"
v-for="item in config.itemList || []"
:title="item.productNameSnapshot"
:key="item.id || `${item.productId}-${item.productUnitId}`"
:title="getItemTitle(item)"
:key="item.id || `${item.skuId}-${item.skuUnitId}`"
:note="`${item.defaultQuantity} ${item.unitSnapshot || ''}${item.remark ? `|${item.remark}` : ''}`"
>
<template #leftIcon>
@@ -50,7 +50,7 @@
</template>
<template #description>
<t-tag
:content="getProductTypeText(item.product?.productType)"
:content="item.skuCodeSnapshot || item.sku?.code || 'SKU'"
theme="primary"
variant="light"
/>
@@ -89,7 +89,7 @@ import { getErrorMessage } from "@/utils/error";
import { formatPackageAmount, getPackageConfigStatusText } from "@/utils/package";
import { Message } from "@/utils/message";
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
import { getProductPhotoURL as getProductPhotoUrl, getProductTypeText } from "@/utils/product";
import { getProductPhotoURL as getProductPhotoUrl } from "@/utils/product";
defineOptions({ name: "PackageConfigDetail" });
@@ -113,7 +113,12 @@ function getStatusTheme(status?: PackageConfigStatus): "success" | "warning" | "
}
function getItemPhotoURL(item: PackageConfigItem): string {
return getProductPhotoUrl(item.product || {});
return getProductPhotoUrl(item.sku || {});
}
function getItemTitle(item: PackageConfigItem): string {
const skuText = item.skuNameSnapshot || item.specSummarySnapshot;
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""}`;
}
async function loadData(): Promise<void> {
+48 -56
View File
@@ -34,7 +34,7 @@
>
<div class="header">
<span class="no" v-text="String(index + 1).padStart(2, '0')" />
<strong v-text="item.productNameSnapshot || '未选择产品'" />
<strong v-text="getItemTitle(item)" />
<t-button
v-if="1 < form.itemList.length"
theme="danger"
@@ -44,26 +44,15 @@
>删除</t-button>
</div>
<product-selector
:model-value="item.productId ? {productId: item.productId, productUnitId: item.productUnitId || ''} : undefined"
:model-value="item.skuId ? { skuId: item.skuId, skuUnitId: item.skuUnitId || '' } : undefined"
:selected-product="getProduct(item)"
label="产品"
placeholder="请选择产品"
required-mark
@update:model-value="applyProduct(index, $event)"
/>
<t-form-item v-if="item.productId" label="产品单位" required-mark>
<div v-if="getSaleableUnits(item).length" class="unit-list">
<t-button
v-for="unit in getSaleableUnits(item)"
:key="unit.id"
:theme="item.productUnitId === unit.id ? 'primary' : 'default'"
:variant="item.productUnitId === unit.id ? 'base' : 'outline'"
size="extra-small"
:content="unit.name"
@click="selectProductUnit(index, unit)"
/>
</div>
<span v-else class="unit-empty" v-text="'暂无可售单位'" />
<t-form-item v-if="item.skuId" label="SKU 单位" content-align="right">
<span v-text="getUnit(item)?.name || '未选择单位'" />
</t-form-item>
<t-form-item label="默认配额" content-align="right" required-mark>
<t-stepper
@@ -72,7 +61,7 @@
:max="Number.MAX_SAFE_INTEGER"
:min="getQuantityStep(item)"
:step="getQuantityStep(item)"
:integer="!getProduct(item)?.allowDecimalQuantity"
:integer="!getSku(item)?.allowDecimalQuantity"
theme="outline"
/>
</t-form-item>
@@ -122,7 +111,7 @@ import { useCurrentStoreStore } from "@/store/currentStoreStore";
import { useNavBarStore } from "@/store/navBarStore";
import type { GaoPackageConfig, PackageConfigItem, PackageConfigStatus } from "@/types/Package";
import ProductAPI from "@/api/ProductAPI";
import type { Product, ProductUnit } from "@/types/Product";
import type { Product, ProductSku, ProductSkuUnit } from "@/types/Product";
import { getErrorMessage } from "@/utils/error";
import { formatPackageAmountInput, getPackageConfigStatusText, normalizePackageQuantity, parsePackageAmount } from "@/utils/package";
import { Message } from "@/utils/message";
@@ -178,13 +167,28 @@ function createItem(item?: Partial<PackageConfigItem>): PackageConfigFormItem {
}
const productCache = new Map<string, Product>();
const skuCache = new Map<string, ProductSku>();
function getProduct(item: PackageConfigFormItem): Product | undefined {
return productCache.get(item.productId || "");
const sku = getSku(item);
return productCache.get(sku?.productId || "");
}
function getSku(item: PackageConfigFormItem): ProductSku | undefined {
return skuCache.get(item.skuId || "") || item.sku;
}
function getUnit(item: PackageConfigFormItem): ProductSkuUnit | undefined {
return getSku(item)?.unitList?.find(unit => unit.id === item.skuUnitId);
}
function getItemTitle(item: PackageConfigFormItem): string {
const sku = getSku(item);
return sku?.specSummary || sku?.name || item.productNameSnapshot || "未选择产品";
}
function getQuantityStep(item: PackageConfigFormItem): number {
return getProductQuantityStep(getProduct(item));
return getProductQuantityStep(getSku(item));
}
const estimatedOriginalAmount = computed<number | undefined>(() => {
@@ -200,45 +204,29 @@ const estimatedOriginalAmount = computed<number | undefined>(() => {
});
const estimatedOriginalAmountText = computed(() => estimatedOriginalAmount.value === undefined ? "待完善" : `¥${formatProductAmount(estimatedOriginalAmount.value)}`);
async function applyProduct(index: number, value?: { productId: string; productUnitId: string }): Promise<void> {
async function applyProduct(index: number, value?: { skuId: string; skuUnitId: string }): Promise<void> {
if (!value) {
return;
}
const product = productCache.get(value.productId) || await ProductAPI.detail(value.productId);
productCache.set(value.productId, product);
const saleableUnits = (product.unitList || []).filter(unit => unit.allowSale !== false && unit.id);
const productUnitId = saleableUnits.length < 2 ? saleableUnits[0]?.id || "" : value.productUnitId;
const unit = saleableUnits.find(item => item.id === productUnitId);
const sku = skuCache.get(value.skuId) || await ProductAPI.skuDetail(value.skuId);
skuCache.set(value.skuId, sku);
const product = productCache.get(sku.productId || "") || await ProductAPI.detail(sku.productId || "");
productCache.set(sku.productId || "", product);
const unit = (sku.unitList || []).find(item => item.id === value.skuUnitId);
Object.assign(form.itemList[index], {
productId: value.productId,
productUnitId,
skuId: value.skuId,
skuUnitId: value.skuUnitId,
productNameSnapshot: product.name,
skuNameSnapshot: sku.name,
specSummarySnapshot: sku.specSummary,
unitSnapshot: unit?.name || "",
baseQuantityPerUnitSnapshot: unit?.baseQuantityPerUnit
});
}
function getSaleableUnits(item: PackageConfigFormItem): ProductUnit[] {
return (productCache.get(item.productId || "")?.unitList || []).filter(unit => unit.allowSale !== false && unit.id);
}
function selectProductUnit(index: number, unit: ProductUnit): void {
const item = form.itemList[index];
const product = productCache.get(item.productId || "");
if (!product?.id || !unit.id) {
return;
}
Object.assign(item, {
productUnitId: unit.id,
productNameSnapshot: product.name,
unitSnapshot: unit.name,
baseQuantityPerUnitSnapshot: unit.baseQuantityPerUnit
});
}
function calculateOriginalAmount(item: PackageConfigFormItem): number | undefined {
const quantity = normalizePackageQuantity(item.defaultQuantity ?? "");
const salePrice = productCache.get(item.productId || "")?.unitList?.find(unit => unit.id === item.productUnitId)?.salePrice;
const salePrice = getUnit(item)?.salePrice;
if (!quantity || quantity === "0" || salePrice === undefined || salePrice === null) {
return undefined;
}
@@ -331,13 +319,13 @@ function validateForm(): boolean {
const keySet = new Set<string>();
for (const item of form.itemList) {
const quantity = normalizePackageQuantity(item.defaultQuantity ?? "");
const key = `${item.productId}\u0000${item.productUnitId}`;
if (!item.productId || !item.productUnitId || !quantity || quantity === "0") {
Message.warning("产品单位和正数量不能为空");
const key = `${item.skuId}\u0000${item.skuUnitId}`;
if (!item.skuId || !item.skuUnitId || !quantity || quantity === "0") {
Message.warning("SKU 单位和正数量不能为空");
return false;
}
if (getProduct(item) && !getProduct(item)!.allowDecimalQuantity && quantity.includes(".")) {
Message.warning("该产品不允许小数数量");
if (getSku(item) && !getSku(item)!.allowDecimalQuantity && quantity.includes(".")) {
Message.warning("该 SKU 不允许小数数量");
return false;
}
if (keySet.has(key)) {
@@ -371,8 +359,8 @@ async function save(): Promise<void> {
beginAt: form.beginAt ?? null,
endAt: form.endAt ?? null,
itemList: form.itemList.map((item, index) => ({
productId: item.productId!,
productUnitId: item.productUnitId!,
skuId: item.skuId!,
skuUnitId: item.skuUnitId!,
defaultQuantity: normalizePackageQuantity(item.defaultQuantity ?? "")!,
sort: index,
remark: item.remark?.trim() || null
@@ -408,9 +396,13 @@ async function loadData(): Promise<void> {
}
const result = await PackageAPI.configDetail(routeId.value);
const itemList = (result.itemList || []).map(createItem);
const productIdList = [...new Set(itemList.map(item => item.productId).filter((id): id is string => !!id))];
await Promise.all(productIdList.map(async productId => {
productCache.set(productId, await ProductAPI.detail(productId));
const skuIdList = [...new Set(itemList.map(item => item.skuId).filter((id): id is string => !!id))];
await Promise.all(skuIdList.map(async skuId => {
const sku = itemList.find(item => item.skuId === skuId)?.sku || await ProductAPI.skuDetail(skuId);
skuCache.set(skuId, sku);
if (sku.productId) {
productCache.set(sku.productId, await ProductAPI.detail(sku.productId));
}
}));
Object.assign(form, {
id: result.id || routeId.value,
+3 -2
View File
@@ -46,7 +46,7 @@
<div class="products">
<t-tag
v-for="productItem in item.itemList || []"
:key="productItem.id || `${productItem.productId}-${productItem.productUnitId}`"
:key="productItem.id || `${productItem.skuId}-${productItem.skuUnitId}`"
:content="getProductRightText(productItem)"
theme="primary"
variant="light"
@@ -193,7 +193,8 @@ function getStatusTheme(statusValue?: PackageConfigStatus): "success" | "warning
function getProductRightText(item: PackageConfigItem): string {
const quantity = getPackageQuantityText(item.defaultQuantity);
return `${item.productNameSnapshot || "未命名产品"} × ${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
const skuText = item.skuNameSnapshot || item.specSummarySnapshot;
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""} × ${quantity}${item.unitSnapshot ? ` ${item.unitSnapshot}` : ""}`;
}
onMounted(async () => {
+7 -7
View File
@@ -75,7 +75,7 @@
</div>
<t-form-item
v-for="(item, index) in packagePurchaseItemList"
:key="`${index}-${item.productId}-${item.productUnitId}`"
:key="`${index}-${item.skuId}-${item.skuUnitId}`"
class="item"
>
<template #label>
@@ -374,21 +374,21 @@ const {
});
function getItemLabel(item: PackagePurchaseItem): string {
const configItem = config.value?.itemList?.find(configItem => configItem.productId === item.productId && configItem.productUnitId === item.productUnitId);
return configItem ? `${configItem.productNameSnapshot || "未命名产品"}` : "产品权益";
const configItem = config.value?.itemList?.find(configItem => configItem.skuId === item.skuId && configItem.skuUnitId === item.skuUnitId);
return configItem ? `${configItem.productNameSnapshot || "未命名产品"} · ${configItem.skuNameSnapshot || configItem.specSummarySnapshot || "默认 SKU"}` : "产品权益";
}
function getItemName(item: PackagePurchaseItem): string {
return config.value?.itemList?.find(configItem => configItem.productId === item.productId && configItem.productUnitId === item.productUnitId)?.productNameSnapshot || "未命名产品";
return config.value?.itemList?.find(configItem => configItem.skuId === item.skuId && configItem.skuUnitId === item.skuUnitId)?.productNameSnapshot || "未命名产品";
}
function getItemPhotoURL(item: PackagePurchaseItem): string {
const configItem = config.value?.itemList?.find(configItem => configItem.productId === item.productId && configItem.productUnitId === item.productUnitId);
return getProductPhotoURL(configItem?.product || {});
const configItem = config.value?.itemList?.find(configItem => configItem.skuId === item.skuId && configItem.skuUnitId === item.skuUnitId);
return getProductPhotoURL(configItem?.sku || {});
}
function getItemUnit(item: PackagePurchaseItem): string {
return config.value?.itemList?.find(configItem => configItem.productId === item.productId && configItem.productUnitId === item.productUnitId)?.unitSnapshot || "";
return config.value?.itemList?.find(configItem => configItem.skuId === item.skuId && configItem.skuUnitId === item.skuUnitId)?.unitSnapshot || "";
}
function updateItemQuantity(index: number, value: string | number): void {
+11 -6
View File
@@ -42,8 +42,8 @@ export function usePackagePurchase(options: UsePackagePurchaseOptions) {
}
saleAmountText.value = formatPackageAmountInput(config.standardAmount);
packagePurchaseItemList.value = (config.itemList || []).map((item, index) => ({
productId: item.productId,
productUnitId: item.productUnitId,
skuId: item.skuId,
skuUnitId: item.skuUnitId,
totalQuantity: normalizePackageQuantity(item.defaultQuantity) || "",
sort: item.sort ?? index,
remark: item.remark ?? null
@@ -79,8 +79,8 @@ export function usePackagePurchase(options: UsePackagePurchaseOptions) {
purchasedAt: options.buildRegisteredAt(),
attachmentList: options.buildAttachments(),
itemList: packagePurchaseItemList.value.length ? packagePurchaseItemList.value.map((item, index) => ({
productId: item.productId,
productUnitId: item.productUnitId,
skuId: item.skuId,
skuUnitId: item.skuUnitId,
totalQuantity: normalizePackageQuantity(item.totalQuantity)!,
sort: item.sort ?? index,
remark: item.remark ?? null
@@ -112,8 +112,13 @@ export function usePackagePurchase(options: UsePackagePurchaseOptions) {
}
for (const item of packagePurchaseItemList.value) {
const quantity = normalizePackageQuantity(item.totalQuantity);
if (!item.productId || !item.productUnitId || !quantity || quantity === "0") {
Message.warning("产品单位和正数量不能为空");
if (!item.skuId || !item.skuUnitId || !quantity || quantity === "0") {
Message.warning("SKU 单位和正数量不能为空");
return false;
}
const configItem = options.config.value.itemList?.find(source => source.skuId === item.skuId && source.skuUnitId === item.skuUnitId);
if (configItem?.sku && !configItem.sku.allowDecimalQuantity && quantity.includes(".")) {
Message.warning("该 SKU 不允许小数数量");
return false;
}
}
+20 -4
View File
@@ -49,6 +49,7 @@
<product-stock-health-table
v-entrance-transition="350"
:list="stockHealthList"
:sku-health-list="skuHealthList"
:loading="isLoading"
/>
</div>
@@ -58,6 +59,7 @@
<script setup lang="ts">
import GaoProductChartAPI from "@/api/GaoProductChartAPI";
import GaoProductSkuChartAPI from "@/api/GaoProductSkuChartAPI";
import ProductFulfillmentRankChart from "@/pages/product/component/ProductFulfillmentRankChart.vue";
import ProductFulfillmentTrendChart from "@/pages/product/component/ProductFulfillmentTrendChart.vue";
import ProductSalesRankChart from "@/pages/product/component/ProductSalesRankChart.vue";
@@ -70,7 +72,8 @@ import type {
GaoProductSalesDailyStatView,
GaoProductSalesRankView,
GaoProductStockHealthView,
GaoProductStockMovementDailyStatView
GaoProductStockMovementDailyStatView,
GaoProductSkuStockHealthView
} from "@/types/GaoChart";
import { useCurrentStoreStore } from "@/store/currentStoreStore";
import { useNavBarStore } from "@/store/navBarStore";
@@ -100,6 +103,7 @@ const fulfillmentDailyList = ref<GaoProductFulfillmentDailyStatView[]>([]);
const fulfillmentRankList = ref<GaoProductFulfillmentRankView[]>([]);
const stockMovementList = ref<GaoProductStockMovementDailyStatView[]>([]);
const stockHealthList = ref<GaoProductStockHealthView[]>([]);
const skuHealthList = ref<GaoProductSkuStockHealthView[]>([]);
const isLoading = ref(false);
let requestId = 0;
@@ -111,11 +115,11 @@ const summaryList = computed<SummaryItem[]>(() => [
},
{
label: "直接销量",
value: formatQuantity(sumNumber(salesDailyList.value, item => item.directQuantity))
value: formatQuantity(sumNumber(salesDailyList.value, item => item.directBaseQuantity))
},
{
label: "套餐权益",
value: formatQuantity(sumNumber(salesDailyList.value, item => item.packageQuantity))
value: formatQuantity(sumNumber(salesDailyList.value, item => item.packageBaseQuantity))
},
{
label: "直接销售额",
@@ -123,7 +127,7 @@ const summaryList = computed<SummaryItem[]>(() => [
},
{
label: "低库存产品",
value: `${stockHealthList.value.filter(item => item.lowStock === 1).length} 个`
value: `${stockHealthList.value.filter(item => 0 < (item.lowStockSkuCount || 0)).length} 个`
}
]);
@@ -176,6 +180,17 @@ async function loadCharts(): Promise<void> {
fulfillmentRankList.value = fulfillmentRank || [];
stockMovementList.value = stockMovement || [];
stockHealthList.value = stockHealth || [];
skuHealthList.value = [];
if (stockHealthList.value.some(item => 0 < (item.lowStockSkuCount || 0))) {
try {
const skuHealth = await GaoProductSkuChartAPI.stockHealth({ storeId: storeId.value });
if (currentRequestId === requestId) {
skuHealthList.value = (skuHealth || []).filter(item => item.lowStock === 1);
}
} catch (error) {
Message.warning(getErrorMessage(error, "低库存规格明细加载失败"));
}
}
} catch (error) {
if (currentRequestId === requestId) {
Message.error(getErrorMessage(error, "产品图表加载失败"));
@@ -195,6 +210,7 @@ function clearData(): void {
fulfillmentRankList.value = [];
stockMovementList.value = [];
stockHealthList.value = [];
skuHealthList.value = [];
}
function buildDefaultDateRange(): [string, string] {
+21 -36
View File
@@ -23,59 +23,40 @@
<t-cell
v-if="product.stockEnabled && userStore.hasPermissions(permissionCodes.productStock.read)"
title="库存"
note="查看库存详情"
:note="product.skuList?.length === 1 ? '查看 SKU 库存详情' : '查看全部 SKU 库存'"
arrow
@click="viewStock"
/>
</t-cell-group>
<t-cell-group title="业务单位" theme="card" class="units" v-entrance-transition="210">
<t-cell-group title="SKU 列表" theme="card" class="units" v-entrance-transition="210">
<t-cell
v-for="unit in product.unitList || []"
:key="unit.id || unit.name"
v-for="sku in product.skuList || []"
:key="sku.id || sku.code"
>
<template #title>
<div class="title">
<h3 class="name" v-text="unit.name || '未命名单位'" />
<t-tag
v-if="!unit.isBase"
theme="default"
size="small"
:content="`${unit.baseQuantityPerUnit} ${getProductBaseUnitName(product)}`"
/>
<h3 class="name" v-text="getSkuTitle(sku)" />
<t-tag size="small" variant="light-outline" :theme="sku.status === 'ACTIVE' ? 'success' : 'warning'" :content="sku.status === 'ACTIVE' ? '启用' : '停用'" />
</div>
</template>
<template #note>
<span class="price">
<span class="qute red text-bold">¥</span>
<span
class="value text-bold red"
v-text="formatProductAmount(unit.salePrice)"
/>
<span class="value text-bold" v-text="sku.code || '无编码'" />
</span>
</template>
<template #description>
<div class="tags">
<t-tag
v-if="unit.isBase"
theme="warning"
variant="light-outline"
content="基础单位"
/>
<t-tag
v-if="unit.allowSale"
v-for="unit in sku.unitList || []"
:key="unit.id || unit.name"
theme="primary"
variant="light-outline"
content="可销售"
/>
<t-tag
v-if="unit.allowPurchase"
theme="primary"
variant="light-outline"
content="可采购"
:content="`${unit.name}${unit.isBase ? '(基础)' : ''}`"
/>
</div>
</template>
</t-cell>
<div v-if="!product.skuList?.length" class="empty" v-text="'暂无 SKU'" />
</t-cell-group>
</template>
</div>
@@ -95,11 +76,7 @@ import type { PhotoItem } from "@/types/Photo";
import type { Product } from "@/types/Product";
import { getAttachmentReadURL } from "@/utils/attachment";
import { getErrorMessage } from "@/utils/error";
import {
formatProductAmount,
getProductBaseUnitName,
getProductStatusText
} from "@/utils/product";
import { getProductStatusText } from "@/utils/product";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { Text } from "timi-web";
@@ -153,14 +130,22 @@ async function edit(): Promise<void> {
async function viewStock(): Promise<void> {
if (product.value?.id) {
if (product.value.skuList?.length === 1 && product.value.skuList[0]?.id) {
await router.push({ name: "ProductStockDetail", params: { skuId: product.value.skuList[0].id }, query: { transitionDepth: String(getCurrentRouteDepth() + 1) } });
return;
}
await router.push({
name: "ProductStockDetail",
name: "ProductStockSkuList",
params: { productId: product.value.id },
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
}
function getSkuTitle(sku: NonNullable<Product["skuList"]>[number]): string {
return sku.specSummary || sku.name || "未命名 SKU";
}
function getCurrentRouteDepth(): number {
const transitionDepth = Array.isArray(route.query.transitionDepth)
? route.query.transitionDepth[0]
File diff suppressed because it is too large Load Diff
+22 -17
View File
@@ -1,9 +1,10 @@
<template>
<div v-can="permissionCodes.productStock.read" class="product-stock-detail">
<t-loading v-if="isLoading" class="loading" size="32px" />
<template v-else-if="product && stock">
<template v-else-if="product && sku && stock">
<product-profile :product="product" v-entrance-transition>
<template #tags>
<t-tag :content="sku?.specSummary || sku?.name || '默认 SKU'" variant="light-outline" theme="primary" />
<t-tag :content="getStockStatusText(stock)" variant="light-outline" :theme="getStockTheme(stock)" />
</template>
</product-profile>
@@ -18,29 +19,29 @@
<span class="label">库存</span>
<div class="value">
<strong class="text" v-text="getProductQuantityText(stock.onHandQuantity)" />
<span class="unit" v-text="getProductBaseUnitName(product) || '基础单位'" />
<span class="unit" v-text="getProductBaseUnitName(sku) || '基础单位'" />
</div>
</div>
<div class="footer">
<div class="available">
<span class="label">可用</span>
<strong class="value" v-text="getProductQuantityText(stock.availableQuantity)" />
<span class="unit" v-text="getProductBaseUnitName(product) || '基础单位'" />
<span class="unit" v-text="getProductBaseUnitName(sku) || '基础单位'" />
</div>
<div class="reserved">
<span class="label">预占</span>
<strong class="value" v-text="getProductQuantityText(stock.reservedQuantity)" />
<span class="unit" v-text="getProductBaseUnitName(product) || '基础单位'" />
<span class="unit" v-text="getProductBaseUnitName(sku) || '基础单位'" />
</div>
</div>
</div>
</template>
</t-cell>
<t-cell v-if="0 < Number(stock.reservedQuantity || 0)" title="查看预占流水" arrow @click="openReservedRecordList" />
<t-cell title="查看该产品流水" arrow @click="openRecordList" />
<t-cell title="查看该产品 SKU 流水" arrow @click="openRecordList" />
</t-cell-group>
<card-container
v-if="canOperate && product.stockEnabled"
v-if="canOperate && sku?.status === 'ACTIVE' && sku.stockEnabled"
class="actions-wrap"
title="库存操作"
description="所有操作必须选择业务单位、上传照片并填写备注"
@@ -65,9 +66,10 @@
</template>
<t-empty v-else description="库存或产品不存在" />
<product-stock-operation-popup
v-if="product && stock"
v-if="product && sku && stock"
v-model:visible="operationVisible"
:product="product"
:sku="sku"
:stock="stock"
:operation="operationType"
@success="loadAll"
@@ -81,7 +83,7 @@ import ProductAPI from "@/api/ProductAPI";
import ProductProfile from "@/pages/product/component/ProductProfile.vue";
import ProductStockOperationPopup from "@/pages/product/ProductStockOperationPopup.vue";
import { useNavBarStore } from "@/store/navBarStore";
import type { Product, ProductStock, StockOperationType } from "@/types/Product";
import type { Product, ProductSku, ProductStock, StockOperationType } from "@/types/Product";
import { getErrorMessage } from "@/utils/error";
import { getProductBaseUnitName, getProductQuantityText } from "@/utils/product";
import { Message } from "@/utils/message";
@@ -96,6 +98,7 @@ const router = useRouter();
const navBarStore = useNavBarStore();
const userStore = useUserStore();
const product = ref<Product>();
const sku = ref<ProductSku>();
const stock = ref<ProductStock>();
const isLoading = ref(false);
const operationVisible = ref(false);
@@ -109,36 +112,38 @@ const operationList: Array<{ text: string; icon: string; type: ManualStockOperat
];
function getStockStatusText(item: ProductStock): string {
if (!item.product?.stockEnabled) {
if (!item.sku?.stockEnabled) {
return "不管理库存";
}
const available = Number(item.availableQuantity || 0);
const min = Number(item.product.minStockQuantity || 0);
const min = Number(item.sku.minStockQuantity || 0);
return 0 < min && available < min ? "库存不足" : "库存正常";
}
function getStockTheme(item: ProductStock): "danger" | "success" | "default" {
if (!item.product?.stockEnabled) {
if (!item.sku?.stockEnabled) {
return "default";
}
const available = Number(item.availableQuantity || 0);
const min = Number(item.product.minStockQuantity || 0);
const min = Number(item.sku.minStockQuantity || 0);
return 0 < min && available < min ? "danger" : "success";
}
async function loadAll(): Promise<void> {
const productId = String(route.params.productId || "");
if (!productId) {
const skuId = String(route.params.skuId || "");
if (!skuId) {
return;
}
isLoading.value = true;
try {
const skuResult = await ProductAPI.skuDetail(skuId);
const [productResult, stockResult] = await Promise.all([
ProductAPI.detail(productId),
ProductAPI.stockDetail(productId)
ProductAPI.detail(skuResult.productId || ""),
ProductAPI.stockDetail(skuId)
]);
product.value = productResult;
stock.value = { ...stockResult, product: productResult };
sku.value = skuResult;
stock.value = { ...stockResult, sku: skuResult };
} finally {
isLoading.value = false;
}
+68 -38
View File
@@ -10,6 +10,7 @@
placeholder="搜索产品名称或编码"
/>
</div>
<t-pull-down-refresh
class="list-wrap empty-cell-title-margin"
v-model="isRefreshing"
@@ -17,41 +18,37 @@
@refresh="refresh"
@scrolltolower="loadMore"
>
<t-cell-group v-if="stockList.length" theme="card" class="list fix-last-cell-line">
<t-cell v-for="(item, index) in stockList" :key="item.productId || item.id" arrow hover class="item" v-entrance-transition="index * 30" @click="toDetail(item)">
<t-cell-group v-if="productList.length" theme="card" class="list fix-last-cell-line">
<t-cell
v-for="(item, index) in productList"
:key="item.productId"
arrow
hover
class="item"
v-entrance-transition="index * 30"
@click="toSkuList(item)"
>
<template #leftIcon>
<t-image
v-if="getProductPhotoURL(item.product!)"
:src="getProductPhotoURL(item.product!)"
:alt="item.product?.name || '产品图片'"
fit="cover"
class="avatar"
/>
<div
v-else
class="avatar fallback"
v-text="(item.product?.name || '产').slice(0, 1)"
/>
<div class="avatar fallback" v-text="(item.productName || '产').slice(0, 1)" />
</template>
<template #title>
<div class="title">
<strong v-text="item.product?.name || '未命名产品'" />
<t-tag
size="small"
variant="outline"
:content="item.product?.code || '无产品编码'"
/>
<strong v-text="item.productName || '未命名产品'" />
<t-tag size="small" variant="outline" :content="item.productCode || '无产品编码'" />
</div>
</template>
<template #note>
<span v-text="`${item.skuCount || 0} 个 SKU 明细`" />
</template>
<template #description>
<div class="stock">
<span class="on-hand">
<span>库存</span>
<strong v-text="getProductQuantityText(item.onHandQuantity)"/>
<strong v-text="getProductQuantityText(item.onHandQuantity)" />
</span>
<span class="available">
<span>可用</span>
<strong v-text="getProductQuantityText(item.availableQuantity)"/>
<strong v-text="getProductQuantityText(item.availableQuantity)" />
</span>
<span class="reserved">
<span>预占</span>
@@ -62,7 +59,7 @@
</t-cell>
</t-cell-group>
<div v-else class="center-tips" v-text="emptyText" />
<div v-if="stockList.length" class="center-tips" v-text="isLoading ? '正在加载更多' : isNoMore ? '已经到底了' : '上拉加载更多'" />
<div v-if="productList.length" class="center-tips" v-text="isLoading ? '正在加载更多' : isNoMore ? '已经到底了' : '上拉加载更多'" />
</t-pull-down-refresh>
</div>
</template>
@@ -71,19 +68,20 @@
import { useUserStore } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI";
import { useNavBarStore } from "@/store/navBarStore";
import type { ProductStock } from "@/types/Product";
import type { ProductStockProduct } from "@/types/Product";
import { getErrorMessage } from "@/utils/error";
import { getProductPhotoURL, getProductQuantityText } from "@/utils/product";
import { getProductQuantityText } from "@/utils/product";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
defineOptions({ name: "ProductStockList" });
const router = useRouter();
const route = useRoute();
const navBarStore = useNavBarStore();
const userStore = useUserStore();
const keyword = ref("");
const stockList = ref<ProductStock[]>([]);
const productList = ref<ProductStockProduct[]>([]);
const pageIndex = ref(0);
const total = ref(0);
const isLoading = ref(false);
@@ -92,7 +90,11 @@ const isNoMore = ref(false);
let keywordTimer: number | undefined;
let requestToken = 0;
const emptyText = computed(() => isLoading.value ? "正在加载库存" : keyword.value ? "未找到匹配产品" : "暂无启用库存管理的产品");
const emptyText = computed(() => isLoading.value ? "正在加载产品" : keyword.value ? "未找到匹配产品" : "暂无启用库存管理的产品");
function getCurrentRouteDepth(): number {
return Number(route.meta.depth ?? 0);
}
async function fetch(reset = false): Promise<void> {
if (!reset && (isLoading.value || isNoMore.value)) {
@@ -100,7 +102,7 @@ async function fetch(reset = false): Promise<void> {
}
if (reset) {
pageIndex.value = 0;
stockList.value = [];
productList.value = [];
total.value = 0;
isNoMore.value = false;
}
@@ -108,15 +110,19 @@ async function fetch(reset = false): Promise<void> {
isLoading.value = true;
try {
const pageSize = 15;
const result = await ProductAPI.stockList({ index: pageIndex.value, size: pageSize, keyword: keyword.value || undefined });
const result = await ProductAPI.stockProductList({
index: pageIndex.value,
size: pageSize,
keyword: keyword.value || undefined
});
if (token !== requestToken) {
return;
}
const list = result.list || [];
stockList.value = reset ? list : stockList.value.concat(list);
productList.value = reset ? list : productList.value.concat(list);
total.value = result.total || 0;
pageIndex.value += 1;
isNoMore.value = list.length < pageSize || stockList.value.length === total.value || total.value < stockList.value.length;
isNoMore.value = list.length < pageSize || productList.value.length === total.value || total.value < productList.value.length;
} finally {
if (token === requestToken) {
isLoading.value = false;
@@ -128,7 +134,7 @@ async function refresh(): Promise<void> {
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "库存列表加载失败"));
Message.error(getErrorMessage(error, "产品列表加载失败"));
} finally {
isRefreshing.value = false;
}
@@ -138,14 +144,19 @@ async function loadMore(): Promise<void> {
try {
await fetch();
} catch (error) {
Message.error(getErrorMessage(error, "库存列表加载失败"));
Message.error(getErrorMessage(error, "产品列表加载失败"));
}
}
async function toDetail(item: ProductStock): Promise<void> {
if (item.productId) {
await router.push(`/management/product-stocks/${item.productId}`);
async function toSkuList(item: ProductStockProduct): Promise<void> {
if (!item.productId) {
return;
}
await router.push({
name: "ProductStockSkuList",
params: { productId: item.productId },
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
onMounted(async () => {
@@ -156,7 +167,7 @@ onMounted(async () => {
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "库存列表加载失败"));
Message.error(getErrorMessage(error, "产品列表加载失败"));
}
});
@@ -166,7 +177,7 @@ watch(keyword, () => {
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "库存列表加载失败"));
Message.error(getErrorMessage(error, "产品列表加载失败"));
}
}, 300);
});
@@ -212,12 +223,31 @@ onUnmounted(() => {
height: 3.5rem;
}
.fallback {
color: var(--td-brand-color);
display: flex;
align-items: center;
justify-content: center;
background: var(--td-brand-color-1);
border-radius: .75rem;
font-size: 1.5rem;
font-weight: 700;
}
.title {
gap: .5rem;
min-width: 0;
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
strong {
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.stock {
@@ -70,9 +70,9 @@ import ProductAPI from "@/api/ProductAPI";
import PhotoScroller from "@/components/PhotoScroller.vue";
import type {
Product,
ProductSku,
ProductStock,
ProductStockChangeRequest,
ProductUnit,
StockOperationType
} from "@/types/Product";
import { getErrorMessage } from "@/utils/error";
@@ -86,6 +86,7 @@ type PickerValue = string | number;
interface Props {
product: Product;
sku: ProductSku;
stock?: ProductStock;
operation: ManualStockOperation;
}
@@ -108,7 +109,7 @@ const unitPickerZIndex = 12001;
const unitPickerOverlayZIndex = unitPickerZIndex - 1;
const isInbound = computed(() => props.operation === "MANUAL_IN" || props.operation === "STOCKTAKE_GAIN");
const selectableUnits = computed<ProductUnit[]>(() => (props.product.unitList || []).filter(unit => isInbound.value ? unit.allowPurchase : unit.allowSale));
const selectableUnits = computed(() => (props.sku.unitList || []).filter(unit => isInbound.value ? unit.allowPurchase : unit.allowSale));
const unitOptions = computed(() => [selectableUnits.value.map(unit => ({ label: unit.name || "未命名单位", value: unit.id || "" }))]);
const selectedUnitName = computed(() => selectableUnits.value.find(unit => unit.id === selectedUnitId.value)?.name || "选择业务单位");
const quickRemarkText = computed(() => props.operation === "MANUAL_IN" ? "正常入库" : props.operation === "MANUAL_OUT" ? "正常出库" : "");
@@ -148,7 +149,7 @@ function validate(): boolean {
Message.warning("数量必须是大于 0 的数字,最多三位小数");
return false;
}
if (!props.product.allowDecimalQuantity && !/^\d+$/.test(quantity.value)) {
if (!props.sku.allowDecimalQuantity && !/^\d+$/.test(quantity.value)) {
Message.warning("该产品不允许输入小数数量");
return false;
}
@@ -166,8 +167,8 @@ function validate(): boolean {
function buildRequest(): ProductStockChangeRequest {
return {
requestNo: requestNo.value || (requestNo.value = createProductRequestNo()),
productId: props.product.id || "",
productUnitId: selectedUnitId.value,
skuId: props.sku.id || "",
skuUnitId: selectedUnitId.value,
quantity: quantity.value,
remark: remark.value.trim(),
attachmentList: photoItems.value.flatMap(item => item.tempFileId ? [{ tempFileId: item.tempFileId, attachType: item.attachType || "PHOTO" }] : [])
+50 -20
View File
@@ -1,17 +1,16 @@
<template>
<div v-can="permissionCodes.productStock.read" class="product-stock-record-detail">
<t-loading v-if="isLoading" class="loading" size="32px" />
<template v-else-if="record && product">
<product-profile :product="product" v-entrance-transition>
<template #tags>
<t-tag
size="small"
variant="light-outline"
:theme="getOperationTheme(record.onHandDelta)"
:content="getStockOperationText(record.operationType)"
/>
</template>
</product-profile>
<template v-else-if="record">
<section class="snapshot-head" v-entrance-transition>
<div class="eyebrow">库存 SKU 快照</div>
<h2 v-text="record.productNameSnapshot || '未命名产品'" />
<div class="sku" v-text="record.skuNameSnapshot || record.specSummarySnapshot || '默认 SKU'" />
<div class="meta">
<span v-text="record.skuCodeSnapshot || '无 SKU 编码'" />
<t-tag size="small" variant="light-outline" :theme="getOperationTheme(record.onHandDelta)" :content="getStockOperationText(record.operationType)" />
</div>
</section>
<card-container description="库存变动信息">
<div class="data">
<div class="card">
@@ -39,7 +38,7 @@
<span v-text="getProductQuantityText(record.onHandBefore)" />
<t-icon name="arrow-right" />
<span :class="getDeltaClass(record.onHandDelta)" v-text="getProductQuantityText(record.onHandAfter)" />
<span class="unit" v-text="getProductBaseUnitName(product) || '基础单位'" />
<span class="unit">基础单位</span>
</span>
</template>
</t-cell>
@@ -49,7 +48,7 @@
<span v-text="getProductQuantityText(record.reservedBefore)" />
<t-icon name="arrow-right" />
<span :class="getDeltaClass(record.reservedDelta)" v-text="getProductQuantityText(record.reservedAfter)" />
<span class="unit" v-text="getProductBaseUnitName(product) || '基础单位'" />
<span class="unit">基础单位</span>
</span>
</template>
</t-cell>
@@ -133,13 +132,12 @@ import { PassTimeLabel } from "timi-web";
import { useUserStore, type Attachment } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI";
import PhotoScroller from "@/components/PhotoScroller.vue";
import ProductProfile from "@/pages/product/component/ProductProfile.vue";
import { useNavBarStore } from "@/store/navBarStore";
import type { PhotoItem } from "@/types/Photo";
import type { Product, StockBizType, StockRecord } from "@/types/Product";
import type { StockBizType, StockRecord } from "@/types/Product";
import { getAttachmentReadURL } from "@/utils/attachment";
import { getErrorMessage } from "@/utils/error";
import { createProductRequestNo, getProductBaseUnitName, getProductQuantityText, getStockOperationText } from "@/utils/product";
import { createProductRequestNo, getProductQuantityText, getStockOperationText } from "@/utils/product";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { uploadPhotoList } from "@/utils/photo";
@@ -151,7 +149,6 @@ const navBarStore = useNavBarStore();
const router = useRouter();
const userStore = useUserStore();
const record = ref<StockRecord>();
const product = ref<Product>();
const isLoading = ref(false);
const isOperating = ref(false);
const revokeVisible = ref(false);
@@ -293,9 +290,6 @@ async function loadData(): Promise<void> {
try {
const result = await ProductAPI.recordDetail(id);
record.value = result;
if (result.productId) {
product.value = await ProductAPI.detail(result.productId);
}
} catch (error) {
Message.error(getErrorMessage(error, "库存流水加载失败"));
} finally {
@@ -328,6 +322,42 @@ onUnmounted(() => navBarStore.clearRight());
margin: 3rem auto;
}
.snapshot-head {
margin: 0 1rem;
padding: 1rem;
background: var(--td-bg-color-container);
box-shadow: var(--td-shadow-1);
border-radius: 1rem;
.eyebrow {
color: var(--td-brand-color);
font-size: .75rem;
font-weight: 700;
}
h2 {
margin: .5rem 0 .25rem;
font-size: 1.25rem;
}
.sku {
color: var(--td-text-color-secondary);
}
.meta {
gap: .5rem;
display: flex;
margin-top: .75rem;
align-items: center;
justify-content: space-between;
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
}
}
.positive {
color: var(--td-success-color);
}
+6 -1
View File
@@ -54,7 +54,7 @@
</template>
<template #description>
<div class="description">
<span v-text="record.productNameSnapshot || '未命名产品'" />
<span v-text="getRecordTitle(record)" />
<pass-time-label :timestamp="record.occurredAt" underline />
</div>
</template>
@@ -157,6 +157,11 @@ function getStockQuantityText(record: StockRecord): string {
return `${getProductQuantityText(record.quantity)}${unitText}`;
}
function getRecordTitle(record: StockRecord): string {
const skuText = record.skuNameSnapshot || record.specSummarySnapshot;
return `${record.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""}${record.unitSnapshot ? ` / ${record.unitSnapshot}` : ""}`;
}
function getDeltaText(value?: number | string): string {
const amount = Number(value || 0);
const text = String(value || "0").replace(/^-/, "");
+357
View File
@@ -0,0 +1,357 @@
<template>
<div v-can="permissionCodes.productStock.read" class="product-stock-sku-list">
<div class="product-context">
<strong v-text="product?.name || '产品 SKU'" />
<span v-text="product?.code || productId" />
</div>
<div class="search bg-white">
<t-input
v-model="keyword"
class="keyword"
type="search"
borderless
clearable
placeholder="搜索 SKU 名称、编码或规格"
/>
</div>
<t-pull-down-refresh
class="list-wrap empty-cell-title-margin"
v-model="isRefreshing"
:refresh-timeout="30000"
@refresh="refresh"
@scrolltolower="loadMore"
>
<t-cell-group v-if="skuStockList.length" theme="card" class="list fix-last-cell-line">
<t-cell
v-for="(item, index) in skuStockList"
:key="item.skuId || item.id"
arrow
hover
class="item"
v-entrance-transition="index * 30"
@click="toDetail(item)"
>
<template #leftIcon>
<div class="avatar fallback" v-text="(item.sku?.name || 'S').slice(0, 1)" />
</template>
<template #title>
<div class="title">
<strong v-text="item.sku?.name || '未命名 SKU 明细'" />
<t-tag size="small" variant="outline" :content="item.sku?.code || '无 SKU 编码'" />
</div>
</template>
<template #note>
<span class="sku-spec" v-text="getSkuSpecText(item)" />
</template>
<template #description>
<div class="stock">
<span class="on-hand">
<span>库存</span>
<strong v-text="getProductQuantityText(item.onHandQuantity)" />
</span>
<span class="available">
<span>可用</span>
<strong v-text="getProductQuantityText(item.availableQuantity)" />
</span>
<span class="reserved">
<span>预占</span>
<strong v-text="getProductQuantityText(item.reservedQuantity)" />
</span>
</div>
</template>
</t-cell>
</t-cell-group>
<div v-else class="center-tips" v-text="emptyText" />
<div v-if="skuStockList.length" class="center-tips" v-text="isLoading ? '正在加载更多' : isNoMore ? '已经到底了' : '上拉加载更多'" />
</t-pull-down-refresh>
</div>
</template>
<script setup lang="ts">
import { useUserStore } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI";
import { useNavBarStore } from "@/store/navBarStore";
import type { Product, ProductStock } from "@/types/Product";
import { getErrorMessage } from "@/utils/error";
import { getProductQuantityText, getProductSkuSpecEntries } from "@/utils/product";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
defineOptions({ name: "ProductStockSkuList" });
const router = useRouter();
const route = useRoute();
const navBarStore = useNavBarStore();
const userStore = useUserStore();
const keyword = ref("");
const product = ref<Product>();
const skuStockList = ref<ProductStock[]>([]);
const pageIndex = ref(0);
const total = ref(0);
const isLoading = ref(false);
const isRefreshing = ref(false);
const isNoMore = ref(false);
const productId = computed(() => {
const value = route.params.productId;
return Array.isArray(value) ? String(value[0] || "") : String(value || "");
});
const emptyText = computed(() => {
if (isLoading.value) {
return "正在加载 SKU";
}
if (keyword.value) {
return "未找到匹配 SKU";
}
return "该产品暂无启用库存管理的 SKU";
});
let keywordTimer: number | undefined;
let requestToken = 0;
let suppressKeywordFetch = false;
function getSkuSpecText(item: ProductStock): string {
const sku = item.sku;
if (!sku) {
return "未配置规格";
}
const entries = getProductSkuSpecEntries(sku, product.value?.specList || []);
return entries.length ? entries.map(entry => `${entry.specName}:${entry.valueName}`).join(" · ") : sku.specSummary || "无多规格";
}
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) && 0 <= depth && depth <= 20) {
return depth;
}
return Number(route.meta.depth ?? 0);
}
async function fetch(reset = false): Promise<void> {
if (!reset && (isLoading.value || isNoMore.value)) {
return;
}
if (reset) {
pageIndex.value = 0;
skuStockList.value = [];
total.value = 0;
isNoMore.value = false;
}
const token = ++requestToken;
isLoading.value = true;
try {
const pageSize = 15;
const result = await ProductAPI.stockList({
index: pageIndex.value,
size: pageSize,
productId: productId.value,
keyword: keyword.value || undefined
});
if (token !== requestToken) {
return;
}
const list = result.list || [];
skuStockList.value = reset ? list : skuStockList.value.concat(list);
total.value = result.total || 0;
pageIndex.value += 1;
isNoMore.value = list.length < pageSize || skuStockList.value.length === total.value || total.value < skuStockList.value.length;
} finally {
if (token === requestToken) {
isLoading.value = false;
}
}
}
async function loadProduct(): Promise<void> {
product.value = productId.value ? await ProductAPI.detail(productId.value) : undefined;
}
async function loadCurrent(): Promise<void> {
if (!productId.value) {
return;
}
try {
await Promise.all([loadProduct(), fetch(true)]);
} catch (error) {
Message.error(getErrorMessage(error, "SKU 列表加载失败"));
}
}
async function refresh(): Promise<void> {
try {
await Promise.all([loadProduct(), fetch(true)]);
} catch (error) {
Message.error(getErrorMessage(error, "SKU 列表加载失败"));
} finally {
isRefreshing.value = false;
}
}
async function loadMore(): Promise<void> {
try {
await fetch();
} catch (error) {
Message.error(getErrorMessage(error, "SKU 列表加载失败"));
}
}
async function toDetail(item: ProductStock): Promise<void> {
if (!item.skuId) {
return;
}
await router.push({
name: "ProductStockDetail",
params: { skuId: item.skuId },
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
onMounted(async () => {
navBarStore.clearRight();
if (!userStore.hasPermissions(permissionCodes.productStock.read)) {
return;
}
await loadCurrent();
});
watch(productId, async () => {
suppressKeywordFetch = true;
keyword.value = "";
requestToken += 1;
await loadCurrent();
suppressKeywordFetch = false;
});
watch(keyword, () => {
if (suppressKeywordFetch) {
return;
}
window.clearTimeout(keywordTimer);
keywordTimer = window.setTimeout(async () => {
try {
await fetch(true);
} catch (error) {
Message.error(getErrorMessage(error, "SKU 列表加载失败"));
}
}, 300);
});
onUnmounted(() => {
navBarStore.clearRight();
window.clearTimeout(keywordTimer);
requestToken += 1;
});
</script>
<style scoped lang="less">
.product-stock-sku-list {
padding: var(--app-nav-height) 0 1rem;
.product-context {
gap: .25rem;
display: flex;
padding: .75rem 1rem;
background: var(--td-bg-color-container);
flex-direction: column;
strong,
span {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
}
.search {
top: var(--app-nav-height);
z-index: 10;
padding: .75rem 1rem;
position: sticky;
background: var(--td-bg-color-page);
box-shadow: var(--td-shadow-1);
.keyword {
border: 1px solid var(--td-component-border);
padding: .5rem 1rem;
background: var(--td-bg-color-container);
border-radius: 1rem;
}
}
.list-wrap {
min-height: 70vh;
.list {
padding-top: .75rem;
.item {
padding: 10px;
.avatar {
width: 3.5rem;
height: 3.5rem;
}
.fallback {
color: var(--td-brand-color);
display: flex;
align-items: center;
justify-content: center;
background: var(--td-brand-color-1);
border-radius: .75rem;
font-size: 1.5rem;
font-weight: 700;
}
.title {
gap: .5rem;
min-width: 0;
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
strong {
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.sku-spec {
color: var(--td-text-color-secondary);
}
.stock {
gap: .5rem;
display: flex;
margin-top: .5rem;
flex-wrap: wrap;
strong {
display: inline-block;
margin-left: .25rem;
}
}
.reserved {
color: var(--td-warning-color);
}
.available {
color: var(--td-success-color);
}
}
}
}
}
</style>
@@ -1,7 +1,7 @@
<template>
<gao-chart-card
title="履约进度排行"
caption="购买数量的当前履约快照"
caption="基础单位购买数量的当前履约快照"
:option="chartOption"
:loading="loading"
:has-data="list.length > 0"
@@ -33,19 +33,19 @@ const chartOption = computed<EChartsOption>(() => {
name: "待履约",
type: "bar",
stack: "progress",
data: list.map(item => getNumber(item.reservedQuantity))
data: list.map(item => getNumber(item.reservedBaseQuantity))
},
{
name: "已履约",
type: "bar",
stack: "progress",
data: list.map(item => getNumber(item.fulfilledQuantity))
data: list.map(item => getNumber(item.fulfilledBaseQuantity))
},
{
name: "可履约",
type: "bar",
stack: "progress",
data: list.map(item => getNumber(item.availableQuantity))
data: list.map(item => getNumber(item.availableBaseQuantity))
}
]
};
@@ -1,7 +1,7 @@
<template>
<gao-chart-card
title="每日履约趋势"
caption="冲正数量允许为负值"
caption="基础单位,冲正数量允许为负值"
:date-text-list="dateTextList"
:option="buildOption"
:loading="loading"
@@ -41,16 +41,16 @@ function buildOption(visibleDateTextList: string[]): EChartsOption {
name: "直接履约",
type: "bar",
stack: "fulfillment",
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.directQuantity))
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.directBaseQuantity))
},
{
name: "套餐履约",
type: "bar",
stack: "fulfillment",
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.packageQuantity))
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.packageBaseQuantity))
},
{
name: "基础单位变化",
name: "履约基础单位",
type: "line",
smooth: true,
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.baseQuantity))
@@ -1,7 +1,7 @@
<template>
<gao-chart-card
title="产品销售排行"
caption="按销量取前 10"
caption="按基础单位销量取前 10"
:option="chartOption"
:loading="loading"
:has-data="list.length > 0"
@@ -33,13 +33,13 @@ const chartOption = computed<EChartsOption>(() => {
name: "直接销量",
type: "bar",
stack: "quantity",
data: list.map(item => getNumber(item.directQuantity))
data: list.map(item => getNumber(item.directBaseQuantity))
},
{
name: "套餐权益",
type: "bar",
stack: "quantity",
data: list.map(item => getNumber(item.packageQuantity))
data: list.map(item => getNumber(item.packageBaseQuantity))
}
]
};
@@ -1,7 +1,7 @@
<template>
<gao-chart-card
title="产品销售趋势"
caption="直接产品与套餐权益分开展示"
caption="基础单位,直接产品与套餐权益分开展示"
:date-text-list="dateTextList"
:option="buildOption"
:loading="loading"
@@ -41,13 +41,13 @@ function buildOption(visibleDateTextList: string[]): EChartsOption {
name: "直接销量",
type: "bar",
stack: "quantity",
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.directQuantity))
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.directBaseQuantity))
},
{
name: "套餐权益",
type: "bar",
stack: "quantity",
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.packageQuantity))
data: visibleDateTextList.map(dateText => getNumber(getDailyItem(props.list, dateText)?.packageBaseQuantity))
},
{
name: "订单数",
@@ -0,0 +1,415 @@
<template>
<t-swipe-cell class="sku-cell">
<t-cell role="button" tabindex="0" arrow @click="openEditor">
<template #title>
<div class="title">
<span class="code gray" v-text="sku.code" />
<strong class="clip-text" v-text="skuTitle" />
<t-tag v-if="sku.id" size="small" variant="light-outline" :content="sku.status === 'ACTIVE' ? '已建立' : '已停用'" />
</div>
</template>
<template #note>
<t-tag
size="small"
variant="light-outline"
:theme="sku.status === 'ACTIVE' ? 'success' : 'warning'"
:content="sku.status === 'ACTIVE' ? '启用' : '停用'"
/>
</template>
<template #description>
<div class="tags">
<t-tag
v-for="entry in skuSpecEntries"
:key="`${entry.specName}-${entry.valueName}`"
size="small"
:content="entry.valueName"
/>
<t-tag
v-if="sku.stockEnabled"
theme="warning"
size="small"
content="库存"
/>
<t-tag
v-for="unit in sku.unitList"
:key="unit.clientKey"
class="description-tag"
size="small"
:content="unit.name || '未命名单位'"
/>
</div>
</template>
</t-cell>
<template #right>
<t-button class="delete-action" theme="danger" @click.stop="requestRemove">
删除
</t-button>
</template>
</t-swipe-cell>
<bottom-popup
v-model="editorVisible"
title="配置 SKU 明细"
height="min(90vh, 52rem)"
:left-button-text="sku.id ? '关闭' : '取消'"
right-button-text="完成"
:z-index="skuEditorZIndex"
:overlay-props="{ zIndex: skuEditorZIndex - 1 }"
@left-button-click="closeEditor"
@right-button-click="closeEditor"
>
<div class="sku-popup">
<div class="sku-popup-header">
<div class="sku-heading">
<span class="sku-index" v-text="String(props.skuIndex + 1).padStart(2, '0')" />
<strong v-text="skuTitle" />
</div>
</div>
<div class="sku-spec-panel">
<div class="section-title">
<strong>销售规格</strong>
<span v-if="sku.specSummary" v-text="`摘要:${sku.specSummary}`" />
</div>
<div v-if="skuSpecEntries.length" class="sku-spec-list">
<div v-for="entry in skuSpecEntries" :key="`${entry.specName}-${entry.valueName}`" class="sku-spec-item">
<span class="spec-name" v-text="entry.specName" />
<strong v-text="entry.valueName" />
</div>
</div>
<div v-else class="sku-spec-empty" v-text="props.specList.length ? '请重新生成 SKU 明细以匹配规格项和规格值' : '无多规格产品,使用默认 SKU'" />
</div>
<t-form class="sku-form" label-align="left" label-width="5rem">
<t-form-item label="SKU 编码" required-mark help="门店内唯一;已有 SKU 修改失败时请保留原编码">
<t-input v-model.trim="sku.code" borderless maxlength="64" placeholder="如 TSHIRT-RED-M" />
</t-form-item>
<t-form-item label="明细名称" required-mark>
<t-input v-model.trim="sku.name" borderless maxlength="128" placeholder="如 黑色运动鞋;男;36" />
</t-form-item>
<t-form-item label="SKU 条码">
<t-input v-model.trim="sku.barcode" borderless maxlength="64" placeholder="选填" />
</t-form-item>
<div class="section-title setting-title">
<strong>库存设置</strong>
<span>每条 SKU 明细独立生效</span>
</div>
<t-form-item label="库存管理" content-align="right">
<t-switch v-model="sku.stockEnabled" size="small" :disabled="props.productType === 'SERVICE'" />
</t-form-item>
<t-form-item label="允许小数" content-align="right">
<t-switch v-model="sku.allowDecimalQuantity" size="small" />
</t-form-item>
<t-form-item v-if="sku.stockEnabled" label="最低库存" help="基础单位数量,最多三位小数">
<t-input v-model.trim="sku.minStockQuantityText" type="number" align="right" borderless placeholder="0" />
</t-form-item>
<t-form-item label="明细状态" content-align="right">
<t-switch :model-value="sku.status === 'ACTIVE'" size="small" @change="setSkuStatus" />
</t-form-item>
<t-form-item label="备注">
<t-input v-model.trim="sku.remark" borderless maxlength="255" placeholder="选填" />
</t-form-item>
</t-form>
<photo-scroller
:model-value="photoUrlList"
v-model:photo-items="sku.photoItemList"
title="SKU 图片(选填)"
:edit-mode="true"
:upload="uploadPhotoList"
/>
<div class="unit-section">
<div class="unit-heading">
<strong>销售单位</strong>
<span>采购、销售和库存操作共用</span>
</div>
<div class="unit-summary-list">
<div v-for="unit in sku.unitList" :key="unit.clientKey" class="unit-summary">
<strong v-text="unit.name || '未命名单位'" />
<span v-text="getUnitSummary(unit)" />
</div>
</div>
<t-button class="unit-button" variant="dashed" size="small" content="配置销售单位" @click="requestConfigureUnits" />
</div>
</div>
</bottom-popup>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import type { ProductType } from "@/types/Product";
import type { ProductSkuForm, ProductSpecForm, ProductSkuUnitForm } from "@/types/ProductEditor";
import PhotoScroller from "@/components/PhotoScroller.vue";
import { getProductSkuSpecEntries } from "@/utils/product";
import { uploadPhotoList } from "@/utils/photo";
defineOptions({ name: "ProductSkuEditor" });
const props = defineProps<{
productType: ProductType;
skuIndex: number;
specList: ProductSpecForm[];
}>();
const sku = defineModel<ProductSkuForm>("sku", { required: true });
const emit = defineEmits<{
configureUnits: [];
remove: [];
}>();
const editorVisible = ref(false);
const skuEditorZIndex = 12000;
const photoUrlList = computed(() => sku.value.photoItemList.map(item => item.url));
const skuSpecEntries = computed(() => getProductSkuSpecEntries(sku.value, props.specList));
const skuTitle = computed(() => props.specList.length ? `SKU 明细 ${props.skuIndex + 1}` : "默认 SKU");
function openEditor(): void {
editorVisible.value = true;
}
function closeEditor(): void {
editorVisible.value = false;
}
function requestRemove(): void {
editorVisible.value = false;
emit("remove");
}
function requestConfigureUnits(): void {
emit("configureUnits");
}
function setSkuStatus(value: boolean | string | number): void {
const active = value === true || value === "true" || value === 1 || value === "1";
sku.value.status = active ? "ACTIVE" : "INACTIVE";
}
function getUnitSummary(unit: ProductSkuUnitForm): string {
const quantityText = unit.isBase ? "基础单位" : `1 ${unit.name || "单位"} = ${unit.baseQuantityPerUnit || "?"} 基础单位`;
const priceText = unit.salePriceText ? `¥${unit.salePriceText}` : "未定价";
const saleText = unit.allowSale ? "可销售" : "停售";
const purchaseText = unit.allowPurchase ? "可采购" : "禁采购";
return `${quantityText} · ${priceText} · ${saleText} · ${purchaseText}`;
}
</script>
<style scoped lang="less">
.sku-cell {
.title {
}
.cell-title {
gap: .5rem;
min-width: 0;
display: flex;
align-items: center;
justify-content: space-between;
strong {
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.description-tags {
gap: .375rem;
display: flex;
flex-wrap: wrap;
}
.description-tag {
max-width: 100%;
}
.delete-action {
width: 4.5rem;
height: 100%;
border-radius: 0;
}
}
.sku-popup {
max-height: 100%;
padding: 1rem 0 calc(1rem + env(safe-area-inset-bottom, 0px));
overflow-y: auto;
.sku-popup-header {
gap: .5rem;
display: flex;
padding: 0 1rem .75rem;
align-items: center;
justify-content: space-between;
}
.sku-heading {
gap: .5rem;
min-width: 0;
display: flex;
align-items: center;
.sku-index {
width: 1.75rem;
height: 1.75rem;
color: var(--td-brand-color);
flex: none;
display: flex;
align-items: center;
justify-content: center;
background: var(--td-brand-color-1);
border-radius: .625rem;
font-size: .6875rem;
font-weight: 700;
}
}
.sku-spec-panel {
margin: 0 .75rem .75rem;
padding: .75rem;
background: var(--td-bg-color-secondarycontainer);
border-radius: .875rem;
}
.section-title {
gap: .5rem;
display: flex;
align-items: baseline;
justify-content: space-between;
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.sku-spec-list {
gap: .5rem;
display: grid;
margin-top: .625rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.sku-spec-item {
gap: .375rem;
min-width: 0;
display: flex;
padding: .5rem .625rem;
align-items: baseline;
background: var(--td-bg-color-container);
border-radius: .625rem;
.spec-name {
color: var(--td-text-color-secondary);
font-size: .75rem;
flex: none;
}
strong {
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.sku-spec-empty {
margin-top: .5rem;
color: var(--td-text-color-secondary);
font-size: .75rem;
}
.sku-form {
margin: 0 .75rem;
.setting-title {
margin-top: .5rem;
padding: .75rem 0 .25rem;
border-top: 1px solid var(--td-component-border);
}
}
:deep(.t-form-item) {
padding-right: 0;
padding-left: 0;
}
:deep(.photo-scroller) {
margin: .5rem .75rem 0;
}
.unit-section {
margin-top: .75rem;
border-top: 1px solid var(--td-component-border);
}
.unit-heading {
gap: .5rem;
display: flex;
padding: .75rem 1rem .5rem;
align-items: baseline;
justify-content: space-between;
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
text-align: right;
}
}
.unit-summary-list {
gap: .5rem;
display: flex;
padding: 0 1rem .5rem;
flex-direction: column;
}
.unit-summary {
gap: .5rem;
min-width: 0;
display: flex;
padding: .625rem .75rem;
align-items: center;
background: var(--td-bg-color-secondarycontainer);
border-radius: .75rem;
justify-content: space-between;
strong {
max-width: 5rem;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
span {
min-width: 0;
color: var(--td-text-color-secondary);
font-size: .75rem;
text-align: right;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.unit-button {
margin: 0 1rem .75rem;
}
}
:global(html.theme-dark) {
.sku-popup {
.sku-spec-panel,
.unit-summary {
background: rgba(148, 163, 184, .12);
}
}
}
</style>
@@ -0,0 +1,198 @@
<template>
<bottom-popup
v-model="visible"
title="统一配置 SKU 单位"
height="min(88vh, 48rem)"
left-button-text="关闭"
right-button-text="应用到全部"
:z-index="batchEditorZIndex"
:overlay-props="{ zIndex: batchEditorZIndex - 1 }"
@left-button-click="close"
@right-button-click="applyUnits"
>
<div class="batch-editor">
<div class="editor-context">
<strong>批量配置销售单位</strong>
<span v-text="`以下单位将应用到全部 ${props.skuCount} 个 SKU 明细`" />
</div>
<div class="unit-list">
<div v-for="(unit, unitIndex) in unitList" :key="unit.clientKey" class="unit-card">
<div class="unit-card-header">
<strong v-text="`单位 ${unitIndex + 1}`" />
<t-button v-if="1 < unitList.length" theme="danger" variant="text" size="extra-small" content="删除" @click="removeUnit(unitIndex)" />
</div>
<t-form class="unit-form" label-align="left" label-width="6rem">
<t-form-item label="单位名称" required-mark>
<t-input v-model.trim="unit.name" borderless maxlength="32" placeholder="如 件、盒、箱" />
</t-form-item>
<t-form-item label="基础单位" content-align="right">
<t-switch v-model="unit.isBase" size="small" :disabled="unitList.length === 1" @change="setBaseUnit(unitIndex)" />
</t-form-item>
<t-form-item label="换算数量" help="1 个当前单位对应的基础单位数量" required-mark>
<t-input v-model.trim="unit.baseQuantityPerUnit" type="number" align="right" borderless :disabled="unit.isBase" placeholder="1" />
</t-form-item>
<t-form-item label="售价(元)">
<t-input v-model.trim="unit.salePriceText" type="number" align="right" borderless placeholder="选填" />
</t-form-item>
<t-form-item label="允许采购" content-align="right">
<t-switch v-model="unit.allowPurchase" size="small" :disabled="props.productType === 'SERVICE'" />
</t-form-item>
<t-form-item label="允许销售" content-align="right">
<t-switch v-model="unit.allowSale" size="small" />
</t-form-item>
</t-form>
</div>
<t-button class="add-button" variant="dashed" size="small" content="添加销售单位" @click="addUnit" />
</div>
</div>
</bottom-popup>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import type { ProductType } from "@/types/Product";
import type { ProductSkuUnitForm } from "@/types/ProductEditor";
import { Message } from "@/utils/message";
defineOptions({ name: "ProductSkuUnitBatchEditor" });
const props = defineProps<{
modelValue: boolean;
productType: ProductType;
skuCount: number;
}>();
const unitList = defineModel<ProductSkuUnitForm[]>("unitList", { required: true });
const emit = defineEmits<{
"update:modelValue": [value: boolean];
apply: [];
close: [];
}>();
const visible = computed({
get: () => props.modelValue,
set: value => handleVisibleChange(value)
});
const batchEditorZIndex = 12000;
function handleVisibleChange(value: boolean): void {
emit("update:modelValue", value);
if (!value) {
emit("close");
}
}
function close(): void {
visible.value = false;
}
function applyUnits(): void {
if (!unitList.value.length) {
Message.warning("至少需要配置一个销售单位");
return;
}
emit("apply");
close();
}
function addUnit(): void {
unitList.value.push({
clientKey: window.crypto.randomUUID(),
name: unitList.value[0]?.name || "件",
baseQuantityPerUnit: "",
salePriceText: "",
isBase: false,
allowPurchase: props.productType !== "SERVICE",
allowSale: true,
sort: unitList.value.length
});
}
function removeUnit(index: number): void {
if (unitList.value.length < 2) {
Message.warning("每个 SKU 至少需要一个单位");
return;
}
const wasBase = unitList.value[index]?.isBase;
unitList.value.splice(index, 1);
if (wasBase) {
setBaseUnit(0);
}
}
function setBaseUnit(index: number): void {
unitList.value.forEach((unit, unitIndex) => { unit.isBase = unitIndex === index; });
const unit = unitList.value[index];
if (unit) {
unit.baseQuantityPerUnit = "1";
}
}
</script>
<style scoped lang="less">
.batch-editor {
max-height: 100%;
overflow-y: auto;
padding: 1rem 0 calc(1rem + env(safe-area-inset-bottom, 0px));
.editor-context {
gap: .25rem;
display: flex;
margin: 0 1rem .75rem;
padding: .75rem;
background: var(--td-bg-color-secondarycontainer);
border-radius: .875rem;
flex-direction: column;
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
}
.unit-list {
gap: .75rem;
display: flex;
padding: 0 1rem 1rem;
flex-direction: column;
}
.unit-card {
border: 1px solid var(--td-component-border);
padding: .5rem 0;
border-radius: .75rem;
}
.unit-card-header {
gap: .5rem;
display: flex;
padding: 0 .75rem .5rem;
align-items: center;
justify-content: space-between;
}
.unit-form {
margin: 0 .75rem;
:deep(.t-form-item) {
padding-right: 0;
padding-left: 0;
}
}
.add-button {
align-self: flex-start;
}
}
:global(html.theme-dark) .batch-editor {
.editor-context {
background: rgba(148, 163, 184, .12);
}
.unit-card {
border-color: rgba(148, 163, 184, .3);
}
}
</style>
@@ -0,0 +1,252 @@
<template>
<bottom-popup
v-model="visible"
title="配置 SKU 单位"
height="min(88vh, 48rem)"
left-button-text="关闭"
right-button-text="完成"
:z-index="unitEditorZIndex"
:overlay-props="{ zIndex: unitEditorZIndex - 1 }"
@left-button-click="close"
@right-button-click="close"
>
<div v-if="sku" class="unit-editor">
<div class="editor-context">
<span class="context-label">当前 SKU 明细</span>
<strong class="context-title" v-text="sku.name || sku.specSummary || '默认 SKU'" />
<div v-if="skuSpecEntries.length" class="context-spec-list">
<div v-for="entry in skuSpecEntries" :key="`${entry.specName}-${entry.valueName}`" class="context-spec">
<span v-text="entry.specName" />
<strong v-text="entry.valueName" />
</div>
</div>
<span v-else class="context-empty">无多规格</span>
<div class="context-count" v-text="`${sku.unitList.length} 个单位`" />
</div>
<div class="unit-list">
<div v-for="(unit, unitIndex) in sku.unitList" :key="unit.clientKey" class="unit-card">
<div class="unit-card-header">
<strong v-text="`单位 ${unitIndex + 1}`" />
<t-button v-if="1 < sku.unitList.length" theme="danger" variant="text" size="extra-small" content="删除" @click="removeUnit(unitIndex)" />
</div>
<t-form class="unit-form" label-align="left" label-width="6rem">
<t-form-item label="单位名称" required-mark>
<t-input v-model.trim="unit.name" borderless maxlength="32" placeholder="如 件、盒、箱" />
</t-form-item>
<t-form-item label="基础单位" content-align="right">
<t-switch v-model="unit.isBase" size="small" :disabled="sku.unitList.length === 1" @change="setBaseUnit(unitIndex)" />
</t-form-item>
<t-form-item label="换算数量" help="1 个当前单位对应的基础单位数量" required-mark>
<t-input v-model.trim="unit.baseQuantityPerUnit" type="number" align="right" borderless :disabled="unit.isBase" placeholder="1" />
</t-form-item>
<t-form-item label="售价(元)">
<t-input v-model.trim="unit.salePriceText" type="number" align="right" borderless placeholder="选填" />
</t-form-item>
<t-form-item label="允许采购" content-align="right">
<t-switch v-model="unit.allowPurchase" size="small" :disabled="props.productType === 'SERVICE'" />
</t-form-item>
<t-form-item label="允许销售" content-align="right">
<t-switch v-model="unit.allowSale" size="small" />
</t-form-item>
</t-form>
</div>
<t-button class="add-button" variant="dashed" size="small" content="添加 SKU 单位" @click="addUnit" />
</div>
</div>
</bottom-popup>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import type { ProductSkuUnit, ProductType } from "@/types/Product";
import type { ProductSkuForm, ProductSkuUnitForm, ProductSpecForm } from "@/types/ProductEditor";
import { Message } from "@/utils/message";
import { formatProductAmount, getProductSkuSpecEntries } from "@/utils/product";
defineOptions({ name: "ProductSkuUnitEditor" });
const props = defineProps<{
modelValue: boolean;
productType: ProductType;
specList: ProductSpecForm[];
}>();
const sku = defineModel<ProductSkuForm | undefined>("sku");
const emit = defineEmits<{
"update:modelValue": [value: boolean];
close: [];
}>();
const visible = computed({
get: () => props.modelValue,
set: value => handleVisibleChange(value)
});
const unitEditorZIndex = 12100;
const skuSpecEntries = computed(() => sku.value ? getProductSkuSpecEntries(sku.value, props.specList) : []);
function handleVisibleChange(value: boolean): void {
emit("update:modelValue", value);
if (!value) {
emit("close");
}
}
function close(): void {
visible.value = false;
}
function createUnit(unit?: Partial<ProductSkuUnit>, defaultName = "件"): ProductSkuUnitForm {
return {
...unit,
id: unit?.id,
clientKey: window.crypto.randomUUID(),
name: unit?.name || defaultName,
baseQuantityPerUnit: unit?.baseQuantityPerUnit ?? "1",
salePriceText: unit?.salePrice === null || unit?.salePrice === undefined ? "" : formatProductAmount(unit.salePrice),
isBase: unit?.isBase ?? true,
allowPurchase: unit?.allowPurchase ?? props.productType !== "SERVICE",
allowSale: unit?.allowSale ?? true,
sort: unit?.sort ?? 0
};
}
function addUnit(): void {
if (!sku.value) {
return;
}
sku.value.unitList.push(createUnit({ isBase: false, baseQuantityPerUnit: "" }, sku.value.unitList[0]?.name || "件"));
}
function removeUnit(index: number): void {
if (!sku.value) {
return;
}
if (sku.value.unitList.length < 2) {
Message.warning("每个 SKU 至少需要一个单位");
return;
}
const wasBase = sku.value.unitList[index]?.isBase;
sku.value.unitList.splice(index, 1);
if (wasBase && sku.value.unitList[0]) {
sku.value.unitList[0].isBase = true;
sku.value.unitList[0].baseQuantityPerUnit = "1";
}
}
function setBaseUnit(index: number): void {
if (!sku.value) {
return;
}
sku.value.unitList.forEach((unit, unitIndex) => { unit.isBase = unitIndex === index; });
const unit = sku.value.unitList[index];
if (unit) {
unit.baseQuantityPerUnit = "1";
}
}
</script>
<style scoped lang="less">
.unit-editor {
max-height: 100%;
overflow-y: auto;
padding: 1rem 0 calc(1rem + env(safe-area-inset-bottom, 0px));
.editor-context {
margin: 0 1rem .75rem;
padding: .75rem;
background: var(--td-bg-color-secondarycontainer);
border-radius: .875rem;
.context-label,
.context-empty {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
.context-label {
display: block;
margin-bottom: .25rem;
}
.context-title {
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.context-spec-list {
gap: .375rem;
display: flex;
margin-top: .625rem;
flex-wrap: wrap;
}
.context-spec {
gap: .25rem;
display: flex;
padding: .25rem .5rem;
background: var(--td-bg-color-container);
border-radius: .5rem;
font-size: .75rem;
span {
color: var(--td-text-color-secondary);
}
}
.context-count {
margin-top: .625rem;
color: var(--td-text-color-secondary);
font-size: .75rem;
}
}
.unit-list {
gap: .75rem;
display: flex;
padding: 0 1rem 1rem;
flex-direction: column;
}
.unit-card {
border: 1px solid var(--td-component-border);
padding: .5rem 0;
border-radius: .75rem;
}
.unit-card-header {
gap: .5rem;
display: flex;
padding: 0 .75rem .5rem;
align-items: center;
justify-content: space-between;
}
.unit-form {
margin: 0 .75rem;
}
:deep(.t-form-item) {
padding-right: 0;
padding-left: 0;
}
.add-button {
align-self: flex-start;
}
}
:global(html.theme-dark) .unit-editor {
.editor-context,
.context-spec {
background: rgba(148, 163, 184, .12);
}
.unit-card {
border-color: rgba(148, 163, 184, .3);
}
}
</style>
@@ -22,12 +22,18 @@
<td>
<div class="product-name" v-text="item.productName || '未命名产品'" />
<div class="product-type" v-text="getProductTypeText(item.productType)" />
<div v-if="hasLowStockSku(item)" class="sku-list">
<div v-for="sku in getLowStockSkuList(item)" :key="`${sku.skuId}-${sku.skuCode}`" class="sku-item">
<span v-text="getSkuName(sku)" />
<span v-text="`可用 ${formatQuantity(sku.availableQuantity)}`" />
</div>
</div>
</td>
<td class="number" v-text="formatQuantity(item.availableQuantity)" />
<td class="number" v-text="formatQuantity(item.reservedQuantity)" />
<td class="number" v-text="formatQuantity(item.minStockQuantity)" />
<td>
<t-tag v-if="item.lowStock === 1" theme="danger" variant="light" content="低库存" />
<t-tag v-if="hasLowStockSku(item)" theme="danger" variant="light" :content="`低库存 ${formatQuantity(item.lowStockSkuCount)} 个规格`" />
<t-tag v-else theme="success" variant="light" content="正常" />
</td>
</tr>
@@ -38,7 +44,7 @@
</template>
<script setup lang="ts">
import type { GaoProductStockHealthView } from "@/types/GaoChart";
import type { GaoProductSkuStockHealthView, GaoProductStockHealthView } from "@/types/GaoChart";
import { formatQuantity, getNumber } from "@/pages/product/component/chartUtils";
defineOptions({
@@ -47,14 +53,27 @@ defineOptions({
const props = defineProps<{
list: GaoProductStockHealthView[];
skuHealthList: GaoProductSkuStockHealthView[];
loading: boolean;
}>();
const sortedList = computed(() => [...props.list].sort((left, right) => {
const lowStockDiff = getNumber(right.lowStock) - getNumber(left.lowStock);
const lowStockDiff = getNumber(right.lowStockSkuCount) - getNumber(left.lowStockSkuCount);
return lowStockDiff || getNumber(left.availableQuantity) - getNumber(right.availableQuantity);
}));
function hasLowStockSku(item: GaoProductStockHealthView): boolean {
return 0 < getNumber(item.lowStockSkuCount);
}
function getLowStockSkuList(item: GaoProductStockHealthView): GaoProductSkuStockHealthView[] {
return props.skuHealthList.filter(sku => sku.productId === item.productId);
}
function getSkuName(item: GaoProductSkuStockHealthView): string {
return [item.skuName || "未命名规格", item.specSummary].filter(Boolean).join(" · ");
}
function getProductTypeText(value?: string): string {
return ({ SERVICE: "服务", GOODS: "商品", CONSUMABLE: "耗材" } as Record<string, string>)[value || ""] || "未分类";
}
@@ -127,6 +146,21 @@ function getProductTypeText(value?: string): string {
font-size: .6875rem;
}
.sku-list {
gap: .25rem;
margin-top: .375rem;
display: flex;
flex-direction: column;
}
.sku-item {
gap: .5rem;
color: #b42318;
display: flex;
font-size: .6875rem;
justify-content: space-between;
}
.table-state {
padding: 1.5rem 0;
display: flex;
@@ -148,6 +182,10 @@ function getProductTypeText(value?: string): string {
color: #cbd5e1;
border-top-color: rgba(148, 163, 184, .2);
}
.sku-item {
color: #fda29b;
}
}
}
</style>
+42 -52
View File
@@ -46,35 +46,24 @@
<strong>购买产品</strong>
<span v-text="`${items.length} 项`" />
</div>
<div class="tips">同一产品单位不能重复,数量最多三位小数</div>
<div class="tips">同一 SKU 单位不能重复,数量最多三位小数</div>
<div class="items">
<div v-for="(item, index) in items" :key="item.clientKey" class="item">
<div class="header">
<span class="no" v-text="String(index + 1).padStart(2, '0')" />
<strong v-text="item.productName || '未选择产品'" />
<strong v-text="getItemTitle(item)" />
<t-button theme="danger" variant="text" size="extra-small" @click="removeItem(index)">删除</t-button>
</div>
<product-selector
:model-value="item.productId ? {productId: item.productId, productUnitId: item.productUnitId || ''} : undefined"
:model-value="item.skuId ? { skuId: item.skuId, skuUnitId: item.skuUnitId || '' } : undefined"
:selected-product="getProduct(item)"
label="产品"
placeholder="请选择产品"
selection-mode="product"
required-mark
@update:model-value="applyProduct(index, $event)"
/>
<t-form-item v-if="item.productId" label="产品单位" required-mark>
<div v-if="getSaleableUnits(item).length" class="unit-list">
<t-button
v-for="unit in getSaleableUnits(item)"
:key="unit.id"
:theme="item.productUnitId === unit.id ? 'primary' : 'default'"
:variant="item.productUnitId === unit.id ? 'base' : 'outline'"
size="extra-small"
:content="unit.name"
@click="selectProductUnit(index, unit)"
/>
</div>
<span v-else class="unit-empty" v-text="'暂无可售单位'" />
<t-form-item v-if="item.skuId" label="SKU 单位" content-align="right">
<span v-text="getUnit(item)?.name || '未选择单位'" />
</t-form-item>
<t-form-item :label="canPriceOverride ? '成交单价' : '单价'">
<t-input
@@ -93,7 +82,7 @@
:max="maxQuantity"
:min="getQuantityStep(item)"
:step="getQuantityStep(item)"
:integer="!getProduct(item)?.allowDecimalQuantity"
:integer="!getSku(item)?.allowDecimalQuantity"
theme="outline"
/>
</t-form-item>
@@ -181,7 +170,7 @@ import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
import CustomerSelector from "@/components/CustomerSelector.vue";
import PhotoScroller from "@/components/PhotoScroller.vue";
import type { Customer } from "@/types/Customer";
import type { Product, ProductUnit } from "@/types/Product";
import type { Product, ProductSku, ProductSkuUnit } from "@/types/Product";
import type { PhotoItem } from "@/types/Photo";
import type { DirectProductOrderItemRequest } from "@/types/SalesOrder";
import { createPackageRequestNo, normalizePackageQuantity, parsePackageAmount } from "@/utils/package";
@@ -213,6 +202,7 @@ const photoItems = ref<PhotoItem[]>([]);
const photoUrlList = computed(() => photoItems.value.map(item => item.url));
const maxQuantity = Number.MAX_SAFE_INTEGER;
const productCache = new Map<string, Product>();
const skuCache = new Map<string, ProductSku>();
const requestNo = ref("");
const customerDisplayText = computed(() => customer.value?.name || customer.value?.code || "选择客户");
const customerCode = ref("");
@@ -221,12 +211,27 @@ const scannerVisible = ref(false);
const scanStatus = ref("点击扫码开始识别。");
let latestDecodedText = "";
function getProduct(item: FormItem): Product | undefined {
return productCache.get(item.productId || "");
function getSku(item: FormItem): ProductSku | undefined {
return skuCache.get(item.skuId || "");
}
function getQuantityStep(item: FormItem): number {
return getProductQuantityStep(getProduct(item));
return getProductQuantityStep(getSku(item));
}
function getProduct(item: FormItem): Product | undefined {
const sku = getSku(item);
return productCache.get(sku?.productId || "");
}
function getUnit(item: FormItem): ProductSkuUnit | undefined {
return getSku(item)?.unitList?.find(unit => unit.id === item.skuUnitId);
}
function getItemTitle(item: FormItem): string {
const product = getProduct(item);
const sku = getSku(item);
return sku?.specSummary || sku?.name || product?.name || item.productName || "未选择产品";
}
const totalAmount = computed(() => {
@@ -264,45 +269,30 @@ function removeItem(index: number): void {
}
}
async function applyProduct(index: number, value?: { productId: string; productUnitId: string }): Promise<void> {
async function applyProduct(index: number, value?: { skuId: string; skuUnitId: string }): Promise<void> {
if (!value) return;
const product = productCache.get(value.productId) || await ProductAPI.detail(value.productId);
productCache.set(value.productId, product);
const sku = skuCache.get(value.skuId) || await ProductAPI.skuDetail(value.skuId);
skuCache.set(value.skuId, sku);
const product = productCache.get(sku.productId || "") || await ProductAPI.detail(sku.productId || "");
productCache.set(sku.productId || "", product);
const item = items.value[index];
const saleableUnits = (product.unitList || []).filter(unit => unit.allowSale !== false && unit.id);
const productUnitId = saleableUnits.length < 2 ? saleableUnits[0]?.id || "" : value.productUnitId;
const selectionChanged = item.productId !== value.productId || item.productUnitId !== productUnitId;
item.productId = value.productId;
item.productUnitId = productUnitId;
const selectionChanged = item.skuId !== value.skuId || item.skuUnitId !== value.skuUnitId;
item.skuId = value.skuId;
item.skuUnitId = value.skuUnitId;
item.productName = product.name;
if (selectionChanged) {
item.unitPriceText = "";
}
}
function getSaleableUnits(item: FormItem): ProductUnit[] {
return (productCache.get(item.productId || "")?.unitList || []).filter(unit => unit.allowSale !== false && unit.id);
}
function selectProductUnit(index: number, unit: ProductUnit): void {
const item = items.value[index];
const product = productCache.get(item.productId || "");
if (!product?.id || !unit.id) {
return;
}
if (item.productUnitId !== unit.id) {
item.unitPriceText = "";
}
item.productUnitId = unit.id;
item.productName = product.name;
}
function getItemUnitPrice(item: FormItem): number | undefined {
if (canPriceOverride.value && item.unitPriceText.trim()) {
return parsePackageAmount(item.unitPriceText);
}
const salePrice = productCache.get(item.productId || "")?.unitList?.find(unit => unit.id === item.productUnitId)?.salePrice;
const salePrice = getUnit(item)?.salePrice;
return salePrice === null ? undefined : salePrice;
}
function getItemUnitPricePlaceholder(item: FormItem): string {
const salePrice = productCache.get(item.productId || "")?.unitList?.find(unit => unit.id === item.productUnitId)?.salePrice;
const salePrice = getUnit(item)?.salePrice;
return salePrice === undefined || salePrice === null ? "产品价" : `产品价:${formatProductAmount(salePrice)}`;
}
function calculateItemAmount(item: FormItem): number | undefined {
@@ -388,9 +378,9 @@ function validate(): boolean {
const keys = new Set<string>();
for (const item of items.value) {
const quantity = normalizePackageQuantity(item.quantity ?? "");
const key = `${item.productId}\u0000${item.productUnitId}`;
if (!item.productId || !item.productUnitId || !quantity || quantity === "0") { Message.warning("产品单位和正数量不能为空"); return false; }
if (getProduct(item) && !getProduct(item)!.allowDecimalQuantity && quantity.includes(".")) { Message.warning("该产品不允许小数数量"); return false; }
const key = `${item.skuId}\u0000${item.skuUnitId}`;
if (!item.skuId || !item.skuUnitId || !quantity || quantity === "0") { Message.warning("SKU 单位和正数量不能为空"); return false; }
if (getSku(item) && !getSku(item)!.allowDecimalQuantity && quantity.includes(".")) { Message.warning("该 SKU 不允许小数数量"); return false; }
if (keys.has(key)) { Message.warning("产品单位不能重复"); return false; }
keys.add(key);
if (canPriceOverride.value && item.unitPriceText && parsePackageAmount(item.unitPriceText) === undefined) { Message.warning("成交单价必须是合法金额"); return false; }
@@ -403,8 +393,8 @@ async function save(): Promise<void> {
isSaving.value = true;
try {
const itemList = items.value.map((item, index) => ({
productId: item.productId!,
productUnitId: item.productUnitId!,
skuId: item.skuId!,
skuUnitId: item.skuUnitId!,
quantity: normalizePackageQuantity(item.quantity ?? "")!,
unitPrice: canPriceOverride.value && item.unitPriceText ? parsePackageAmount(item.unitPriceText) : undefined,
sort: index,
+13 -1
View File
@@ -96,7 +96,7 @@
</div>
<div class="main">
<div class="title">
<span class="name text-bold" v-text="item.productNameSnapshot" />
<span class="name text-bold" v-text="getItemTitle(item)" />
<t-tag
:content="getItemFulfillmentStatus(item).text"
:theme="getItemFulfillmentStatus(item).theme"
@@ -110,6 +110,13 @@
v-text="`¥${formatPackageAmount(item.lineAmount)}`"
/>
<t-tag v-else size="small" content="套餐权益" />
<t-tag
v-if="item.skuCodeSnapshot || item.skuNameSnapshot || item.specSummarySnapshot"
size="small"
theme="primary"
variant="light"
:content="item.skuCodeSnapshot || item.skuNameSnapshot || item.specSummarySnapshot"
/>
<t-tag size="small" theme="primary" variant="light" :content="item.unitSnapshot" />
</div>
</div>
@@ -250,6 +257,11 @@ const canCancel = computed(() => !!order.value && order.value.status === "ACTIVE
const canFulfillByPayment = computed(() => order.value?.paymentStatus === "PAID" || (order.value?.paymentStatus === "PARTIALLY_PAID" && canOperateStock.value));
const photoURLList = computed(() => photoItems.value.map(item => item.url));
function getItemTitle(item: GaoSalesOrderItem): string {
const skuText = item.skuNameSnapshot || item.specSummarySnapshot;
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""}`;
}
function toPhotoItems(attachmentList?: readonly Partial<Attachment>[]): PhotoItem[] {
return (attachmentList || [])
.filter(item => !!item.id)
@@ -43,8 +43,8 @@
<div class="items">
<t-tag
v-for="(item, index) in itemList"
:key="item.id || `${item.productId}-${index}`"
:content="item.productNameSnapshot || '未命名产品'"
:key="item.id || `${item.skuId}-${item.skuUnitId}-${index}`"
:content="getProductText(item)"
theme="primary"
variant="light"
/>
@@ -141,6 +141,11 @@ function sumProductQuantity(field: "quantity" | "fulfilledQuantity"): string {
}
return getPackageQuantityText(total.toFixed(3));
}
function getProductText(item: NonNullable<SalesOrder["itemList"]>[number]): string {
const skuText = item.skuNameSnapshot || item.specSummarySnapshot;
return `${item.productNameSnapshot || "未命名产品"}${skuText ? ` · ${skuText}` : ""}${item.unitSnapshot ? ` / ${item.unitSnapshot}` : ""}`;
}
</script>
<style scoped lang="less">
+17
View File
@@ -112,6 +112,23 @@ const menuGroupList = computed<MenuGroup[]>(() => [
visible: userStore.hasPermissions(permissionCodes.packageConfig.read)
}
]
},
{
title: "经营分析",
items: [
{
icon: "chart",
path: "/management/product-data-charts",
title: "产品经营图表",
visible: userStore.hasPermissions(permissionCodes.stat.read)
},
{
icon: "chart",
path: "/management/order-data-charts",
title: "客户经营图表",
visible: userStore.hasPermissions(permissionCodes.stat.read)
}
]
}
]);