saleor-dashboard/src/products/utils/handlers.ts

100 lines
2.8 KiB
TypeScript
Raw Normal View History

2020-10-15 11:56:22 +00:00
import { MultiAutocompleteChoiceType } from "@saleor/components/MultiAutocompleteSelectField";
2019-08-09 10:17:04 +00:00
import { FormChange } from "@saleor/hooks/useForm";
import { FormsetChange, FormsetData } from "@saleor/hooks/useFormset";
import { toggle } from "@saleor/utils/lists";
2019-08-09 10:17:04 +00:00
import { ProductAttributeInputData } from "../components/ProductAttributes";
2020-10-15 11:56:22 +00:00
import { getAttributeInputFromProductType, ProductType } from "./data";
2019-08-09 10:17:04 +00:00
export function createAttributeChangeHandler(
changeAttributeData: FormsetChange<string[]>,
triggerChange: () => void
): FormsetChange {
return (attributeId: string, value: string) => {
triggerChange();
2020-10-12 10:45:07 +00:00
changeAttributeData(attributeId, value === "" ? [] : [value]);
2019-08-09 10:17:04 +00:00
};
}
export function createAttributeMultiChangeHandler(
changeAttributeData: FormsetChange<string[]>,
attributes: FormsetData<ProductAttributeInputData>,
triggerChange: () => void
): FormsetChange {
return (attributeId: string, value: string) => {
const attributeValue = attributes
.find(attribute => attribute.id === attributeId)
.data.values.find(attributeValue => attributeValue.slug === value);
const valueChoice = {
label: attributeValue ? attributeValue.name : value,
value
};
2020-10-15 11:56:22 +00:00
const itemIndex = attributes.findIndex(item => item.id === attributeId);
const attributeValues: MultiAutocompleteChoiceType[] = attributes[
itemIndex
].data.values.map(value => ({
label: value.name,
value: value.id
}));
2019-08-09 10:17:04 +00:00
const newAttributeValues = toggle(
valueChoice,
attributeValues,
(a, b) => a.value === b.value
);
triggerChange();
changeAttributeData(
attributeId,
newAttributeValues.map(({ value }) => value)
);
};
}
export function createProductTypeSelectHandler(
change: FormChange,
setAttributes: (data: FormsetData<ProductAttributeInputData>) => void,
setProductType: (productType: ProductType) => void,
productTypeChoiceList: ProductType[]
): FormChange {
return (event: React.ChangeEvent<any>) => {
const id = event.target.value;
const selectedProductType = productTypeChoiceList.find(
productType => productType.id === id
);
setProductType(selectedProductType);
change(event);
setAttributes(getAttributeInputFromProductType(selectedProductType));
};
}
interface ProductAvailabilityArgs {
availableForPurchase: string | null;
isAvailableForPurchase: boolean;
productId: string;
}
export function getProductAvailabilityVariables({
isAvailableForPurchase,
availableForPurchase,
productId
}: ProductAvailabilityArgs) {
const isAvailable =
availableForPurchase && !isAvailableForPurchase
? true
: isAvailableForPurchase;
return {
isAvailable,
productId,
startDate: isAvailableForPurchase
? null
: availableForPurchase !== ""
? availableForPurchase
: null
};
}