|
|
@@ -1,6 +1,6 @@
|
|
|
"use client";
|
|
|
|
|
|
-import { useState, useMemo, useEffect } from "react";
|
|
|
+import { useState, useMemo } from "react";
|
|
|
import clsx from "clsx";
|
|
|
import {
|
|
|
ProductOption,
|
|
|
@@ -8,124 +8,20 @@ import {
|
|
|
} from "@/components/catalog/type";
|
|
|
import { ProductAddToCart } from "@/app/(public)/product/_components/ProductAddToCart";
|
|
|
import { useCustomToast } from "@utils/hooks/useToast";
|
|
|
-import {clientFetch} from "@/lib/restApiClient";
|
|
|
import { useAddProduct } from "@utils/hooks/useAddToCart";
|
|
|
import { redirect, RedirectType } from 'next/navigation'
|
|
|
-/**
|
|
|
- * 辅助函数:判断一个完整的选项值ID组合是否对应一个可购买的变体(quantity > 0)
|
|
|
- * @param selectedIds {number[]} 选中的选项值ID的数组
|
|
|
- * @param variants {ResolvedVariant[]} 变体列表
|
|
|
- * @returns {boolean} 该选项组和对应的变体是否可用
|
|
|
- * */
|
|
|
-function isCombinationAvailable(
|
|
|
- selectedIds: number[],
|
|
|
- variants: ResolvedVariant[]
|
|
|
-): boolean {
|
|
|
- // some 每一项都带入参数函数执行,如果遇到一项带入函数执行结果是true,则返回true;如果所有项带入函数执行,结果都是false,则返回false
|
|
|
- return variants.some((variant) => {
|
|
|
- if (variant.quantity <= 0) return false;
|
|
|
- const values = variant.optionValues;
|
|
|
+import {
|
|
|
+ isValueAvailable,
|
|
|
+ isOptionValueAvailable,
|
|
|
+ getFirstAvailable,
|
|
|
+ getAvailableVariants,
|
|
|
+ isCombinationAvailable,
|
|
|
+ formatFlexibleVariants,
|
|
|
+ findNearestAvailableVariant
|
|
|
+} from "@/utils/variantTools";
|
|
|
+import { Price } from "@components/theme/ui/Price";
|
|
|
|
|
|
- const variantValueIds = values.map((v) => v.id);
|
|
|
- return (
|
|
|
- selectedIds.length === variantValueIds.length &&
|
|
|
- selectedIds.every((id) => variantValueIds.includes(id))
|
|
|
- );
|
|
|
- });
|
|
|
-}
|
|
|
-
|
|
|
-/**
|
|
|
- * 辅助函数:根据部分选中的映射,判断某个选项值是否可用
|
|
|
- * @param optionId {number} 选项组ID
|
|
|
- * @param valueId {number} 选项值ID
|
|
|
- * @param currentSelected {Record<number, number>} 当前已选中的映射
|
|
|
- * @param allOptions 产品选项列表
|
|
|
- * @param variants 产品变体列表
|
|
|
- * @returns {boolean} 该选项值是否可用
|
|
|
- * */
|
|
|
-function isOptionValueAvailable(
|
|
|
- optionId: number,
|
|
|
- valueId: number,
|
|
|
- currentSelected: Record<number, number>, // 当前已选中的映射
|
|
|
- allOptions: ProductOption[],
|
|
|
- variants: ResolvedVariant[]
|
|
|
-): boolean {
|
|
|
- const testSelected = { ...currentSelected, [optionId]: valueId };
|
|
|
- // 检查是否所有选项组都已选中(有些组可能尚未选择,但禁用判断时我们只关心已选中的组能否与当前测试值组成可用变体)
|
|
|
- // 获取所有选项值ID的列表
|
|
|
- const selectedValueIds = Object.values(testSelected);
|
|
|
- // 如果有任何组未选中,则无法构成完整变体,此时应视为可能可用(不禁用),因为用户还需要继续选择
|
|
|
- if (selectedValueIds.length < allOptions.length) {
|
|
|
- // 但需要检查:在已选中的这些组中,是否存在一个变体其对应的值包含这些已选中的值?
|
|
|
- // 即是否存在变体,其选项值集合包含当前测试选中的值(作为子集)
|
|
|
- return variants.some((variant) => {
|
|
|
- if (variant.quantity <= 0) return false;
|
|
|
- const values = variant.optionValues;
|
|
|
- const variantValueIds = values.map((v) => v.id);
|
|
|
- // 检查测试选中的值是否都是该变体选项值的子集
|
|
|
- return selectedValueIds.every((id) => variantValueIds.includes(id));
|
|
|
- });
|
|
|
- } else {
|
|
|
- // 所有组都已选中,直接检查完整组合是否可用
|
|
|
- return isCombinationAvailable(selectedValueIds, variants);
|
|
|
- }
|
|
|
-}
|
|
|
-/**
|
|
|
- * 根据传入的value id判断变体中是否存在可购买变体,如果有返回true,如果没有则返回false
|
|
|
- * @param valueId {number} 选项值ID
|
|
|
- * @param variants {ResolvedVariant[]} 变体列表
|
|
|
- * @returns {boolean} 该value id是否可用
|
|
|
- * */
|
|
|
-function isValueAvailable( valueId: number, variants: ResolvedVariant[]): boolean {
|
|
|
- return variants.some((variant) => {
|
|
|
- if (variant.quantity <= 0) return false;
|
|
|
- const values = variant.optionValues;
|
|
|
- const variantValueIds = values.map((v) => v.id);
|
|
|
- return variantValueIds.includes(valueId);
|
|
|
- });
|
|
|
-}
|
|
|
-/**
|
|
|
- * 根据传入的value id组合,找到一个最近的可购买的变体
|
|
|
- * @param fixedOptionId {number} 调过校验的选项组id
|
|
|
- * @param fixedValueId {number} 调过校验的选项值id
|
|
|
- * @param valueIdMap {Record<number, number>} 选中的选项值映射
|
|
|
- * @param allOptions 产品的选项列表
|
|
|
- * @param variants 产品的变体列表
|
|
|
- * @returns {Record<number, number>} 返回一个最近可用变体的选项值映射
|
|
|
- * */
|
|
|
-function findNearestAvailableVariant(
|
|
|
- fixedOptionId: number,
|
|
|
- fixedValueId: number,
|
|
|
- valueIdMap: Record<number, number>,
|
|
|
- allOptions: ProductOption[],
|
|
|
- variants: ResolvedVariant[] // 可购买的变体列表
|
|
|
-): Record<number, number>{
|
|
|
- let res:Record<number, number> = {[fixedOptionId]: fixedValueId};
|
|
|
|
|
|
- for (const option of allOptions) {
|
|
|
- let optionId = option.id;
|
|
|
- if(fixedOptionId === optionId) continue;
|
|
|
- let valueId = valueIdMap[optionId];
|
|
|
- if(isOptionValueAvailable(optionId,valueId,res,allOptions,variants)) {
|
|
|
- res = {...res,[optionId]: valueId};
|
|
|
- } else {
|
|
|
- let found = false;
|
|
|
- for(let i = 0; i < option.values.length; i++) {
|
|
|
- if(isOptionValueAvailable(optionId,option.values[i].id,res,allOptions,variants)) {
|
|
|
- found = true;
|
|
|
- res = {...res,[optionId]: option.values[i].id};
|
|
|
- break;
|
|
|
- }
|
|
|
- }
|
|
|
- if (!found) {
|
|
|
- // 极端情况:找不到可用值,保留原值以维持完整状态
|
|
|
- res = { ...res, [optionId]: valueId };
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- return res;
|
|
|
-}
|
|
|
export function ProductInformation({
|
|
|
name,
|
|
|
productId,
|
|
|
@@ -149,41 +45,14 @@ export function ProductInformation({
|
|
|
|
|
|
// 获取所有可用变体(quantity > 0)
|
|
|
const availableVariants = useMemo(() => {
|
|
|
- return flexibleVariants.filter((v) => v.quantity > 0);
|
|
|
+ return getAvailableVariants(flexibleVariants);
|
|
|
}, [flexibleVariants]);
|
|
|
|
|
|
// 当前选中的选项值映射:option_id -> value_id
|
|
|
- // const [selected, setSelected] = useState<Record<number, number>>({});
|
|
|
-
|
|
|
const [selected, setSelected] = useState<Record<number, number>>(() => {
|
|
|
let res: Record<number, number> = {};
|
|
|
- // 递归回溯查找第一个可用组合
|
|
|
- const findFirstAvailable = ( optionIndex: number, currentMap: Record<number, number> ): Record<number, number> | null => {
|
|
|
- if (optionIndex >= productOptions.length) {
|
|
|
- // 所有组都已选,检查完整组合是否可用
|
|
|
- const valueIds = Object.values(currentMap);
|
|
|
- return isCombinationAvailable(valueIds, flexibleVariants) ? { ...currentMap } : null;
|
|
|
- }
|
|
|
-
|
|
|
- const option = productOptions[optionIndex];
|
|
|
- for (const value of option.values) {
|
|
|
- const nextMap = { ...currentMap, [option.id]: value.id };
|
|
|
- // 剪枝:检查当前部分组合是否可能导向可用变体
|
|
|
- const partialValueIds = Object.values(nextMap);
|
|
|
- const hasPotential = flexibleVariants.some((v) => {
|
|
|
- if (v.quantity <= 0) return false;
|
|
|
- const vIds = v.optionValues.map((ov) => ov.id);
|
|
|
- return partialValueIds.every((id) => vIds.includes(id));
|
|
|
- });
|
|
|
- if (!hasPotential) continue;
|
|
|
|
|
|
- const result = findFirstAvailable(optionIndex + 1, nextMap);
|
|
|
- if (result) return result;
|
|
|
- }
|
|
|
- return null;
|
|
|
- };
|
|
|
-
|
|
|
- const defaultSelected = findFirstAvailable(0, {});
|
|
|
+ const defaultSelected = getFirstAvailable(productOptions, flexibleVariants);;
|
|
|
if (defaultSelected) {
|
|
|
res = defaultSelected;
|
|
|
} else {
|
|
|
@@ -195,53 +64,7 @@ export function ProductInformation({
|
|
|
console.log('set default selected');
|
|
|
return res;
|
|
|
});
|
|
|
- /****
|
|
|
- // useEffect在浏览器绘制后执行
|
|
|
- // 初始化默认选中:找到第一个可用的完整组合
|
|
|
- useEffect(() => {
|
|
|
- // 如果已经初始化过,不再重复执行
|
|
|
- if (Object.keys(selected).length > 0) return;
|
|
|
|
|
|
- // 递归回溯查找第一个可用组合
|
|
|
- const findFirstAvailable = ( optionIndex: number, currentMap: Record<number, number> ): Record<number, number> | null => {
|
|
|
- if (optionIndex >= productOptions.length) {
|
|
|
- // 所有组都已选,检查完整组合是否可用
|
|
|
- const valueIds = Object.values(currentMap);
|
|
|
- return isCombinationAvailable(valueIds, flexibleVariants) ? { ...currentMap } : null;
|
|
|
- }
|
|
|
-
|
|
|
- const option = productOptions[optionIndex];
|
|
|
- for (const value of option.values) {
|
|
|
- const nextMap = { ...currentMap, [option.id]: value.id };
|
|
|
- // 剪枝:检查当前部分组合是否可能导向可用变体
|
|
|
- const partialValueIds = Object.values(nextMap);
|
|
|
- const hasPotential = flexibleVariants.some((v) => {
|
|
|
- if (v.quantity <= 0) return false;
|
|
|
- const vIds = v.optionValues.map((ov) => ov.id);
|
|
|
- return partialValueIds.every((id) => vIds.includes(id));
|
|
|
- });
|
|
|
- if (!hasPotential) continue;
|
|
|
-
|
|
|
- const result = findFirstAvailable(optionIndex + 1, nextMap);
|
|
|
- if (result) return result;
|
|
|
- }
|
|
|
- return null;
|
|
|
- };
|
|
|
-
|
|
|
- const defaultSelected = findFirstAvailable(0, {});
|
|
|
- if (defaultSelected) {
|
|
|
- setSelected(defaultSelected);
|
|
|
- } else {
|
|
|
- // 极端情况:没有任何可用组合,默认全选每组第一个(但仍需标记为不可用,由禁用逻辑处理)
|
|
|
- const fallback: Record<number, number> = {};
|
|
|
- productOptions.forEach((opt) => {
|
|
|
- fallback[opt.id] = opt.values[0]?.id;
|
|
|
- });
|
|
|
- setSelected(fallback);
|
|
|
- }
|
|
|
- console.log('set default selected');
|
|
|
- }, [productOptions, flexibleVariants, selected]);
|
|
|
- ****/
|
|
|
// 计算每个选项值的禁用状态
|
|
|
const disabledMap = useMemo(() => {
|
|
|
const map: Record<number, boolean> = {};
|
|
|
@@ -301,10 +124,6 @@ export function ProductInformation({
|
|
|
// useEffect和useMemo的执行时机不同,useMemo早于useEffect执行,如果使用useEffect初始化selected,则需要对selected做判断,当为空对象时返回占位对象
|
|
|
const currentVariantInfo: {variant:ResolvedVariant | null; totalLinePrice: number; totalNowPrice: number; save: number;} = useMemo(() => {
|
|
|
const selectedIds = Object.values(selected);
|
|
|
- if (selectedIds.length === 0) {
|
|
|
- // 尚未初始化,返回一个安全占位对象
|
|
|
- return { variant: null, totalLinePrice: 0, totalNowPrice: 0, save: 0 };
|
|
|
- }
|
|
|
let totalLinePrice = 0;
|
|
|
let totalNowPrice = 0;
|
|
|
let save = 0;
|
|
|
@@ -312,17 +131,17 @@ export function ProductInformation({
|
|
|
const vIds = v.optionValues.map((ov) => ov.id);
|
|
|
return selectedIds.length === vIds.length && selectedIds.every((id) => vIds.includes(id));
|
|
|
});
|
|
|
- // 类型守卫
|
|
|
- if(variant === undefined) {
|
|
|
- // 显式断言 + 运行时保护
|
|
|
- throw new Error(`Unexpected: no variant matches selected ${JSON.stringify(selected)}`);
|
|
|
+ if (selectedIds.length === 0 || variant === undefined) {
|
|
|
+ // 尚未初始化,返回一个安全占位对象
|
|
|
+ return { variant: null, totalLinePrice: 0, totalNowPrice: 0, save: 0 };
|
|
|
}
|
|
|
- if(variant.priceIndices) {
|
|
|
+
|
|
|
+ if(variant.priceIndices && variant.priceIndices.length > 0) {
|
|
|
totalLinePrice = Number(variant.priceIndices[0].regular_min_price) * productQty;
|
|
|
totalNowPrice = Number(variant.priceIndices[0].min_price) * productQty;
|
|
|
}
|
|
|
if(totalLinePrice !== totalNowPrice) {
|
|
|
- save = totalLinePrice - totalNowPrice;
|
|
|
+ save = -(totalLinePrice - totalNowPrice);
|
|
|
}
|
|
|
|
|
|
return {
|
|
|
@@ -366,11 +185,6 @@ export function ProductInformation({
|
|
|
|
|
|
let addToCartHandler = async () => {
|
|
|
|
|
|
- // let result = await clientFetch('/api/shop/addProductInCart',{
|
|
|
- // method: "POST",
|
|
|
- // body: JSON.stringify({ productId: productId, quantity: productQty, variantId: currentVariantInfo.variant?._id }),
|
|
|
- // });
|
|
|
- // console.log(result);
|
|
|
if(!isCurrentSelectionAvailable) {
|
|
|
showToast("The selected options are not available!", "warning");
|
|
|
return;
|
|
|
@@ -397,18 +211,28 @@ export function ProductInformation({
|
|
|
<h3 className="text-ly-12 mt-4 leading-ly-22">{name} {isSaleable}</h3>
|
|
|
|
|
|
<div className="flex items-center mt-2">
|
|
|
- <span className="text-ly-16 leading-ly-24 font-bold">
|
|
|
- {currentVariantInfo.totalNowPrice.toFixed(2)}
|
|
|
- </span>
|
|
|
+ <Price
|
|
|
+ className="text-ly-16 leading-ly-24 font-bold"
|
|
|
+ amount={String(currentVariantInfo.totalNowPrice)}
|
|
|
+ currencyCode="USD"
|
|
|
+ />
|
|
|
{
|
|
|
currentVariantInfo.totalLinePrice !== currentVariantInfo.totalNowPrice && (
|
|
|
<>
|
|
|
- <span className="text-ly-12 leading-ly-20 text-ly-gray line-through ml-1">
|
|
|
- {currentVariantInfo.totalLinePrice.toFixed(2)}
|
|
|
- </span>
|
|
|
- <span className="text-ly-12 leading-ly-16 bg-ly-gold pr-1.5 pl-1.5 ml-3">
|
|
|
- -{currentVariantInfo.save.toFixed(2)}
|
|
|
- </span>
|
|
|
+ <Price
|
|
|
+ className="text-ly-12 leading-ly-20 text-ly-gray line-through ml-1"
|
|
|
+ amount={String(currentVariantInfo.totalLinePrice)}
|
|
|
+ currencyCode="USD"
|
|
|
+ /><Price
|
|
|
+ className="text-ly-12 leading-ly-20 text-ly-gray line-through ml-1"
|
|
|
+ amount={String(currentVariantInfo.totalLinePrice)}
|
|
|
+ currencyCode="USD"
|
|
|
+ />
|
|
|
+ <Price
|
|
|
+ className="text-ly-12 leading-ly-16 bg-ly-gold pr-1.5 pl-1.5 ml-3"
|
|
|
+ amount={String(currentVariantInfo.save)}
|
|
|
+ currencyCode="USD"
|
|
|
+ />
|
|
|
</>
|
|
|
)
|
|
|
}
|