Skip to content
Extraits de code Groupes Projets
Valider 7479b9bc rédigé par salaheddine zidani's avatar salaheddine zidani
Parcourir les fichiers

save changes

parent 26d81fda
Branches
1 requête de fusion!264Refactoring Sale an Supplier Order Management module
Pipeline #6768 en échec avec l'étape
in 31 minutes et 55 secondes
import React, { useMemo, useCallback, useState, useEffect } from "react";
import React, { useMemo, useState, useEffect } from "react";
import { useForm, Resolver, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as Yup from "yup";
import { Grid } from "@mui/material";
import { useRouter } from "@/hooks";
import { useResponsive } from "@/hooks/use-responsive";
import { useSnackbar } from "@/shared/components/snackbar";
import FormProvider from "@/shared/components/hook-form";
import ProductDetails from "./ProductDetails";
import ProductProperties from "./ProductProperties";
......@@ -23,17 +22,17 @@ import {
useAllGetProducts,
useAddSimpleProduct,
useUpdateProduct,
checkUgsUnique,
} from "@/shared/api/product";
import { paths } from "@/routes/paths";
import { CustomProduct } from "@/shared/api/create-supplier-order";
import CustomAlert from "@/shared/components/CustomAlert";
import { logger } from "@/utils/logger";
import { CustomProduct } from "../../supplier/supplier-orders/add-edit-SupplierOrder/order-new-edit-details";
type Props = {
currentProduct?: IProductItem;
onClose?: () => void;
onAddProduct?: (product: CustomProduct) => void
onAddProduct?: (product: CustomProduct) => void;
};
export default function ProductNewEditForm({
......@@ -51,18 +50,33 @@ export default function ProductNewEditForm({
const { revalidate } = useAllGetProducts();
const { productMutate } = useUpdateProduct(currentProduct?.id!);
const [alert, setAlert] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
const [isCheckingUgs, setIsCheckingUgs] = useState(false);
const NewProductSchema = Yup.object().shape({
ugs: Yup.string().required("UGS is required"),
name: Yup.string().required("Name is required"),
ugs: Yup.string()
.required("UGS est requis")
.test("is-unique", "UGS déjà utilisé.", async function (value) {
const { currentProduct } = this.options.context as { currentProduct?: IProductItem };
if (currentProduct && currentProduct.ugs === value) {
return true;
}
const isUnique = await checkUgsUnique(value || "");
return isUnique;
}),
name: Yup.string().required("Le nom est requis"),
regularPrice: Yup.number()
.required("regularPrice is required")
.min(0, "Price cannot be negative"),
promoPrice: Yup.number()
.min(0, "Promo price cannot be negative")
.required("Le tarif régulier est requis")
.min(0, "Le prix ne peut pas être négatif"),
promoPrice: Yup.number()
.transform((value, originalValue) => (originalValue === "" ? null : value))
.nullable()
.min(0, "Le prix promo ne peut pas être négatif")
.optional(),
description: Yup.string().optional(),
shortDescription: Yup.string().optional(),
draft: Yup.boolean().required("Draft status is required"),
draft: Yup.boolean().required("Le statut de brouillon est requis"),
publishWeb: Yup.boolean().optional(),
publishLive: Yup.boolean().optional(),
liveProductConfigs: Yup.object().shape({
......@@ -71,24 +85,23 @@ export default function ProductNewEditForm({
}),
stockWebConfig: Yup.object().shape({
quantity: Yup.number()
.nullable()
.min(0, "Web stock quantity cannot be negative")
.optional(),
.nullable()
.min(0, "La quantité en stock web ne peut pas être négative")
.optional(),
isPreOrderAuthorized: Yup.string().optional(),
authorizedConfig: Yup.boolean().optional(),
thresholdValue: Yup.number().nullable(),
}),
stockLiveConfig: Yup.object().shape({
quantity: Yup.number()
.nullable()
.min(0, "Live stock quantity cannot be negative")
.optional(),
.nullable()
.min(0, "La quantité en stock live ne peut pas être négative")
.optional(),
isPreOrderAuthorized: Yup.string().optional(),
authorizedConfig: Yup.boolean().optional(),
thresholdValue: Yup.number().nullable(),
}),
});
const defaultValues = useMemo(
() => ({
......@@ -104,7 +117,7 @@ export default function ProductNewEditForm({
draft: currentProduct?.draft,
material: currentProduct?.material || "",
categoryIds: currentProduct?.categoryIds,
tagIds: currentProduct?.tagIds,
tagIds: currentProduct?.tagIds || [],
variations: currentProduct?.variations || [],
regularPrice: currentProduct?.regularPrice,
promoPrice: currentProduct?.promoPrice,
......@@ -129,7 +142,6 @@ export default function ProductNewEditForm({
authorizedConfig: false,
thresholdValue: null,
},
liveProductConfigs: currentProduct?.liveProductConfigs || {
feedStockFromWebStock: true,
authorizeUpdateQuantity: true,
......@@ -144,6 +156,8 @@ export default function ProductNewEditForm({
any
>,
defaultValues,
context: { currentProduct },
mode: "onChange",
});
const {
......@@ -152,8 +166,11 @@ export default function ProductNewEditForm({
control,
handleSubmit,
formState: { isSubmitting },
setError,
clearErrors,
} = methods;
const values = watch();
useEffect(() => {
if (variations.length > 0) {
methods.setValue("variations", variations);
......@@ -174,9 +191,38 @@ export default function ProductNewEditForm({
variations: currentProduct.variations || [],
});
}
}, [currentProduct, reset]);
}, [currentProduct, reset, defaultValues]);
const [alert, setAlert] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
const ugsValue = watch("ugs");
useEffect(() => {
if (ugsValue === undefined) return;
const handler = setTimeout(async () => {
if (ugsValue) {
if (isEditing && currentProduct && currentProduct.ugs === ugsValue) {
clearErrors("ugs");
setIsCheckingUgs(false);
return;
}
setIsCheckingUgs(true);
const isUnique = await checkUgsUnique(ugsValue);
setIsCheckingUgs(false);
if (!isUnique) {
setError("ugs", {
type: "manual",
message: "UGS déjà utilisé.",
});
} else {
clearErrors("ugs");
}
}
}, 500);
return () => {
clearTimeout(handler);
};
}, [ugsValue, isEditing, currentProduct, setError, clearErrors]);
const onSubmit = handleSubmit(async (data: IProductItem) => {
try {
......@@ -226,8 +272,8 @@ export default function ProductNewEditForm({
await onAddProduct({
id: response.id,
name: response.name,
regularPrice: response.regularPrice!,
isVariable: response.productType == ProductType.VARIABLE,
price: response.regularPrice,
isVariable: response.productType !== "SIMPLE",
mainImagePath: response.mainImagePath,
type: response.productType,
quantity:
......@@ -237,10 +283,10 @@ export default function ProductNewEditForm({
(v: any) => ({
id: v.id,
name: v.name,
regularPrice:v.regularPrice,
mainImagePath: v.mainImagePath || response.mainImagePath,
mainImagePath: v.mainImagePath,
regularPrice: v.regularPrice,
quantity: (v.stockWebConfig?.quantity || 0) +
(v.stockLiveConfig?.quantity || 0)
(v.stockLiveConfig?.quantity || 0)
})
) : []
});
......@@ -290,6 +336,7 @@ export default function ProductNewEditForm({
setVariations={setVariations}
currentProduct={currentProduct}
mainImagePath={path}
isCheckingUgs={isCheckingUgs}
/>
<FormActions
......
0% ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter