Files
gao-customer-h5/src/pages/product/component/ProductStockCalendar.vue
T

243 lines
7.8 KiB
Vue

<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 && 1 < units.length"
size="extra-small"
variant="text"
@click="nextUnit"
:content="`单位:${currentUnit?.name}`"
/>
<t-button
v-if="selection"
size="extra-small"
variant="outline"
content="清除"
@click="clearSelection"
/>
</div>
</template>
<template #day="{ day }">
<template v-if="selection">
<span
v-if="daily(day)?.inQuantity"
class="quantity in"
v-text="formatQuantity(daily(day)?.inQuantity)"
/>
<span
v-if="daily(day)?.outQuantity"
class="quantity out"
v-text="formatQuantity(daily(day)?.outQuantity)"
/>
</template>
<span class="movement-bar" :style="movementStyle(day)" />
</template>
</month-calendar>
<t-loading v-if="loading" text="加载中" />
<product-select-popup
:key="storeId"
v-model="selectedProductSku"
v-model:visible="selectorVisible"
@select="selectProduct"
/>
<product-stock-calendar-records-popup
ref="recordsPopup"
v-model:unit-index="unitIndex"
:store-id="storeId"
:selection="selection"
:summary="selectedSummary"
:summary-loading="loading"
@date-change="selectedDate = $event"
/>
</section>
</template>
<script setup lang="ts">
import { useUserStore } from "timi-web-api";
import GaoProductChartAPI from "@/api/GaoProductChartAPI";
import GaoProductSkuChartAPI from "@/api/GaoProductSkuChartAPI";
import StoreChartAPI from "@/api/StoreChartAPI";
import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue";
import ProductSelectPopup from "@/components/productSelector/ProductSelectPopup.vue";
import ProductStockCalendarRecordsPopup from "@/pages/product/component/ProductStockCalendarRecordsPopup.vue";
import { buildMonthCalendarDays, type MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
import type { GaoProductStockMovementDailyStatView } from "@/types/GaoChart";
import type { ProductSelection } from "@/types/Product";
import type { ProductSkuSelectionValue } from "@/types/ProductSkuSelection";
import { permissionCodes } from "@/utils/permission";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
const props = defineProps<{ storeId: string }>();
const userStore = useUserStore();
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
].filter(Boolean).join(" · ");
});
const unitIndex = ref(0);
const units = computed(() => selection.value?.sku.unitList || []);
const currentUnit = computed(() => units.value[unitIndex.value]);
function nextUnit(): void {
unitIndex.value = (unitIndex.value + 1) % units.value.length;
}
function formatQuantity(value: number | string | undefined): string {
const ratio = Number(currentUnit.value?.baseQuantityPerUnit) || 1;
return String(Number((Number(value || 0) / ratio).toFixed(4)));
}
function movementStyle(day: MonthCalendarDay): Record<string, string> {
const item = daily(day);
const incoming = Math.abs(Number(item?.inQuantity) || 0);
const outgoing = Math.abs(Number(item?.outQuantity) || 0);
if (!incoming && !outgoing) return { background: "var(--td-component-stroke)" };
const percentage = incoming / (incoming + outgoing) * 100;
return { background: `linear-gradient(90deg, var(--td-success-color-4) ${percentage}%, var(--td-error-color-4) ${percentage}%)` };
}
function selectProduct(value: ProductSelection): void {
if (!value.sku.id) return;
selection.value = value;
unitIndex.value = Math.max(0, (value.sku.unitList || []).findIndex(unit => unit.id === value.unit.id));
}
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;
let restDayToken = 0;
const restDaySet = ref<Set<number>>(new Set());
watch([month, () => props.storeId], async () => {
const token = ++restDayToken;
const days = buildMonthCalendarDays(month.value);
try {
const list = await StoreChartAPI.businessDayCalendar(props.storeId, Number(days[0].dateText.replaceAll("-", "")), Number(days[days.length - 1].dateText.replaceAll("-", "")));
if (token === restDayToken) restDaySet.value = new Set(list.filter(item => item.status === "CLOSED" && item.dateValue).map(item => item.dateValue as number));
} catch {
if (token === restDayToken) restDaySet.value = new Set();
}
}, { immediate: true });
const calendarDays = computed(() => buildMonthCalendarDays(month.value).map(day => ({
...day,
isRestDay: restDaySet.value.has(Number(day.dateText.replaceAll("-", "")))
})));
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 recordsPopup = ref<InstanceType<typeof ProductStockCalendarRecordsPopup>>();
const selectedDate = ref("");
const selectedSummary = computed(() => stats.value.find(item => item.dateValue === Number(selectedDate.value.replaceAll("-", ""))));
async function openDay(day: MonthCalendarDay): Promise<void> {
await recordsPopup.value?.openDay(day);
}
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: end;
}
.movement-bar {
width: 100%;
height: .25rem;
flex-shrink: 0;
margin-top: auto;
border-radius: .125rem;
}
.quantity {
margin-bottom: .125rem;
}
.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);
}
}
}
</style>