From 2272f038a5c3373a2cdec9485ac7ae2581e18c1a Mon Sep 17 00:00:00 2001 From: dominik-zeglen Date: Fri, 14 Feb 2020 12:19:17 +0100 Subject: [PATCH] Move label creation logic to util function --- .../ProductVariants/ProductVariants.tsx | 101 +++++++++++------- 1 file changed, 62 insertions(+), 39 deletions(-) diff --git a/src/products/components/ProductVariants/ProductVariants.tsx b/src/products/components/ProductVariants/ProductVariants.tsx index fe6b79765..f92aff08f 100644 --- a/src/products/components/ProductVariants/ProductVariants.tsx +++ b/src/products/components/ProductVariants/ProductVariants.tsx @@ -112,6 +112,61 @@ const useStyles = makeStyles( { name: "ProductVariants" } ); +function getAvailabilityLabel( + intl: IntlShape, + warehouse: string, + variant: ProductDetails_product_variants, + numAvailable: number +): string { + const variantStock = variant.stock.find(s => s.warehouse.id === warehouse); + + if (!!warehouse) { + if (!!variantStock) { + if (variantStock.quantity > 0) { + return intl.formatMessage( + { + defaultMessage: + "{stockQuantity,plural,other{{stockQuantity} available}}", + description: "product variant inventory" + }, + { + stockQuantity: variantStock.quantity + } + ); + } else { + return intl.formatMessage({ + defaultMessage: "Unavailable", + description: "product variant inventory" + }); + } + } else { + return intl.formatMessage({ + defaultMessage: "Not stocked", + description: "product variant inventory" + }); + } + } else { + if (numAvailable > 0) { + return intl.formatMessage( + { + defaultMessage: + "{numLocations,plural,one{{numAvailable} available at {numLocations} location} other{{numAvailable} available at {numLocations} locations}}", + description: "product variant inventory" + }, + { + numAvailable, + numLocations: variant.stock.length + } + ); + } else { + return intl.formatMessage({ + defaultMessage: "Unavailable in all locations", + description: "product variant inventory" + }); + } + } +} + interface ProductVariantsProps extends ListActions { disabled: boolean; variants: ProductDetails_product_variants[]; @@ -140,7 +195,7 @@ export const ProductVariants: React.FC = props => { const classes = useStyles(props); const intl = useIntl(); - const [warehouse, setWarehouse] = React.useState(null); + const [warehouse, setWarehouse] = React.useState(null); const hasVariants = maybe(() => variants.length > 0, true); return ( @@ -243,9 +298,6 @@ export const ProductVariants: React.FC = props => { variant && variant.stock ? variant.stock.reduce((acc, s) => acc + s.quantity, 0) : null; - const variantStock = variant.stock.find( - s => s.warehouse.id === warehouse - ); return ( = props => { > {numAvailable === null ? ( - ) : warehouse === null ? ( - numAvailable === 0 ? ( - - ) : ( - - ) - ) : !!variantStock ? ( - variantStock.quantity > 0 ? ( - - ) : ( - - ) ) : ( - + getAvailabilityLabel( + intl, + warehouse, + variant, + numAvailable + ) )}