add ProductStockCalendar

This commit is contained in:
Timi
2026-11-06 17:39:13 +08:00
parent 251985d8da
commit a32aaef8ae
5 changed files with 386 additions and 215 deletions
+40 -208
View File
@@ -1,18 +1,7 @@
<template>
<section class="register-record-calendar">
<div class="calendar-head">
<t-button class="month-btn" shape="square" variant="text" @click="shiftMonth(-1)">
<template #icon>
<t-icon name="chevron-left" />
</template>
</t-button>
<h2 v-text="monthTitle" />
<div class="head-actions">
<t-button class="month-btn" shape="square" variant="text" @click="shiftMonth(1)">
<template #icon>
<t-icon name="chevron-right" />
</template>
</t-button>
<month-calendar v-model="monthProxy" :days="calendarDayList" @day-click="openDayRecords">
<template #actions>
<t-button
v-if="showEventFilter"
class="filter-btn"
@@ -22,32 +11,13 @@
@click="eventFilterVisible = true"
content="登记事件"
>
<template #icon>
<t-icon name="filter" />
</template>
<template #icon><t-icon name="filter" /></template>
</t-button>
</div>
</div>
<div class="week-line">
<span v-for="item in weekNameList" :key="item" v-text="item" />
</div>
<div class="calendar-grid">
<button
v-for="item in calendarDayList"
:key="item.key"
class="day-cell"
:class="{muted: !item.inMonth, today: item.isToday, marked: 0 < item.records.length, 'rest-day': item.isRestDay}"
type="button"
:disabled="!item.records.length"
@click="openDayRecords(item)"
>
<span class="date">
<span v-text="item.day" />
<span v-if="item.isRestDay" class="rest">休</span>
</span>
<span v-if="item.records.length" class="count" v-text="`${item.records.length} 条`" />
</button>
</div>
</template>
<template #day="{ day }">
<span v-if="getDayRecords(day.dateText).length" class="count" v-text="`${getDayRecords(day.dateText).length} 条`" />
</template>
</month-calendar>
<center-tips v-if="loading">正在加载登记日历</center-tips>
<center-tips v-else-if="!currentMonthFilteredRecords.length" :content="emptyText" />
<t-cell title="登记事件记录列表" arrow @click="openRecordList">
@@ -103,19 +73,15 @@
<script setup lang="ts">
import StoreAPI from "@/api/StoreAPI";
import EventSelector from "@/components/EventSelector.vue";
import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue";
import { buildMonthCalendarDays, type MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
import type {EventItem} from "@/types/EventItem";
import type {EventRecord} from "@/types/EventRecord";
import type {StoreBusinessDay} from "@/types/Store";
import {getCurrentStoreId} from "@/utils/store";
import {Time} from "timi-web";
interface CalendarDay {
key: string;
day: string;
dateText: string;
inMonth: boolean;
isToday: boolean;
isRestDay: boolean;
interface CalendarDay extends MonthCalendarDay {
records: EventRecord[];
}
@@ -150,7 +116,10 @@ const emit = defineEmits<{
const route = useRoute();
const router = useRouter();
const weekNameList = ["日", "一", "二", "三", "四", "五", "六"];
const monthProxy = computed({
get: () => props.modelValue,
set: value => emit("update:modelValue", value)
});
const dayRecordVisible = ref(false);
const eventFilterVisible = ref(false);
const selectedDayTitle = ref("");
@@ -186,26 +155,16 @@ const filteredRecords = computed(() => {
return props.records.filter(item => item.eventId && selectedEventIdSet.value.has(item.eventId));
});
const currentMonthFilteredRecords = computed(() => filteredRecords.value.filter(item => isInCurrentMonth(item.registeredAt)));
const monthTitle = computed(() => `${props.modelValue.getFullYear()} 年 ${props.modelValue.getMonth() + 1} 月`);
const calendarDayList = computed<CalendarDay[]>(() => {
const beginDate = getCalendarBeginDate(props.modelValue);
const todayText = Time.toDate(new Date());
const list: CalendarDay[] = [];
for (let index = 0; index < 42; index += 1) {
const date = addDays(beginDate, index);
const dateText = Time.toDate(date);
list.push({
key: dateText,
day: String(date.getDate()),
dateText,
inMonth: date.getMonth() === props.modelValue.getMonth(),
isToday: dateText === todayText,
isRestDay: restDaySet.value.has(toDateValue(date)),
records: filteredRecords.value.filter(item => getRecordDateText(item) === dateText)
});
}
return list;
});
const calendarDayList = computed<CalendarDay[]>(() => buildMonthCalendarDays(props.modelValue).map(day => {
const records = getDayRecords(day.dateText);
return {
...day,
isRestDay: restDaySet.value.has(Number(day.dateText.replaceAll("-", ""))),
records,
marked: 0 < records.length,
disabled: !records.length
};
}));
watch([() => props.modelValue, resolvedStoreId], async () => {
await loadBusinessDays();
@@ -236,17 +195,18 @@ async function loadBusinessDays(): Promise<void> {
}
}
function shiftMonth(offset: number): void {
emit("update:modelValue", addMonths(props.modelValue, offset));
function getDayRecords(dateText: string): EventRecord[] {
return filteredRecords.value.filter(item => getRecordDateText(item) === dateText);
}
function openDayRecords(day: CalendarDay): void {
if (!day.records.length) {
function openDayRecords(day: MonthCalendarDay): void {
const records = getDayRecords(day.dateText);
if (!records.length) {
return;
}
selectedDayTitle.value = `${day.dateText} 登记事件记录`;
selectedDayRecords.value = [...day.records].sort((left, right) => (right.registeredAt || 0) - (left.registeredAt || 0));
selectedDayRecords.value = [...records].sort((left, right) => (right.registeredAt || 0) - (left.registeredAt || 0));
dayRecordVisible.value = true;
}
@@ -324,10 +284,6 @@ function addDays(date: Date, days: number): Date {
return value;
}
function addMonths(date: Date, months: number): Date {
return new Date(date.getFullYear(), date.getMonth() + months, 1, 0, 0, 0, 0);
}
function toDateValue(date: Date): number {
return Number(Time.toDate(date).replaceAll("-", ""));
}
@@ -343,106 +299,14 @@ function toDateValue(date: Date): number {
border-radius: .75rem;
flex-direction: column;
.calendar-head {
display: flex;
padding: .5rem 1rem;
align-items: center;
justify-content: space-between;
h2 {
margin: 0;
color: #0f172a;
font-size: 1rem;
font-weight: 700;
}
.month-btn {
width: 2.5rem;
height: 2.5rem;
}
.head-actions {
gap: .5rem;
display: flex;
align-items: center;
}
}
.week-line,
.calendar-grid {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
}
.week-line {
color: #52607a;
padding: 0 1rem;
font-size: .75rem;
text-align: center;
}
.calendar-grid {
gap: .375rem;
padding: 1rem 1rem .5rem 1rem;
.day-cell {
padding: .25rem;
height: 2.5rem;
display: flex;
min-width: 0;
color: #0f172a;
border: 1px solid var(--td-component-border);
background: #fff;
text-align: left;
align-items: flex-start;
border-radius: .25rem;
flex-direction: column;
.date {
display: flex;
font-size: .875rem;
align-items: center;
font-weight: 700;
}
.rest {
color: orange;
margin-left: .125rem;
font-size: .625rem;
font-weight: 700;
}
.count {
width: 100%;
color: var(--td-brand-color);
overflow: hidden;
font-size: .625rem;
font-weight: 700;
white-space: nowrap;
text-overflow: ellipsis;
}
&.muted {
color: #94a3b8;
background: #f8fafc;
}
&.today {
color: var(--td-brand-color);
}
&.marked {
background: var(--td-brand-color-1);
}
&.rest-day {
background: #fef2f2;
}
&:disabled {
cursor: default;
}
}
.count {
width: 100%;
color: var(--td-brand-color);
overflow: hidden;
font-size: .625rem;
font-weight: 700;
white-space: nowrap;
text-overflow: ellipsis;
}
}
@@ -493,39 +357,7 @@ function toDateValue(date: Date): number {
background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
.calendar-head {
h2 {
color: #e2e8f0;
}
}
.week-line {
color: #94a3b8;
}
.calendar-grid {
.day-cell {
color: #e2e8f0;
background: rgba(30, 41, 59, .9);
.count {
color: #60a5fa;
}
&.muted {
color: #94a3b8;
background: rgba(15, 23, 42, .7);
}
&.marked {
background: rgba(37, 99, 235, .2);
}
&.rest-day {
background: rgba(220, 38, 38, .12);
}
}
}
.count { color: #60a5fa; }
}
.day-record-panel,
@@ -0,0 +1,95 @@
<template>
<div class="month-calendar">
<div class="calendar-head">
<t-button class="month-btn" shape="square" variant="text" @click="shiftMonth(-1)">
<template #icon><t-icon name="chevron-left" /></template>
</t-button>
<h2 v-text="monthTitle" />
<div class="head-actions">
<t-button class="month-btn" shape="square" variant="text" @click="shiftMonth(1)">
<template #icon><t-icon name="chevron-right" /></template>
</t-button>
<slot name="actions" />
</div>
</div>
<slot name="subtitle" />
<div class="week-line">
<span v-for="item in weekNameList" :key="item" v-text="item" />
</div>
<div class="calendar-grid">
<button
v-for="day in days"
:key="day.key"
class="day-cell"
:class="{ muted: !day.inMonth, today: day.isToday, marked: day.marked, 'rest-day': day.isRestDay }"
type="button"
:disabled="day.disabled"
@click="emit('day-click', day)"
>
<span class="date"><span v-text="day.day" /><span v-if="day.isRestDay" class="rest">休</span></span>
<slot name="day" :day="day" />
</button>
</div>
</div>
</template>
<script setup lang="ts">
import type { MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
const props = defineProps<{ modelValue: Date; days: MonthCalendarDay[] }>();
const emit = defineEmits<{ "update:modelValue": [value: Date]; "day-click": [day: MonthCalendarDay] }>();
const weekNameList = ["日", "一", "二", "三", "四", "五", "六"];
const monthTitle = computed(() => `${props.modelValue.getFullYear()} 年 ${props.modelValue.getMonth() + 1} 月`);
function shiftMonth(offset: number): void {
emit("update:modelValue", new Date(props.modelValue.getFullYear(), props.modelValue.getMonth() + offset, 1));
}
</script>
<style scoped lang="less">
.month-calendar {
.calendar-head {
display: flex;
padding: .5rem 1rem;
align-items: center;
justify-content: space-between;
h2 { margin: 0; color: #0f172a; font-size: 1rem; font-weight: 700; }
.month-btn { width: 2.5rem; height: 2.5rem; }
.head-actions { gap: .5rem; display: flex; align-items: center; }
}
.week-line, .calendar-grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); }
.week-line { color: #52607a; padding: 0 1rem; font-size: .75rem; text-align: center; }
.calendar-grid {
gap: .375rem;
padding: 1rem 1rem .5rem;
.day-cell {
padding: .25rem;
min-height: 2.5rem;
display: flex;
min-width: 0;
color: #0f172a;
border: 1px solid var(--td-component-border);
background: #fff;
text-align: left;
align-items: flex-start;
border-radius: .25rem;
flex-direction: column;
.date { display: flex; font-size: .875rem; align-items: center; font-weight: 700; }
.rest { color: orange; margin-left: .125rem; font-size: .625rem; font-weight: 700; }
&.muted { color: #94a3b8; background: #f8fafc; }
&.today { color: var(--td-brand-color); }
&.marked { background: var(--td-brand-color-1); }
&.rest-day { background: #fef2f2; }
&:disabled { cursor: default; }
}
}
}
:global(html.theme-dark) .month-calendar {
.calendar-head h2 { color: #e2e8f0; }
.week-line { color: #94a3b8; }
.calendar-grid .day-cell {
color: #e2e8f0;
background: rgba(30, 41, 59, .9);
&.muted { color: #94a3b8; background: rgba(15, 23, 42, .7); }
&.today { color: var(--td-brand-color); }
&.marked { background: rgba(37, 99, 235, .2); }
&.rest-day { background: rgba(220, 38, 38, .12); }
}
}
</style>
@@ -0,0 +1,29 @@
export interface MonthCalendarDay {
key: string;
day: string;
dateText: string;
inMonth: boolean;
isToday: boolean;
isRestDay?: boolean;
marked?: boolean;
disabled?: boolean;
}
/** 返回包含相邻月份的六周日期。 */
export function buildMonthCalendarDays(month: Date): MonthCalendarDay[] {
const first = new Date(month.getFullYear(), month.getMonth(), 1);
first.setDate(1 - first.getDay());
const format = (date: Date): string => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
const today = format(new Date());
return Array.from({ length: 42 }, (_, index) => {
const date = new Date(first.getFullYear(), first.getMonth(), first.getDate() + index);
const dateText = format(date);
return {
key: dateText,
day: String(date.getDate()),
dateText,
inMonth: date.getMonth() === month.getMonth(),
isToday: dateText === today
};
});
}
@@ -25,6 +25,13 @@
</div>
</section>
<div class="chart-list">
<product-stock-calendar :key="calendarVersion" :store-id="storeId" />
<product-stock-movement-chart
v-entrance-transition
:date-text-list="dateTextList"
:list="stockMovementList"
:loading="isLoading"
/>
<product-sales-trend-chart
v-entrance-transition
:date-text-list="dateTextList"
@@ -49,12 +56,6 @@
:list="fulfillmentDailyList"
:loading="isLoading"
/>
<product-stock-movement-chart
v-entrance-transition
:date-text-list="dateTextList"
:list="stockMovementList"
:loading="isLoading"
/>
<product-stock-health-table
v-entrance-transition
:list="stockHealthList"
@@ -73,6 +74,7 @@ import ProductFulfillmentRankChart from "@/pages/product/component/ProductFulfil
import ProductFulfillmentTrendChart from "@/pages/product/component/ProductFulfillmentTrendChart.vue";
import ProductSalesRankChart from "@/pages/product/component/ProductSalesRankChart.vue";
import ProductSalesTrendChart from "@/pages/product/component/ProductSalesTrendChart.vue";
import ProductStockCalendar from "@/pages/product/component/ProductStockCalendar.vue";
import ProductStockHealthTable from "@/pages/product/component/ProductStockHealthTable.vue";
import ProductStockMovementChart from "@/pages/product/component/ProductStockMovementChart.vue";
import type {
@@ -122,6 +124,7 @@ const stockMovementList = ref<GaoProductStockMovementDailyStatView[]>([]);
const stockHealthList = ref<GaoProductStockHealthView[]>([]);
const skuHealthList = ref<GaoProductSkuStockHealthView[]>([]);
const isLoading = ref(false);
const calendarVersion = ref(0);
let requestId = 0;
const storeId = computed(() => currentStoreStore.currentStoreId || getCurrentStoreId());
@@ -160,6 +163,7 @@ onMounted(async () => {
async function reload(): Promise<void> {
clearStoreChartCache();
calendarVersion.value++;
await loadCharts();
}
@@ -335,7 +339,7 @@ defineExpose({
.two-columns {
gap: 1rem;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(100%, 20rem), 1fr));
}
// 分栏窄容器:双列图表一律改单列
@@ -0,0 +1,211 @@
<template>
<section class="stock-calendar">
<month-calendar v-model="month" :days="calendarDays" @day-click="openDay">
<template #actions>
<t-button
v-if="canReadProducts"
theme="primary"
size="extra-small"
variant="outline"
content="产品规格"
@click="selectorVisible = true"
>
<template #icon><t-icon name="filter" /></template>
</t-button>
</template>
<template #subtitle>
<div class="selection">
<span v-text="selectionText" />
<t-button v-if="selection" size="extra-small" variant="text" @click="clearSelection">清除</t-button>
</div>
</template>
<template #day="{ day }">
<span v-if="daily(day)?.inQuantity" class="quantity in" v-text="`入 ${daily(day)?.inQuantity}`" />
<span v-if="daily(day)?.outQuantity" class="quantity out" v-text="`出 ${daily(day)?.outQuantity}`" />
</template>
</month-calendar>
<t-loading v-if="loading" text="加载中" />
<product-select-popup
:key="storeId"
v-model="selectedProductSku"
v-model:visible="selectorVisible"
@select="selectProduct"
/>
<bottom-popup v-model="visible" :title="`${selectedDate} 库存流水`" left-button-text="关闭" @left-button-click="visible = false">
<div v-if="canReadRecords" class="records">
<div class="directions">
<t-button size="small" :theme="direction === 'IN' ? 'primary' : 'default'" @click="selectDirection('IN')">入库</t-button>
<t-button size="small" :theme="direction === 'OUT' ? 'primary' : 'default'" @click="selectDirection('OUT')">出库</t-button>
</div>
<t-cell-group v-if="records.length">
<t-cell
v-for="record in records"
:key="record.id"
:title="record.productNameSnapshot || '未命名产品'"
:description="record.skuNameSnapshot || ''"
:note="`${getStockOperationText(record.operationType)} ${record.onHandDelta || 0}(基础单位)`"
/>
</t-cell-group>
<t-empty v-else-if="!recordsLoading" description="当天暂无流水" />
<t-button v-if="!noMore" block variant="text" :loading="recordsLoading" @click="loadRecords">加载更多</t-button>
</div>
<t-empty v-else description="暂无库存流水查看权限" />
</bottom-popup>
</section>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import { useUserStore } from "timi-web-api";
import GaoProductChartAPI from "@/api/GaoProductChartAPI";
import GaoProductSkuChartAPI from "@/api/GaoProductSkuChartAPI";
import ProductAPI from "@/api/ProductAPI";
import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue";
import ProductSelectPopup from "@/components/productSelector/ProductSelectPopup.vue";
import { buildMonthCalendarDays, type MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
import type { GaoProductStockMovementDailyStatView } from "@/types/GaoChart";
import type { ProductSelection, StockRecord, StockRecordDirection } from "@/types/Product";
import type { ProductSkuSelectionValue } from "@/types/ProductSkuSelection";
import { getProductBaseUnitName, getStockOperationText } from "@/utils/product";
import { permissionCodes } from "@/utils/permission";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
const props = defineProps<{ storeId: string }>();
const userStore = useUserStore();
const canReadRecords = computed(() => userStore.hasPermissions(permissionCodes.productStock.read));
const canReadProducts = computed(() => userStore.hasPermissions(permissionCodes.product.read));
const selectorVisible = ref(false);
const selectedProductSku = ref<ProductSkuSelectionValue>();
const selection = ref<ProductSelection>();
const skuId = computed(() => selection.value?.sku.id || "");
const selectionText = computed(() => {
if (!selection.value) return "全部产品规格 · 数量按各规格基础单位汇总";
const { product, sku } = selection.value;
const name = sku.specSummary || (sku.name !== product.name ? sku.name : "");
return [product.name || product.code, name, `基础单位:${getProductBaseUnitName(sku) || "未知"}`].filter(Boolean).join(" · ");
});
function selectProduct(value: ProductSelection): void {
if (!value.sku.id) return;
selection.value = value;
}
function clearSelection(): void {
selection.value = undefined;
selectedProductSku.value = undefined;
}
const month = ref(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
const stats = ref<GaoProductStockMovementDailyStatView[]>([]);
const loading = ref(false);
let monthToken = 0;
const calendarDays = computed(() => buildMonthCalendarDays(month.value).map(day => ({
...day,
marked: !!(daily(day)?.inQuantity || daily(day)?.outQuantity)
})));
function daily(day: MonthCalendarDay): GaoProductStockMovementDailyStatView | undefined {
return stats.value.find(item => item.dateValue === Number(day.dateText.replaceAll("-", "")));
}
watch([month, () => props.storeId, skuId], async () => {
const token = ++monthToken;
stats.value = [];
loading.value = true;
try {
const first = new Date(month.value.getFullYear(), month.value.getMonth(), 1);
first.setDate(1 - first.getDay());
const beginAt = first.getTime();
const endAt = new Date(first.getFullYear(), first.getMonth(), first.getDate() + 42).getTime() - 1;
const request = { storeId: props.storeId, beginAt, endAt };
const result = skuId.value
? await GaoProductSkuChartAPI.stockMovementDaily({ ...request, skuId: skuId.value })
: await GaoProductChartAPI.stockMovementDaily(request);
if (token === monthToken) stats.value = result || [];
} catch (error) {
if (token === monthToken) Message.error(getErrorMessage(error, "库存日历加载失败"));
} finally {
if (token === monthToken) loading.value = false;
}
}, { immediate: true });
const visible = ref(false);
const selectedDate = ref("");
const selectedStart = ref(0);
const direction = ref<StockRecordDirection>("IN");
const records = ref<StockRecord[]>([]);
const recordsLoading = ref(false);
const noMore = ref(false);
let page = 0;
let recordToken = 0;
async function openDay(day: MonthCalendarDay): Promise<void> {
const [year, monthNumber, dateNumber] = day.dateText.split("-").map(Number);
const date = new Date(year, monthNumber - 1, dateNumber);
selectedStart.value = date.getTime();
selectedDate.value = day.dateText;
visible.value = true;
if (canReadRecords.value) await selectDirection("IN");
}
async function selectDirection(value: StockRecordDirection): Promise<void> {
direction.value = value;
recordToken++;
records.value = [];
page = 0;
noMore.value = false;
recordsLoading.value = false;
await loadRecords();
}
async function loadRecords(): Promise<void> {
if (recordsLoading.value || noMore.value) return;
const token = ++recordToken;
recordsLoading.value = true;
try {
const start = new Date(selectedStart.value);
const endAt = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 1).getTime() - 1;
const result = await ProductAPI.recordList({ storeId: props.storeId, skuId: skuId.value || undefined, beginAt: selectedStart.value, endAt, direction: direction.value, index: page, size: 15 });
if (token !== recordToken) return;
const list = result.list || [];
records.value.push(...list);
page++;
noMore.value = list.length < 15 || !(records.value.length < (result.total || 0));
} catch (error) {
if (token === recordToken) Message.error(getErrorMessage(error, "库存流水加载失败"));
} finally {
if (token === recordToken) recordsLoading.value = false;
}
}
watch([() => props.storeId, skuId], () => {
visible.value = false;
recordToken++;
});
watch(() => props.storeId, () => {
selectorVisible.value = false;
clearSelection();
});
</script>
<style scoped lang="less">
.stock-calendar {
border-radius: 1rem;
background: var(--td-bg-color-container, #fff);
.selection {
gap: .5rem;
display: flex;
padding: 0 1rem .5rem;
color: var(--td-text-color-secondary);
font-size: .75rem;
align-items: center;
justify-content: space-between;
}
.quantity {
overflow: hidden;
max-width: 100%;
font-size: .625rem;
white-space: nowrap;
text-overflow: ellipsis;
&.in { color: var(--td-success-color); }
&.out { color: var(--td-error-color); }
}
.records { overflow: auto; max-height: 60vh; }
.directions { display: flex; gap: .5rem; padding: .75rem; }
}
</style>