@ubnt/store.core 9.36.0-beta.5 → 9.37.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/lib/apis/smartcat.js.map +1 -1
- package/lib/apis/smartcat.mjs.map +1 -1
- package/lib/assets/attention.svg +5 -5
- package/lib/assets/attention2.svg +5 -5
- package/lib/assets/udmPro.jpg +0 -0
- package/lib/assets/udmPro2.jpg +0 -0
- package/lib/assets/udmProMax.jpg +0 -0
- package/lib/assets/udmProMax2.jpg +0 -0
- package/lib/assets/udmProSpecial.jpg +0 -0
- package/lib/assets/udmProSpecial2.jpg +0 -0
- package/lib/components/Accordion/Accordion.js.map +1 -1
- package/lib/components/Accordion/Accordion.mjs.map +1 -1
- package/lib/components/Accordion/Accordion.styles.js.map +1 -1
- package/lib/components/Accordion/Accordion.styles.mjs.map +1 -1
- package/lib/components/Avatar/Avatar.js.map +1 -1
- package/lib/components/Avatar/Avatar.mjs.map +1 -1
- package/lib/components/Banner/Banner.styles.js.map +1 -1
- package/lib/components/Banner/Banner.styles.mjs.map +1 -1
- package/lib/components/ButtonGroup/ButtonGroup.js.map +1 -1
- package/lib/components/ButtonGroup/ButtonGroup.mjs.map +1 -1
- package/lib/components/ButtonGroup/ButtonGroup.styles.js.map +1 -1
- package/lib/components/ButtonGroup/ButtonGroup.styles.mjs.map +1 -1
- package/lib/components/ButtonGroupBasic/ButtonGroupBasic.js.map +1 -1
- package/lib/components/ButtonGroupBasic/ButtonGroupBasic.mjs.map +1 -1
- package/lib/components/CloserLookSection/CloserLookSection.js.map +1 -1
- package/lib/components/CloserLookSection/CloserLookSection.mjs.map +1 -1
- package/lib/components/CloserLookSection/CloserLookSection.styles.js.map +1 -1
- package/lib/components/CloserLookSection/CloserLookSection.styles.mjs.map +1 -1
- package/lib/components/Container/Container.styles.js.map +1 -1
- package/lib/components/Container/Container.styles.mjs.map +1 -1
- package/lib/components/CustomImage/CustomImage.js +1 -1
- package/lib/components/CustomImage/CustomImage.js.map +1 -1
- package/lib/components/CustomImage/CustomImage.mjs +1 -1
- package/lib/components/CustomImage/CustomImage.mjs.map +1 -1
- package/lib/components/CustomImage/CustomImage.styles.js.map +1 -1
- package/lib/components/CustomImage/CustomImage.styles.mjs.map +1 -1
- package/lib/components/Explore/Explore.js.map +1 -1
- package/lib/components/Explore/Explore.mjs.map +1 -1
- package/lib/components/Explore/ExploreData.js.map +1 -1
- package/lib/components/Explore/ExploreData.mjs.map +1 -1
- package/lib/components/FeaturesSection_deprecated/FeaturesSection.js.map +1 -1
- package/lib/components/FeaturesSection_deprecated/FeaturesSection.mjs.map +1 -1
- package/lib/components/FeaturesSection_deprecated/FeaturesSection.styles.js.map +1 -1
- package/lib/components/FeaturesSection_deprecated/FeaturesSection.styles.mjs.map +1 -1
- package/lib/components/Footer/Footer.js +1 -1
- package/lib/components/Footer/Footer.js.map +1 -1
- package/lib/components/Footer/Footer.mjs +1 -1
- package/lib/components/Footer/Footer.mjs.map +1 -1
- package/lib/components/Footer/Footer.styles.js.map +1 -1
- package/lib/components/Footer/Footer.styles.mjs.map +1 -1
- package/lib/components/Gallery/Gallery.js.map +1 -1
- package/lib/components/Gallery/Gallery.mjs.map +1 -1
- package/lib/components/Gallery/Gallery.styles.js.map +1 -1
- package/lib/components/Gallery/Gallery.styles.mjs.map +1 -1
- package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.js.map +1 -1
- package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.mjs.map +1 -1
- package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.styles.js.map +1 -1
- package/lib/components/Gallery/GalleryThumbnails/GalleryThumbnails.styles.mjs.map +1 -1
- package/lib/components/GradientButton/GradientButton.styles.js.map +1 -1
- package/lib/components/GradientButton/GradientButton.styles.mjs.map +1 -1
- package/lib/components/GridGallery/GridGallery.js.map +1 -1
- package/lib/components/GridGallery/GridGallery.mjs.map +1 -1
- package/lib/components/Header/AccountFrame/AccountFrame.js.map +1 -1
- package/lib/components/Header/AccountFrame/AccountFrame.mjs.map +1 -1
- package/lib/components/Header/AccountFrame/AccountFrame.styles.js.map +1 -1
- package/lib/components/Header/AccountFrame/AccountFrame.styles.mjs.map +1 -1
- package/lib/components/Header/AccountMenu/megaphone.http.service.js.map +1 -1
- package/lib/components/Header/AccountMenu/megaphone.http.service.mjs.map +1 -1
- package/lib/components/Header/CartModalV2/Item/Item.js.map +1 -1
- package/lib/components/Header/CartModalV2/Item/Item.mjs.map +1 -1
- package/lib/components/Header/Header.styles.js.map +1 -1
- package/lib/components/Header/Header.styles.mjs.map +1 -1
- package/lib/components/Header/LanguageFrame/LanguageFrame.js.map +1 -1
- package/lib/components/Header/LanguageFrame/LanguageFrame.mjs.map +1 -1
- package/lib/components/Header/LanguageFrame/LanguageFrame.styles.js.map +1 -1
- package/lib/components/Header/LanguageFrame/LanguageFrame.styles.mjs.map +1 -1
- package/lib/components/Header/Navigation/Carousel/Carousel.js.map +1 -1
- package/lib/components/Header/Navigation/Carousel/Carousel.mjs.map +1 -1
- package/lib/components/Header/Navigation/MobileMenu/MobileMenu.styles.js.map +1 -1
- package/lib/components/Header/Navigation/MobileMenu/MobileMenu.styles.mjs.map +1 -1
- package/lib/components/Header/ProHeader/ProHeader.js.map +1 -1
- package/lib/components/Header/ProHeader/ProHeader.mjs.map +1 -1
- package/lib/components/Header/ProHeader/ProHeader.styles.js.map +1 -1
- package/lib/components/Header/ProHeader/ProHeader.styles.mjs.map +1 -1
- package/lib/components/Hero/Hero.js.map +1 -1
- package/lib/components/Hero/Hero.mjs.map +1 -1
- package/lib/components/Hero/Hero.styles.js.map +1 -1
- package/lib/components/Hero/Hero.styles.mjs.map +1 -1
- package/lib/components/ImageCarousel/ImageCarousel.styles.js.map +1 -1
- package/lib/components/ImageCarousel/ImageCarousel.styles.mjs.map +1 -1
- package/lib/components/LandingPage/Cards/Card/Card.js.map +1 -1
- package/lib/components/LandingPage/Cards/Card/Card.mjs.map +1 -1
- package/lib/components/LandingPage/Cards/Cards.js.map +1 -1
- package/lib/components/LandingPage/Cards/Cards.mjs.map +1 -1
- package/lib/components/LandingPage/Cards/Cards.styles.js.map +1 -1
- package/lib/components/LandingPage/Cards/Cards.styles.mjs.map +1 -1
- package/lib/components/LandingPage/LandingPage.js.map +1 -1
- package/lib/components/LandingPage/LandingPage.mjs.map +1 -1
- package/lib/components/LandingPagePro/LandingPagePro.js.map +1 -1
- package/lib/components/LandingPagePro/LandingPagePro.mjs.map +1 -1
- package/lib/components/LandingPageSearch/Modal/Modal.js.map +1 -1
- package/lib/components/LandingPageSearch/Modal/Modal.mjs.map +1 -1
- package/lib/components/LandingPageSidebar/LandingPageSidebar.js.map +1 -1
- package/lib/components/LandingPageSidebar/LandingPageSidebar.mjs.map +1 -1
- package/lib/components/LandingPageSidebar/LandingPageSidebar.styles.js.map +1 -1
- package/lib/components/LandingPageSidebar/LandingPageSidebar.styles.mjs.map +1 -1
- package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.helpers.js.map +1 -1
- package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.helpers.mjs.map +1 -1
- package/lib/components/MicrositeExploreCards/MicrositeExploreCards.styles.js.map +1 -1
- package/lib/components/MicrositeExploreCards/MicrositeExploreCards.styles.mjs.map +1 -1
- package/lib/components/MicrositeFeatureList/MicrositeFeatureList.styles.js.map +1 -1
- package/lib/components/MicrositeFeatureList/MicrositeFeatureList.styles.mjs.map +1 -1
- package/lib/components/MicrositeHero/MicrositeHero.js.map +1 -1
- package/lib/components/MicrositeHero/MicrositeHero.mjs.map +1 -1
- package/lib/components/MicrositeHero/MicrositeHero.styles.js.map +1 -1
- package/lib/components/MicrositeHero/MicrositeHero.styles.mjs.map +1 -1
- package/lib/components/MicrositeMediaGrid/MicrositeMediaGrid.styles.js.map +1 -1
- package/lib/components/MicrositeMediaGrid/MicrositeMediaGrid.styles.mjs.map +1 -1
- package/lib/components/MicrositeProductGrid/MicrositeProductGrid.styles.js.map +1 -1
- package/lib/components/MicrositeProductGrid/MicrositeProductGrid.styles.mjs.map +1 -1
- package/lib/components/MicrositeProductLearnMoreBlock/MicrositeProductLearnMoreBlockWrap.js.map +1 -1
- package/lib/components/MicrositeProductLearnMoreBlock/MicrositeProductLearnMoreBlockWrap.mjs.map +1 -1
- package/lib/components/Microsites/MicrositeProductPage.js.map +1 -1
- package/lib/components/Microsites/MicrositeProductPage.mjs.map +1 -1
- package/lib/components/MobileModal/MobileModal.styles.js.map +1 -1
- package/lib/components/MobileModal/MobileModal.styles.mjs.map +1 -1
- package/lib/components/ModelCompareV3/HeaderShadow.js.map +1 -1
- package/lib/components/ModelCompareV3/HeaderShadow.mjs.map +1 -1
- package/lib/components/ModelCompareV3/ModelCompareV3.js.map +1 -1
- package/lib/components/ModelCompareV3/ModelCompareV3.mjs.map +1 -1
- package/lib/components/ModelCompareV3/ModelCompareV3.styles.js.map +1 -1
- package/lib/components/ModelCompareV3/ModelCompareV3.styles.mjs.map +1 -1
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmPro.jpg.js +5 -5
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmPro.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProMax.jpg.js +5 -5
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProMax.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProSpecial.jpg.js +5 -5
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProSpecial.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/udmPro.jpg.js +1 -1
- package/lib/components/ModelCompareV3/assets/Consoles/udmPro.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/udmProMax.jpg.js +1 -1
- package/lib/components/ModelCompareV3/assets/Consoles/udmProMax.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/udmProSpecial.jpg.js +1 -1
- package/lib/components/ModelCompareV3/assets/Consoles/udmProSpecial.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/data/CloudGateways.js +9 -9
- package/lib/components/ModelCompareV3/data/CloudGateways.mjs +6 -6
- package/lib/components/ModelCompareV3/data/products/UispRouter.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/UispRouter.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/UispRouterPro.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/UispRouterPro.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber11.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber11.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber24.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber24.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber24HiDensity.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber24HiDensity.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber2X.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber2X.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber5.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airFiber5.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz16dBi120Sector.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz16dBi120Sector.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz17dBi90Sector.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz17dBi90Sector.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz19dBi120Sector.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz19dBi120Sector.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz20dBi90Sector.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/airMAX5GHz20dBi90Sector.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/baseStationXG.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/baseStationXG.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/buildingBridge.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/buildingBridge.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/buildingBridgeXG.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/buildingBridgeXG.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/e7.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/e7.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/e7Campus.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/e7Campus.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgePointR6.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgePointR6.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgePointR8.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgePointR8.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgePointS16Switch.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgePointS16Switch.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter10x.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter10x.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter12.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter12.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter12p.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter12p.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter4.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter4.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter6Poe.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouter6Poe.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouterInfinity.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouterInfinity.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouterX.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouterX.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouterXSfp.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeRouterXSfp.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch10x.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch10x.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch10xp.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch10xp.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch16xg.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch16xg.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch16xp.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch16xp.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch16xpoe150.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch16xpoe150.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch18x.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch18x.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch24lite.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch24lite.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe-500.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe-500.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch24poe.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch48lite.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch48lite.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch48poe.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeSwitch48poe.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeswitch48poe-750.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeswitch48poe-750.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeswitch5xp.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeswitch5xp.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeswitch8poe.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/edgeswitch8poe.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/fiberInstant.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/fiberInstant.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/fiberNanog.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/fiberNanog.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/ltuExtremeRange.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/ltuExtremeRange.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/ltuLongRange.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/ltuLongRange.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/ltuPro.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/ltuPro.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/nanoStation5AC.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/nanoStation5AC.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/nanoStation5ACLoco.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/nanoStation5ACLoco.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/prismStation5AC.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/prismStation5AC.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/udb.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/udb.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/udbPro.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/udbPro.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/udmPro.js +1 -1
- package/lib/components/ModelCompareV3/data/products/udmPro.mjs +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProMax.js +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProMax.mjs +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProSpecial.js +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProSpecial.mjs +1 -1
- package/lib/components/ModelCompareV3/data/products/uispSwitch.js.map +1 -1
- package/lib/components/ModelCompareV3/data/products/uispSwitch.mjs.map +1 -1
- package/lib/components/Pagination/Pagination.js.map +1 -1
- package/lib/components/Pagination/Pagination.mjs.map +1 -1
- package/lib/components/PriceRangeSlider/PriceRangeSlider.js.map +1 -1
- package/lib/components/PriceRangeSlider/PriceRangeSlider.mjs.map +1 -1
- package/lib/components/ProductCard/ProductCard.js.map +1 -1
- package/lib/components/ProductCard/ProductCard.mjs.map +1 -1
- package/lib/components/ProductCardPopup/ProductCardPopup.js +2 -2
- package/lib/components/ProductCardPopup/ProductCardPopup.js.map +1 -1
- package/lib/components/ProductCardPopup/ProductCardPopup.mjs +2 -2
- package/lib/components/ProductCardPopup/ProductCardPopup.mjs.map +1 -1
- package/lib/components/ProductGrid/ProductGrid.js.map +1 -1
- package/lib/components/ProductGrid/ProductGrid.mjs.map +1 -1
- package/lib/components/ProductSectionTabs/ProductSectionTabs.js.map +1 -1
- package/lib/components/ProductSectionTabs/ProductSectionTabs.mjs.map +1 -1
- package/lib/components/ProductTechSpecs/ProductTechSpecs.styles.js.map +1 -1
- package/lib/components/ProductTechSpecs/ProductTechSpecs.styles.mjs.map +1 -1
- package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.js.map +1 -1
- package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.mjs.map +1 -1
- package/lib/components/RelatedProducts/RelatedProducts.js.map +1 -1
- package/lib/components/RelatedProducts/RelatedProducts.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/HddSlots/HddSlots.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/HddSlots/HddSlots.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.js +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.mjs +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/Layout.styles.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/Layout.styles.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/attention.svg.js +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/attention.svg.mjs +2 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.js +2 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.mjs +2 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/assets/attention.svg.js +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/assets/attention.svg.mjs +2 -2
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerConfigurator.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerConfigurator.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/RecommendedPoeSwitches.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/RecommendedPoeSwitches.mjs.map +1 -1
- package/lib/components/ScrollWrapper/ScrollWrapper.js.map +1 -1
- package/lib/components/ScrollWrapper/ScrollWrapper.mjs.map +1 -1
- package/lib/components/ScrollWrapper/ScrollWrapper.styles.js.map +1 -1
- package/lib/components/ScrollWrapper/ScrollWrapper.styles.mjs.map +1 -1
- package/lib/components/Search/Input/Input.styles.js.map +1 -1
- package/lib/components/Search/Input/Input.styles.mjs.map +1 -1
- package/lib/components/Search/Modal/Modal.js.map +1 -1
- package/lib/components/Search/Modal/Modal.mjs.map +1 -1
- package/lib/components/SkeletonLoader/SkeletonLoaderTable/SkeletonLoaderTable.js.map +1 -1
- package/lib/components/SkeletonLoader/SkeletonLoaderTable/SkeletonLoaderTable.mjs.map +1 -1
- package/lib/components/StorageSliders/StorageSliders.utils.js.map +1 -1
- package/lib/components/StorageSliders/StorageSliders.utils.mjs.map +1 -1
- package/lib/components/StyleableSvgImage/StyleableSvgImage.js.map +1 -1
- package/lib/components/StyleableSvgImage/StyleableSvgImage.mjs.map +1 -1
- package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.js.map +1 -1
- package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.mjs.map +1 -1
- package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.styles.js.map +1 -1
- package/lib/components/VariantSelector/Variant/Compatibility/Compatibility.styles.mjs.map +1 -1
- package/lib/components/VariantSelector/Variant/Variant.js.map +1 -1
- package/lib/components/VariantSelector/Variant/Variant.mjs.map +1 -1
- package/lib/components/VariantSelector/VariantSelector.constants.js.map +1 -1
- package/lib/components/VariantSelector/VariantSelector.constants.mjs.map +1 -1
- package/lib/constants/layout.js.map +1 -1
- package/lib/constants/layout.mjs.map +1 -1
- package/lib/constants/postalCode.js.map +1 -1
- package/lib/constants/postalCode.mjs.map +1 -1
- package/lib/contexts/MenuContext/utils.js.map +1 -1
- package/lib/contexts/MenuContext/utils.mjs.map +1 -1
- package/lib/helpers/product.js.map +1 -1
- package/lib/helpers/product.mjs.map +1 -1
- package/lib/helpers/time.js.map +1 -1
- package/lib/helpers/time.mjs.map +1 -1
- package/lib/hooks/useTranslation.js.map +1 -1
- package/lib/hooks/useTranslation.mjs.map +1 -1
- package/lib/utils/address.js.map +1 -1
- package/lib/utils/address.mjs.map +1 -1
- package/lib/utils/money/allocators/fixedAmount.js.map +1 -1
- package/lib/utils/money/allocators/fixedAmount.mjs.map +1 -1
- package/lib/utils/money/constants.js +3 -3
- package/lib/utils/money/constants.js.map +1 -1
- package/lib/utils/money/constants.mjs +3 -3
- package/lib/utils/money/constants.mjs.map +1 -1
- package/lib/utils/money/format.js +2 -1
- package/lib/utils/money/format.js.map +1 -1
- package/lib/utils/money/format.mjs +2 -1
- package/lib/utils/money/format.mjs.map +1 -1
- package/lib/utils/money/misc.js.map +1 -1
- package/lib/utils/money/misc.mjs.map +1 -1
- package/lib/utils/nextjs/createInlineScript.js.map +1 -1
- package/lib/utils/nextjs/createInlineScript.mjs.map +1 -1
- package/lib/utils/nextjs/index.d.ts +3 -0
- package/lib/utils/nextjs/index.js +5 -0
- package/lib/utils/nextjs/index.js.map +1 -1
- package/lib/utils/nextjs/index.mjs +3 -0
- package/lib/utils/nextjs/index.mjs.map +1 -1
- package/lib/utils/nextjs/patch.d.ts +1 -0
- package/lib/utils/nextjs/patch.js +53 -0
- package/lib/utils/nextjs/patch.js.map +1 -0
- package/lib/utils/nextjs/patch.mjs +41 -0
- package/lib/utils/nextjs/patch.mjs.map +1 -0
- package/lib/utils/nextjs/plugin.d.ts +8 -0
- package/lib/utils/nextjs/plugin.js +36 -0
- package/lib/utils/nextjs/plugin.js.map +1 -0
- package/lib/utils/nextjs/plugin.mjs +34 -0
- package/lib/utils/nextjs/plugin.mjs.map +1 -0
- package/lib/utils/nextjs/ssr/constants.d.ts +8 -0
- package/lib/utils/nextjs/ssr/constants.js +8 -0
- package/lib/utils/nextjs/ssr/constants.js.map +1 -0
- package/lib/utils/nextjs/ssr/constants.mjs +6 -0
- package/lib/utils/nextjs/ssr/constants.mjs.map +1 -0
- package/lib/utils/nextjs/ssr/registry.d.ts +52 -0
- package/lib/utils/nextjs/ssr/registry.js +19 -0
- package/lib/utils/nextjs/ssr/registry.js.map +1 -0
- package/lib/utils/nextjs/ssr/registry.mjs +17 -0
- package/lib/utils/nextjs/ssr/registry.mjs.map +1 -0
- package/lib/utils/nextjs/ssr/style-inject.d.ts +21 -0
- package/lib/utils/nextjs/ssr/style-inject.js +41 -0
- package/lib/utils/nextjs/ssr/style-inject.js.map +1 -0
- package/lib/utils/nextjs/ssr/style-inject.mjs +37 -0
- package/lib/utils/nextjs/ssr/style-inject.mjs.map +1 -0
- package/lib/utils/nextjs/ssr/transform-css-module.d.ts +10 -0
- package/lib/utils/nextjs/ssr/transform-css-module.js +86 -0
- package/lib/utils/nextjs/ssr/transform-css-module.js.map +1 -0
- package/lib/utils/nextjs/ssr/transform-css-module.mjs +58 -0
- package/lib/utils/nextjs/ssr/transform-css-module.mjs.map +1 -0
- package/lib/utils/nextjs/ssr/transform-css-module.test.d.ts +1 -0
- package/lib/utils/nextjs/ssr/types.d.ts +10 -0
- package/lib/utils/nextjs/stringifyForInject.js.map +1 -1
- package/lib/utils/nextjs/stringifyForInject.mjs.map +1 -1
- package/lib/utils/number.js.map +1 -1
- package/lib/utils/number.mjs.map +1 -1
- package/lib/utils/tax/brazil.js.map +1 -1
- package/lib/utils/tax/brazil.mjs.map +1 -1
- package/lib/utils/wattage.js.map +1 -1
- package/lib/utils/wattage.mjs.map +1 -1
- package/package.json +3 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"address.mjs","sources":["../../src/utils/address.ts"],"sourcesContent":["import type { ZodErrorMap } from \"zod\";\nimport { z } from \"zod\";\n\nimport { AddressType, AddressUsageType, CountryCode } from \"../types\";\nimport type { Country } from \"./countriesAndZones\";\nimport { address2SuperRefinement } from \"./validations/address2SuperRefinement\";\nimport { businessNameSuperRefinement } from \"./validations/businessNameSuperRefinement\";\nimport {\n createLastNameSuperRefinement,\n FIRST_NAME_MAX_LENGTH,\n UPS_SHIPPING_LABEL_MAX_FULL_NAME,\n} from \"./validations/lastNameSuperRefinement\";\nimport { neighborhoodSuperRefinement } from \"./validations/neighborhoodSuperRefinement\";\nimport { phoneNumberSuperRefinement } from \"./validations/phoneNumberSuperRefinement\";\nimport { postalCodeSuperRefinement } from \"./validations/postalCodeSuperRefinement\";\nimport { getProvinceSuperRefinement } from \"./validations/provinceSuperRefinement\";\nimport { createStateRegistrationNumberSuperRefinement } from \"./validations/stateRegistrationNumberSuperRefinement\";\nimport { createTaxIdSuperRefinement } from \"./validations/taxIdSuperRefinement\";\nimport type { ValidateTaxIdExternally } from \"./validations/taxIdSuperRefinement\";\n\nexport type BaseAddressSchemaArgs = {\n countries: Country[];\n errorMap?: ZodErrorMap;\n addressUsageType?: AddressUsageType;\n};\n\nexport type AddressSchemaArgs = BaseAddressSchemaArgs & {\n validateTaxIdExternally?: ValidateTaxIdExternally;\n};\n\nconst COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER = new Set([\n CountryCode.Br,\n]);\n\nconst COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE = new Map<\n CountryCode,\n Array<keyof z.infer<ReturnType<typeof getAddressSchema>>>\n>([\n [\n CountryCode.Br,\n [\"stateRegistrationNumber\", \"neighborhood\", \"additionalInfo\"],\n ],\n]);\n\n/**\n * If it returns `true`, the `address1` field will be used for the street name\n * and `address2` field will be used for the house/apartment number.\n */\nexport const shouldAddressHaveSeparatedStreetAndHouseNumber = (\n country: CountryCode,\n) => COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER.has(country);\n\n/**\n * Returns address form field paths for country-specific fields.\n */\nexport const getCountrySpecificAddressFormFields = <TPathPrefix extends string>(\n country: CountryCode,\n { pathPrefix }: { pathPrefix: TPathPrefix },\n) => {\n const fields = COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE.get(country);\n\n if (!fields) {\n return [];\n }\n\n return fields.map((field) => `${pathPrefix}${field}` as const);\n};\n\nconst DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE = AddressUsageType.Shipping;\n// #############################################################################\n// Base Address Schema\n// #############################################################################\nexport const getBaseAddressSchema = ({\n countries,\n errorMap,\n}: BaseAddressSchemaArgs) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n return schema\n .object({\n // UPS limits address to 35\n address1: z.string().trim().min(1).max(35),\n // UPS limits address to 35\n address2: z.string().trim().max(35).nullish(),\n // UPS limits city name to 30\n city: z.string().trim().min(1).max(30),\n province: z.string().trim().nullish(),\n country: z.nativeEnum(CountryCode),\n postalCode: z.string().trim().max(255).nullish(),\n neighborhood: z.string().trim().max(255).nullish(),\n })\n .superRefine(getProvinceSuperRefinement(countries))\n .superRefine(postalCodeSuperRefinement)\n .superRefine(neighborhoodSuperRefinement)\n .superRefine(address2SuperRefinement);\n};\n\n// #############################################################################\n// Address Schema\n// #############################################################################\nexport const getAddressSchema = ({\n countries,\n validateTaxIdExternally,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: AddressSchemaArgs) => {\n return z\n .object({\n type: z.nativeEnum(AddressType),\n businessName: z.string().trim().max(255).nullish(),\n /**\n * @deprecated Use `taxId` instead (currently backwards supported with `taxId ?? businessVatId`)\n */\n businessVatId: z.string().trim().max(255).nullish(),\n taxId: z.string().trim().max(255).nullish(),\n firstName: z.string().trim().min(1).max(FIRST_NAME_MAX_LENGTH),\n lastName: z.string().trim().min(1).max(UPS_SHIPPING_LABEL_MAX_FULL_NAME),\n phoneNumber: z.string().trim().min(1).max(255),\n stateRegistrationNumber: z.string().trim().max(255).nullish(),\n additionalInfo: z.string().trim().max(255).nullish(),\n })\n .and(getBaseAddressSchema({ countries, errorMap, addressUsageType }))\n .superRefine(phoneNumberSuperRefinement)\n .superRefine(businessNameSuperRefinement)\n .superRefine(\n createTaxIdSuperRefinement({ addressUsageType, validateTaxIdExternally }),\n )\n .superRefine(\n createStateRegistrationNumberSuperRefinement({ addressUsageType }),\n )\n .superRefine(createLastNameSuperRefinement);\n};\n\n// #############################################################################\n// Create Customer Address Schema\n// #############################################################################\nexport const getCreateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n isDefault: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Update Customer Address Schema\n// #############################################################################\nexport const getUpdateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n id: z.string().trim().uuid().nullish(),\n })\n .and(getCreateCustomerAddressSchema(args));\n};\n\n// #############################################################################\n// Update Order Address Schema\n// #############################################################################\nexport const getUpdateOrderAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n customerAddressId: z.string().trim().uuid().nullish(),\n saveForFutureUse: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Address Fields uniform validation\n// #############################################################################\n/**\n * Need to use this schema for uniform validation of address fields in SF\n */\nexport const getAddressFieldsSchema = (args: AddressSchemaArgs) => {\n return getUpdateCustomerAddressSchema(args).and(\n getUpdateOrderAddressSchema(args),\n );\n};\n\n// #############################################################################\n// Email and Accepts marketing validation\n// #############################################################################\n/**\n * Stored as a separate schema because of schema differences in BE and SF.\n * @param {boolean} nullish !!! Use with caution since it is only meant for BE where fields can be optional\n * @see https://github.com/colinhacks/zod/issues/2281#issuecomment-1492082268\n */\n\nexport const getEmailAndMarketingSchema = <Nullish extends boolean = false>(\n {\n errorMap,\n nullish,\n }: {\n errorMap?: ZodErrorMap;\n nullish?: Nullish;\n } = {\n nullish: false as Nullish,\n },\n) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n const email = (\n nullish ? z.string().email().nullish() : z.string().email()\n ) as Nullish extends true\n ? z.ZodOptional<z.ZodNullable<z.ZodString>>\n : z.ZodString;\n\n const acceptsMarketing = (\n nullish ? z.boolean().optional() : z.boolean()\n ) as Nullish extends true ? z.ZodOptional<z.ZodBoolean> : z.ZodBoolean;\n\n return schema.object({\n email,\n acceptsMarketing,\n });\n};\n"],"names":["COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER","Set","CountryCode","Br","COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE","Map","shouldAddressHaveSeparatedStreetAndHouseNumber","country","has","getCountrySpecificAddressFormFields","pathPrefix","fields","get","map","field","DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE","AddressUsageType","Shipping","getBaseAddressSchema","countries","errorMap","schema","z","setErrorMap","object","address1","string","trim","min","max","address2","nullish","city","province","nativeEnum","postalCode","neighborhood","superRefine","getProvinceSuperRefinement","postalCodeSuperRefinement","neighborhoodSuperRefinement","address2SuperRefinement","getAddressSchema","validateTaxIdExternally","addressUsageType","type","AddressType","businessName","businessVatId","taxId","firstName","FIRST_NAME_MAX_LENGTH","lastName","UPS_SHIPPING_LABEL_MAX_FULL_NAME","phoneNumber","stateRegistrationNumber","additionalInfo","and","phoneNumberSuperRefinement","businessNameSuperRefinement","createTaxIdSuperRefinement","createStateRegistrationNumberSuperRefinement","createLastNameSuperRefinement","getCreateCustomerAddressSchema","args","isDefault","boolean","getUpdateCustomerAddressSchema","id","uuid","getUpdateOrderAddressSchema","customerAddressId","saveForFutureUse","getAddressFieldsSchema","getEmailAndMarketingSchema","email","acceptsMarketing","optional"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAMA,gDAAA,GAAA,mBAAuDC,GAAI,CAAA,CAC/DC,WAAY,CAAAC,EAAA,CACb,CAAA;AAED,MAAMC,+CAAA,GAAA,mBAAsDC,GAG1D,CAAA,CACA,CACEH,WAAY,CAAAC,EAAA,EACZ,CAAC,yBAA2B,EAAA,cAAA,EAAgB,gBAAgB,CAAA,CAC9D,CACD,CAAA;AAMM,MAAMG,8CAAiD,GAC5DC,OACG,IAAAP,gDAAA,CAAiDQ,IAAID,OAAO,CAAA;AAK1D,MAAME,mCAAsC,GAAAA,CACjDF,OACA,EAAA;EAAEG;CACC,KAAA;EACG,MAAAC,MAAA,GAASP,+CAAgD,CAAAQ,GAAA,CAAIL,OAAO,CAAA;EAE1E,IAAI,CAACI,MAAQ,EAAA;IACX,OAAO,EAAC;EACV;EAEO,OAAAA,MAAA,CAAOE,IAAKC,KAAA,OAAaJ,UAAU,GAAGI,KAAgB,EAAA,CAAA;AAC/D,CAAA;AAEA,MAAMC,wCAAwCC,gBAAiB,CAAAC,QAAA;AAIxD,MAAMC,uBAAuBA,CAAC;EACnCC,SAAA;EACAC;AACF,CAA6B,KAAA;EAC3B,MAAMC,MAAS,GAAAC,CAAA;EAEf,IAAIF,QAAU,EAAA;IACZC,MAAA,CAAOE,YAAYH,QAAQ,CAAA;EAC7B;EAEA,OAAOC,OACJG,MAAO,CAAA;IAAA;IAENC,QAAA,EAAUH,CAAE,CAAAI,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AAQ,CAAA;EAC7B;EAEA,MAAMuD,KACJ,GAAA5C,OAAA,GAAUT,CAAE,CAAAI,MAAA,CAAA,CAAS,CAAAiD,KAAA,EAAQ,CAAA5C,OAAA,CAAY,CAAA,GAAAT,CAAA,CAAEI,MAAO,CAAA,CAAA,CAAEiD,KAAM,CAAA,CAAA;EAKtD,MAAAC,gBAAA,GACJ7C,UAAUT,CAAE,CAAA4C,OAAA,GAAUW,QAAS,CAAA,CAAA,GAAIvD,EAAE4C,OAAQ,EAAA;EAG/C,OAAO7C,OAAOG,MAAO,CAAA;IACnBmD,KAAA;IACAC;EAAA,CACD,CAAA;AACH,CAAA;"}
|
|
1
|
+
{"version":3,"file":"address.mjs","sources":["../../src/utils/address.ts"],"sourcesContent":["import type { ZodErrorMap } from \"zod\";\nimport { z } from \"zod\";\n\nimport { AddressType, AddressUsageType, CountryCode } from \"../types\";\nimport type { Country } from \"./countriesAndZones\";\nimport { address2SuperRefinement } from \"./validations/address2SuperRefinement\";\nimport { businessNameSuperRefinement } from \"./validations/businessNameSuperRefinement\";\nimport {\n createLastNameSuperRefinement,\n FIRST_NAME_MAX_LENGTH,\n UPS_SHIPPING_LABEL_MAX_FULL_NAME,\n} from \"./validations/lastNameSuperRefinement\";\nimport { neighborhoodSuperRefinement } from \"./validations/neighborhoodSuperRefinement\";\nimport { phoneNumberSuperRefinement } from \"./validations/phoneNumberSuperRefinement\";\nimport { postalCodeSuperRefinement } from \"./validations/postalCodeSuperRefinement\";\nimport { getProvinceSuperRefinement } from \"./validations/provinceSuperRefinement\";\nimport { createStateRegistrationNumberSuperRefinement } from \"./validations/stateRegistrationNumberSuperRefinement\";\nimport { createTaxIdSuperRefinement } from \"./validations/taxIdSuperRefinement\";\nimport type { ValidateTaxIdExternally } from \"./validations/taxIdSuperRefinement\";\n\nexport type BaseAddressSchemaArgs = {\n countries: Country[];\n errorMap?: ZodErrorMap;\n addressUsageType?: AddressUsageType;\n};\n\nexport type AddressSchemaArgs = BaseAddressSchemaArgs & {\n validateTaxIdExternally?: ValidateTaxIdExternally;\n};\n\nconst COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER = new Set([\n CountryCode.Br,\n]);\n\nconst COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE = new Map<\n CountryCode,\n Array<keyof z.infer<ReturnType<typeof getAddressSchema>>>\n>([\n [\n CountryCode.Br,\n [\"stateRegistrationNumber\", \"neighborhood\", \"additionalInfo\"],\n ],\n]);\n\n/**\n * If it returns `true`, the `address1` field will be used for the street name\n * and `address2` field will be used for the house/apartment number.\n */\nexport const shouldAddressHaveSeparatedStreetAndHouseNumber = (\n country: CountryCode,\n) => COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER.has(country);\n\n/**\n * Returns address form field paths for country-specific fields.\n */\nexport const getCountrySpecificAddressFormFields = <TPathPrefix extends string>(\n country: CountryCode,\n { pathPrefix }: { pathPrefix: TPathPrefix },\n) => {\n const fields = COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE.get(country);\n\n if (!fields) {\n return [];\n }\n\n return fields.map((field) => `${pathPrefix}${field}` as const);\n};\n\nconst DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE = AddressUsageType.Shipping;\n// #############################################################################\n// Base Address Schema\n// #############################################################################\nexport const getBaseAddressSchema = ({\n countries,\n errorMap,\n}: BaseAddressSchemaArgs) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n return schema\n .object({\n // UPS limits address to 35\n address1: z.string().trim().min(1).max(35),\n // UPS limits address to 35\n address2: z.string().trim().max(35).nullish(),\n // UPS limits city name to 30\n city: z.string().trim().min(1).max(30),\n province: z.string().trim().nullish(),\n country: z.nativeEnum(CountryCode),\n postalCode: z.string().trim().max(255).nullish(),\n neighborhood: z.string().trim().max(255).nullish(),\n })\n .superRefine(getProvinceSuperRefinement(countries))\n .superRefine(postalCodeSuperRefinement)\n .superRefine(neighborhoodSuperRefinement)\n .superRefine(address2SuperRefinement);\n};\n\n// #############################################################################\n// Address Schema\n// #############################################################################\nexport const getAddressSchema = ({\n countries,\n validateTaxIdExternally,\n errorMap,\n addressUsageType = DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE,\n}: AddressSchemaArgs) => {\n return z\n .object({\n type: z.nativeEnum(AddressType),\n businessName: z.string().trim().max(255).nullish(),\n /**\n * @deprecated Use `taxId` instead (currently backwards supported with `taxId ?? businessVatId`)\n */\n businessVatId: z.string().trim().max(255).nullish(),\n taxId: z.string().trim().max(255).nullish(),\n firstName: z.string().trim().min(1).max(FIRST_NAME_MAX_LENGTH),\n lastName: z.string().trim().min(1).max(UPS_SHIPPING_LABEL_MAX_FULL_NAME),\n phoneNumber: z.string().trim().min(1).max(255),\n stateRegistrationNumber: z.string().trim().max(255).nullish(),\n additionalInfo: z.string().trim().max(255).nullish(),\n })\n .and(getBaseAddressSchema({ countries, errorMap, addressUsageType }))\n .superRefine(phoneNumberSuperRefinement)\n .superRefine(businessNameSuperRefinement)\n .superRefine(\n createTaxIdSuperRefinement({ addressUsageType, validateTaxIdExternally }),\n )\n .superRefine(\n createStateRegistrationNumberSuperRefinement({ addressUsageType }),\n )\n .superRefine(createLastNameSuperRefinement);\n};\n\n// #############################################################################\n// Create Customer Address Schema\n// #############################################################################\nexport const getCreateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n isDefault: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Update Customer Address Schema\n// #############################################################################\nexport const getUpdateCustomerAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n id: z.string().trim().uuid().nullish(),\n })\n .and(getCreateCustomerAddressSchema(args));\n};\n\n// #############################################################################\n// Update Order Address Schema\n// #############################################################################\nexport const getUpdateOrderAddressSchema = (args: AddressSchemaArgs) => {\n return z\n .object({\n customerAddressId: z.string().trim().uuid().nullish(),\n saveForFutureUse: z.boolean().nullish(),\n })\n .and(getAddressSchema(args));\n};\n\n// #############################################################################\n// Address Fields uniform validation\n// #############################################################################\n/**\n * Need to use this schema for uniform validation of address fields in SF\n */\nexport const getAddressFieldsSchema = (args: AddressSchemaArgs) => {\n return getUpdateCustomerAddressSchema(args).and(\n getUpdateOrderAddressSchema(args),\n );\n};\n\n// #############################################################################\n// Email and Accepts marketing validation\n// #############################################################################\n/**\n * Stored as a separate schema because of schema differences in BE and SF.\n * @param {boolean} nullish !!! Use with caution since it is only meant for BE where fields can be optional\n * @see https://github.com/colinhacks/zod/issues/2281#issuecomment-1492082268\n */\n\nexport const getEmailAndMarketingSchema = <Nullish extends boolean = false>(\n {\n errorMap,\n nullish,\n }: {\n errorMap?: ZodErrorMap;\n nullish?: Nullish;\n } = {\n nullish: false as Nullish,\n },\n) => {\n const schema = z;\n\n if (errorMap) {\n schema.setErrorMap(errorMap);\n }\n\n const email = (\n nullish ? z.string().email().nullish() : z.string().email()\n ) as Nullish extends true\n ? z.ZodOptional<z.ZodNullable<z.ZodString>>\n : z.ZodString;\n\n const acceptsMarketing = (\n nullish ? z.boolean().optional() : z.boolean()\n ) as Nullish extends true ? z.ZodOptional<z.ZodBoolean> : z.ZodBoolean;\n\n return schema.object({\n email,\n acceptsMarketing,\n });\n};\n"],"names":["COUNTRIES_WITH_SEPARATED_STREET_AND_HOUSE_NUMBER","Set","CountryCode","Br","COUNTRY_SPECIFIC_ADDRESS_FIELDS_BY_COUNTRY_CODE","Map","shouldAddressHaveSeparatedStreetAndHouseNumber","country","has","getCountrySpecificAddressFormFields","pathPrefix","fields","get","map","field","DEFAULT_ADDRESS_VALIDATION_USAGE_TYPE","AddressUsageType","Shipping","getBaseAddressSchema","countries","errorMap","schema","z","setErrorMap","object","address1","string","trim","min","max","address2","nullish","city","province","nativeEnum","postalCode","neighborhood","superRefine","getProvinceSuperRefinement","postalCodeSuperRefinement","neighborhoodSuperRefinement","address2SuperRefinement","getAddressSchema","validateTaxIdExternally","addressUsageType","type","AddressType","businessName","businessVatId","taxId","firstName","FIRST_NAME_MAX_LENGTH","lastName","UPS_SHIPPING_LABEL_MAX_FULL_NAME","phoneNumber","stateRegistrationNumber","additionalInfo","and","phoneNumberSuperRefinement","businessNameSuperRefinement","createTaxIdSuperRefinement","createStateRegistrationNumberSuperRefinement","createLastNameSuperRefinement","getCreateCustomerAddressSchema","args","isDefault","boolean","getUpdateCustomerAddressSchema","id","uuid","getUpdateOrderAddressSchema","customerAddressId","saveForFutureUse","getAddressFieldsSchema","getEmailAndMarketingSchema","email","acceptsMarketing","optional"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAMA,gDAAA,GAAA,mBAAuDC,GAAI,CAAA,CAC/DC,WAAY,CAAAC,EAAA,CACb,CAAA;AAED,MAAMC,+CAAA,GAAA,mBAAsDC,GAG1D,CAAA,CACA,CACEH,WAAY,CAAAC,EAAA,EACZ,CAAC,yBAA2B,EAAA,cAAA,EAAgB,gBAAgB,CAAA,CAC9D,CACD,CAAA;AAMM,MAAMG,8CAAiD,GAC5DC,OACG,IAAAP,gDAAA,CAAiDQ,IAAID,OAAO,CAAA;AAK1D,MAAME,mCAAsC,GAAAA,CACjDF,OACA,EAAA;EAAEG;CACC,KAAA;EACG,MAAAC,MAAA,GAASP,+CAAgD,CAAAQ,GAAA,CAAIL,OAAO,CAAA;EAE1E,IAAI,CAACI,MAAQ,EAAA;IACX,OAAO,EAAC;EACV;EAEO,OAAAA,MAAA,CAAOE,IAAKC,KAAA,IAAU,GAAGJ,UAAU,GAAGI,KAAK,EAAW,CAAA;AAC/D,CAAA;AAEA,MAAMC,wCAAwCC,gBAAiB,CAAAC,QAAA;AAIxD,MAAMC,uBAAuBA,CAAC;EACnCC,SAAA;EACAC;AACF,CAA6B,KAAA;EAC3B,MAAMC,MAAS,GAAAC,CAAA;EAEf,IAAIF,QAAU,EAAA;IACZC,MAAA,CAAOE,YAAYH,QAAQ,CAAA;EAC7B;EAEA,OAAOC,OACJG,MAAO,CAAA;IAAA;IAENC,QAAA,EAAUH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AAOE,YAAYH,QAAQ,CAAA;EAC7B;EAEA,MAAMuD,KACJ,GAAA5C,OAAA,GAAUT,CAAE,CAAAI,MAAA,CAAA,CAAS,CAAAiD,KAAA,EAAQ,CAAA5C,OAAA,CAAY,CAAA,GAAAT,CAAA,CAAEI,MAAO,CAAA,CAAA,CAAEiD,KAAM,CAAA,CAAA;EAKtD,MAAAC,gBAAA,GACJ7C,UAAUT,CAAE,CAAA4C,OAAA,GAAUW,QAAS,CAAA,CAAA,GAAIvD,EAAE4C,OAAQ,EAAA;EAG/C,OAAO7C,OAAOG,MAAO,CAAA;IACnBmD,KAAA;IACAC;EAAA,CACD,CAAA;AACH,CAAA;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fixedAmount.js","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IACAC;EAAA,CAKC,EAAA;IAfH;AAAA;AAAA;IAAOC,aAAA,CAAA,IAAA,EAAA,2BAAA,CAAA;IAIP;AAAA;AAAA;IAAOA,aAAA,CAAA,IAAA,EAAA,sBAAA,CAAA;IACAA,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA;IAWA,IAAA,CAAAC,yBAAA,GAA4BC,IAAAA,CAAAA,SAAU,CAAAL,qBAAA,EAAuBE,QAAQ,CAAA;IACrE,IAAA,CAAAI,oBAAA,GAAuBD,IAAAA,CAAAA,SAAU,CAAAJ,kBAAA,EAAoBC,QAAQ,CAAA;IAC7D,IAAA,CAAAA,QAAA,GAAWK,uBAAkBL,QAAQ,CAAA;EAC5C;EAAA;AAAA;AAAA;EAKAM,QAAAA,CAASC,eAAsBP,QAA0B,EAAA;IACvDQ,MAAA,CAAAA,MAAA,CACE,IAAA,CAAKR,SAASS,IAAS,KAAAT,QAAA,
|
|
1
|
+
{"version":3,"file":"fixedAmount.js","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IACAC;EAAA,CAKC,EAAA;IAfH;AAAA;AAAA;IAAOC,aAAA,CAAA,IAAA,EAAA,2BAAA,CAAA;IAIP;AAAA;AAAA;IAAOA,aAAA,CAAA,IAAA,EAAA,sBAAA,CAAA;IACAA,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA;IAWA,IAAA,CAAAC,yBAAA,GAA4BC,IAAAA,CAAAA,SAAU,CAAAL,qBAAA,EAAuBE,QAAQ,CAAA;IACrE,IAAA,CAAAI,oBAAA,GAAuBD,IAAAA,CAAAA,SAAU,CAAAJ,kBAAA,EAAoBC,QAAQ,CAAA;IAC7D,IAAA,CAAAA,QAAA,GAAWK,uBAAkBL,QAAQ,CAAA;EAC5C;EAAA;AAAA;AAAA;EAKAM,QAAAA,CAASC,eAAsBP,QAA0B,EAAA;IACvDQ,MAAA,CAAAA,MAAA,CACE,IAAA,CAAKR,SAASS,IAAS,KAAAT,QAAA,EACvB,+BAA+BA,QAAQ,SAAS,IAAA,CAAKA,SAASS,IAAI,EAAA,CACpE;IACM,MAAAC,mBAAA,GAAsBP,IAAAA,CAAAA,SAAU,CAAAI,aAAA,EAAeP,QAAQ,CAAA;IAK7D,IAAIO,kBAAkB,CAAG,EAAA;MAChB,OAAAG,mBAAA;IACT;IAEM,MAAA,CAACC,gBAAkB,EAAAT,yBAAyB,CAAI,GAAAI,SAAA,CAAAA,QAAA,CACpD,IAAK,CAAAJ,yBAAA,EACL,CACEK,aAAA,EACAK,KAAKC,GAAI,CAAAC,WAAA,CAAO,KAAKV,oBAAoB,CAAA,GAAIG,eAAe,CAAC,CAAA,CAC/D,CACF;IAEOC,MAAAA,CAAAA,MAAA,CAAA,CAAC,CAACG,gBAAA,EAAkB,2BAA2B,CAAA;IACtDH,MAAA,CAAAA,MAAA,CACE,CAAC,CAACN,yBAAA,EACF,wCAAA,CACF;IAEA,IAAA,CAAKA,yBAA4B,GAAAA,yBAAA;IACjC,IAAA,CAAKE,oBAAuB,GAAAW,SAAA,CAAAA,QAAA,CAC1B,IAAK,CAAAX,oBAAA,EACLM,mBAAA,CACF;IAMA,OAAOM,SAAY,CAAAA,WAAA,CAAAL,gBAAA,EAAkBD,mBAAmB,CAAA,GACpDA,mBACA,GAAAC,gBAAA;EACN;AACF;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fixedAmount.mjs","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IACAC;EAAA,CAKC,EAAA;IAfH;AAAA;AAAA;IAAOC,aAAA,CAAA,IAAA,EAAA,2BAAA,CAAA;IAIP;AAAA;AAAA;IAAOA,aAAA,CAAA,IAAA,EAAA,sBAAA,CAAA;IACAA,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA;IAWA,IAAA,CAAAC,yBAAA,GAA4BC,SAAU,CAAAL,qBAAA,EAAuBE,QAAQ,CAAA;IACrE,IAAA,CAAAI,oBAAA,GAAuBD,SAAU,CAAAJ,kBAAA,EAAoBC,QAAQ,CAAA;IAC7D,IAAA,CAAAA,QAAA,GAAWK,kBAAkBL,QAAQ,CAAA;EAC5C;EAAA;AAAA;AAAA;EAKAM,QAAAA,CAASC,eAAsBP,QAA0B,EAAA;IACvDQ,MAAA,CACE,IAAA,CAAKR,SAASS,IAAS,KAAAT,QAAA,
|
|
1
|
+
{"version":3,"file":"fixedAmount.mjs","sources":["../../../../src/utils/money/allocators/fixedAmount.ts"],"sourcesContent":["import { allocate, greaterThan, subtract } from \"dinero.js\";\n\nimport type { Currency } from \"../../../types\";\nimport { assert } from \"../../errors\";\nimport { amount, getDinero, getDineroCurrency } from \"../misc\";\nimport type { Cents, Dino, DinoCurrency } from \"../types\";\n\n/**\n * Helper class to distribute a fixed amount (e.g. discount) between multiple items.\n * For example when trying to apply 5$ discount to 3 items, we need to distribute it evenly as possible\n */\nexport class FixedAmountAllocator {\n /**\n * How much we have left to allocate for given allocation from the remaining total\n */\n public remainingAllocationAmount: Dino;\n /**\n * How much we have left to allocate in total\n */\n public remainingTotalAmount: Dino;\n public currency: DinoCurrency;\n\n constructor({\n initialAllocateAmount,\n initialTotalAmount,\n currency,\n }: {\n initialAllocateAmount: Cents;\n initialTotalAmount: Cents;\n currency: Currency;\n }) {\n this.remainingAllocationAmount = getDinero(initialAllocateAmount, currency);\n this.remainingTotalAmount = getDinero(initialTotalAmount, currency);\n this.currency = getDineroCurrency(currency);\n }\n\n /**\n * We always allocate biggest share to first item\n */\n allocate(lineItemTotal: Cents, currency: Currency): Dino {\n assert(\n this.currency.code === currency,\n `Currency mismatch, expected ${currency}, got ${this.currency.code}`,\n );\n const lineItemTotalDinero = getDinero(lineItemTotal, currency);\n /**\n * If total price of line items is zero, it means it's free, thus no discount\n * can be calculated (it's either 0 or infinity, but let's go with 0)\n */\n if (lineItemTotal === 0) {\n return lineItemTotalDinero;\n }\n\n const [allocationAmount, remainingAllocationAmount] = allocate(\n this.remainingAllocationAmount,\n [\n lineItemTotal,\n Math.max(amount(this.remainingTotalAmount) - lineItemTotal, 0),\n ],\n );\n\n assert(!!allocationAmount, \"Allocation amount is zero\");\n assert(\n !!remainingAllocationAmount,\n \"Remaining allocation remainder is zero\",\n );\n\n this.remainingAllocationAmount = remainingAllocationAmount;\n this.remainingTotalAmount = subtract(\n this.remainingTotalAmount,\n lineItemTotalDinero,\n );\n\n /**\n * The discount amount is evenly split but can still be higher than the line item total\n * Need to ceil the price to be not more than the line item total\n */\n return greaterThan(allocationAmount, lineItemTotalDinero)\n ? lineItemTotalDinero\n : allocationAmount;\n }\n}\n"],"names":["FixedAmountAllocator","constructor","initialAllocateAmount","initialTotalAmount","currency","__publicField","remainingAllocationAmount","getDinero","remainingTotalAmount","getDineroCurrency","allocate","lineItemTotal","assert","code","lineItemTotalDinero","allocationAmount","Math","max","amount","subtract","greaterThan"],"mappings":";;;;;;;;;;;;AAWO,MAAMA,oBAAqB,CAAA;EAWhCC,WAAYA,CAAA;IACVC,qBAAA;IACAC,kBAAA;IACAC;EAAA,CAKC,EAAA;IAfH;AAAA;AAAA;IAAOC,aAAA,CAAA,IAAA,EAAA,2BAAA,CAAA;IAIP;AAAA;AAAA;IAAOA,aAAA,CAAA,IAAA,EAAA,sBAAA,CAAA;IACAA,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA;IAWA,IAAA,CAAAC,yBAAA,GAA4BC,SAAU,CAAAL,qBAAA,EAAuBE,QAAQ,CAAA;IACrE,IAAA,CAAAI,oBAAA,GAAuBD,SAAU,CAAAJ,kBAAA,EAAoBC,QAAQ,CAAA;IAC7D,IAAA,CAAAA,QAAA,GAAWK,kBAAkBL,QAAQ,CAAA;EAC5C;EAAA;AAAA;AAAA;EAKAM,QAAAA,CAASC,eAAsBP,QAA0B,EAAA;IACvDQ,MAAA,CACE,IAAA,CAAKR,SAASS,IAAS,KAAAT,QAAA,EACvB,+BAA+BA,QAAQ,SAAS,IAAA,CAAKA,SAASS,IAAI,EAAA,CACpE;IACM,MAAAC,mBAAA,GAAsBP,SAAU,CAAAI,aAAA,EAAeP,QAAQ,CAAA;IAK7D,IAAIO,kBAAkB,CAAG,EAAA;MAChB,OAAAG,mBAAA;IACT;IAEM,MAAA,CAACC,gBAAkB,EAAAT,yBAAyB,CAAI,GAAAI,QAAA,CACpD,IAAK,CAAAJ,yBAAA,EACL,CACEK,aAAA,EACAK,KAAKC,GAAI,CAAAC,MAAA,CAAO,KAAKV,oBAAoB,CAAA,GAAIG,eAAe,CAAC,CAAA,CAC/D,CACF;IAEOC,MAAA,CAAA,CAAC,CAACG,gBAAA,EAAkB,2BAA2B,CAAA;IACtDH,MAAA,CACE,CAAC,CAACN,yBAAA,EACF,wCAAA,CACF;IAEA,IAAA,CAAKA,yBAA4B,GAAAA,yBAAA;IACjC,IAAA,CAAKE,oBAAuB,GAAAW,QAAA,CAC1B,IAAK,CAAAX,oBAAA,EACLM,mBAAA,CACF;IAMA,OAAOM,WAAY,CAAAL,gBAAA,EAAkBD,mBAAmB,CAAA,GACpDA,mBACA,GAAAC,gBAAA;EACN;AACF;"}
|
|
@@ -9,7 +9,7 @@ const roundToNearestFull059 = input => {
|
|
|
9
9
|
if (input === 0) {
|
|
10
10
|
return 0;
|
|
11
11
|
}
|
|
12
|
-
if (input <=
|
|
12
|
+
if (input <= 5) {
|
|
13
13
|
return 5;
|
|
14
14
|
}
|
|
15
15
|
const roundedNumber = Math.round(input);
|
|
@@ -26,7 +26,7 @@ const roundToNearestDecimalCent = input => {
|
|
|
26
26
|
if (input === 0) {
|
|
27
27
|
return 0;
|
|
28
28
|
}
|
|
29
|
-
if (input
|
|
29
|
+
if (input <= 0.1) {
|
|
30
30
|
return 0.1;
|
|
31
31
|
}
|
|
32
32
|
return parseFloat((Math.round(input * 10) / 10).toFixed(1));
|
|
@@ -35,7 +35,7 @@ const roundToNearestHalfUnitCent = input => {
|
|
|
35
35
|
if (input === 0) {
|
|
36
36
|
return 0;
|
|
37
37
|
}
|
|
38
|
-
if (input
|
|
38
|
+
if (input <= 0.5) {
|
|
39
39
|
return 0.5;
|
|
40
40
|
}
|
|
41
41
|
return parseFloat((Math.round(input * 2) / 2).toFixed(2));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sources":["../../../src/utils/money/constants.ts"],"sourcesContent":["import {\n AED,\n BGN,\n BRL,\n CAD,\n CHF,\n CZK,\n DKK,\n EUR,\n GBP,\n HRK,\n HUF,\n INR,\n JPY,\n MXN,\n NOK,\n PHP,\n PLN,\n RON,\n SEK,\n SGD,\n TWD,\n USD,\n ZAR,\n} from \"@dinero.js/currencies\";\nimport { down, halfAwayFromZero, halfUp } from \"dinero.js\";\n\nimport type { StoreId } from \"../../types\";\nimport { Currency } from \"../../types\";\nimport type {\n Cents,\n DinoCurrency,\n LocalizedCurrency,\n RoundingFn,\n} from \"./types\";\n\n// #############################################################################\n// Constants\n// #############################################################################\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to nearest FULL 0/5/9 (and strip cents)\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestFull059: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-3.00\n if (input <= 3) {\n return 5;\n }\n\n /**\n * Input comes as float, for this rounding we don't need cents, so round\n * to nearest full number\n */\n const roundedNumber = Math.round(input);\n\n // Determine nearest rounding value\n const remainder = roundedNumber % 10;\n if (remainder <= 2) {\n // Round down to nearest 0\n return roundedNumber - remainder;\n } else if (remainder <= 7) {\n // Round to nearest 5\n return roundedNumber - remainder + 5;\n } else {\n // Round up to nearest 9\n return roundedNumber - remainder + 9;\n }\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest decimal cent. e.g. 1.53 = 1.50 / 1.57 = 1.60\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestDecimalCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.09\n if (input < 0.1) {\n return 0.1;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n */\n return parseFloat((Math.round(input * 10) / 10).toFixed(1));\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest .50 or .00. e.g. 11.22 = 11 / 11.55 = 11.50 / 11.90 = 12\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestHalfUnitCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.5\n if (input < 0.5) {\n return 0.5;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n *\n * Multiply by 2, round to the nearest integer, then divide by 2 to get the nearest .5 or .0\n * Return with fixed precision to avoid floating-point artifacts\n */\n return parseFloat((Math.round(input * 2) / 2).toFixed(2));\n};\n\nexport const Round = {\n /**\n * !!!!!!!!!!!!!!\n * ! Update 2024\n * ! We ar changing from `halfEven` (bankers rounding) to `halfAwayFromZero` (symmetric rounding) to match Avalara tax\n * @see https://knowledge.avalara.com/bundle/dqa1657870670369_dqa1657870670369/page/Change_how_AvaTax_rounds_the_tax_amount.html\n * @see https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n * !!!!!!!!!!!!!!\n *\n * OLD: halfEven docs\n * ⚠️ Instead of using Math.round, we HAVE to use this method to round the financial numbers everywhere where we CAN'T\n * deal with dinero.js (Dinero.js should be the priority). But often for converting from API requests we have to\n * normalize the values so we use this method.\n *\n * It just a re-export of the dinero.js halfEven (a.k.a bankers rounding) method which is the default rounding method.\n * @see https://github.com/dinerojs/dinero.js/blob/v2.0.0-alpha.8/packages/core/src/round/halfEven.ts\n *\n * Compared to Math.round (arithmetic rounding) it differentiates that it changes the `.5` round up or down behavior\n * based on if the rounded number would be an even number. So 1.5 would round to 2 while 2.5 would round to 2.\n * See the youtube link below for a brief exclamation on why it's important to use this method over regular rounding\n * (half-up):\n * https://youtu.be/yuRdYlZvs1E\n *\n * If you really want to get knee-deep in the rounding subject, you can read the following:\n * https://en.wikipedia.org/wiki/Rounding#Round_half_toward_zero\n */\n Financial: halfAwayFromZero,\n // https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n // TODO: maybe we should have separate rounding functions depending on the input value?\n // Reading from wiki \"Round half toward zero\" is better if the value is already \"normalized to cents\"\n // But the \"Round half to even\" seems better for when working with float like values\n // financialRound = Math.round;\n Shipping: down,\n Prettify: down,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyFull059: roundToNearestFull059,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyDecimalCents: roundToNearestDecimalCent,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyHalfUnitCents: roundToNearestHalfUnitCent,\n Subunit: halfUp,\n} satisfies Record<string, RoundingFn>;\n\n/**\n * Mapping of how prices should be rounded down to \"whole numbers\" after certain threshold\n */\nexport const prettifyPriceLookup = new Map([\n [USD.code, 20],\n [AED.code, 50],\n // Approximately every price above ~1.1 usd will be rounded in ZAR\n [ZAR.code, 20],\n]);\n\n/**\n * Map of dinero code to subunit digit count.\n */\nexport const smallestSubunitLookup = new Map<string, [Cents, RoundingFn]>([\n /**\n * TWD does not use subunits at all in day to day transactions.\n */\n [TWD.code, [0, Round.Subunit]],\n]);\n\n/**\n * Precompiled list for faster currency and locale lookups\n */\nexport const localizedCurrencyLookup = new Map<Currency, LocalizedCurrency>([\n [Currency.Aed, { currency: AED, locale: \"ar-AE\" }],\n [Currency.Bgn, { currency: BGN, locale: \"bg-BG\" }],\n [Currency.Cad, { currency: CAD, locale: \"en-CA\" }],\n [Currency.Chf, { currency: CHF, locale: \"it-CH\" }],\n [Currency.Czk, { currency: CZK, locale: \"cs-CZ\" }],\n [Currency.Dkk, { currency: DKK, locale: \"da-DK\" }],\n [Currency.Eur, { currency: EUR, locale: \"de-DE\" }],\n [Currency.Gbp, { currency: GBP, locale: \"en-GB\" }],\n [Currency.Hrk, { currency: HRK, locale: \"hr-HR\" }],\n [Currency.Huf, { currency: HUF, locale: \"hu-HU\" }],\n [Currency.Nok, { currency: NOK, locale: \"no-NO\" }],\n [Currency.Pln, { currency: PLN, locale: \"pl-PL\" }],\n [Currency.Ron, { currency: RON, locale: \"ro-RO\" }],\n [Currency.Sek, { currency: SEK, locale: \"sv-SE\" }],\n [Currency.Usd, { currency: USD, locale: \"en-US\" }],\n [Currency.Zar, { currency: ZAR, locale: \"en-ZA\" }],\n [Currency.Inr, { currency: INR, locale: \"en-IN\" }],\n [Currency.Sgd, { currency: SGD, locale: \"en-SG\" }],\n [Currency.Brl, { currency: BRL, locale: \"pt-BR\" }],\n // NOTE: en-JP Doesn't exist\n [Currency.Jpy, { currency: JPY, locale: \"en-JP\" }],\n // NOTE: en-TW Doesn't exist\n [Currency.Twd, { currency: TWD, locale: \"en-TW\" }],\n [Currency.Mxn, { currency: MXN, locale: \"es-MX\" }],\n [Currency.Php, { currency: PHP, locale: \"en-PH\" }],\n]);\n\n// #############################################################################\n// Tax Rate\n// #############################################################################\n/**\n * List of stores that require calculating per single item qty and then combining them to get the total tax amount for a\n * single line. Rest of the stores inherit default behavior that tax calculated on whole line item\n *\n * ! IMPORTANT: When changing need to sync that store.backend `AVATAX_CUSTOM_COMPANY_CODES` is updated to reflect the change\n *\n * FIXME: as PR for the change as unfinished currently disabled to enable the functionality that calculates tax per single item as requires\n * specific testing both for our custom tax and Avalara stores that use custom company codes. So the groundwork for\n * different tax calculations is there just need to enable on the share side and test if it works\n */\nexport const storesWithPerItemTaxRate = new Set([\n // #############################################################################\n // Stores with custom tax rates\n // #############################################################################\n // StoreId.Br,\n // StoreId.Tw,\n // #############################################################################\n // Stores with Avalara, but will have custom company codes to handle per-item tax rate\n // #############################################################################\n // StoreId.Jp,\n // StoreId.Sg,\n] as StoreId[]);\n\n/**\n * Dinero currency option block for working with tax rates within dinero\n */\nexport const TAX_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We expect the tax rate to be in the range of 0..1\n * 0 --> 0%\n * 1 --> 100%\n * 0.21 --> 21%\n * 0.2169 --> 21.69%\n * 0.12345678 --> 12.345678%\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 8,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n\n// #############################################################################\n// Exchange Rate\n// #############################################################################\n\nexport const EXCHANGE_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We support having certain decimal places for exchange rates\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 6,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n"],"names":["roundToNearestFull059","input","roundedNumber","Math","round","remainder","roundToNearestDecimalCent","parseFloat","toFixed","roundToNearestHalfUnitCent","Round","Financial","halfAwayFromZero","Shipping","down","Prettify","PrettifyFull059","PrettifyDecimalCents","PrettifyHalfUnitCents","Subunit","halfUp","prettifyPriceLookup","Map","USD","code","AED","ZAR","smallestSubunitLookup","TWD","localizedCurrencyLookup","Currency","Aed","currency","locale","Bgn","BGN","Cad","CAD","Chf","CHF","Czk","CZK","Dkk","DKK","Eur","EUR","Gbp","GBP","Hrk","HRK","Huf","HUF","Nok","NOK","Pln","PLN","Ron","RON","Sek","SEK","Usd","Zar","Inr","INR","Sgd","SGD","Brl","BRL","Jpy","JPY","Twd","Mxn","MXN","Php","PHP","storesWithPerItemTaxRate","Set","TAX_RATE_DINERO_CURRENCY","base","exponent","EXCHANGE_RATE_DINERO_CURRENCY"],"mappings":";;;;;;;AA8Ca,MAAAA,qBAAA,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;AAAA;AAAA;AAAA;AAAA;AAAA;EAUNC,QAAU,EAAA,CAAA;EACVvD,IAAM,EAAA;EAAA;AACR,CAAA;AAMO,MAAMwD,6BAAgC,GAAA;EAC3CF,IAAM,EAAA,EAAA;EAAA;AAAA;AAAA;AAAA;EAKNC,QAAU,EAAA,CAAA;EACVvD,IAAM,EAAA;EAAA;AACR,CAAA;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"constants.js","sources":["../../../src/utils/money/constants.ts"],"sourcesContent":["import {\n AED,\n BGN,\n BRL,\n CAD,\n CHF,\n CZK,\n DKK,\n EUR,\n GBP,\n HRK,\n HUF,\n INR,\n JPY,\n MXN,\n NOK,\n PHP,\n PLN,\n RON,\n SEK,\n SGD,\n TWD,\n USD,\n ZAR,\n} from \"@dinero.js/currencies\";\nimport { down, halfAwayFromZero, halfUp } from \"dinero.js\";\n\nimport type { StoreId } from \"../../types\";\nimport { Currency } from \"../../types\";\nimport type {\n Cents,\n DinoCurrency,\n LocalizedCurrency,\n RoundingFn,\n} from \"./types\";\n\n// #############################################################################\n// Constants\n// #############################################################################\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to nearest FULL 0/5/9 (and strip cents)\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestFull059: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-5.00\n if (input <= 5) {\n return 5;\n }\n\n /**\n * Input comes as float, for this rounding we don't need cents, so round\n * to nearest full number\n */\n const roundedNumber = Math.round(input);\n\n // Determine nearest rounding value\n const remainder = roundedNumber % 10;\n if (remainder <= 2) {\n // Round down to nearest 0\n return roundedNumber - remainder;\n } else if (remainder <= 7) {\n // Round to nearest 5\n return roundedNumber - remainder + 5;\n } else {\n // Round up to nearest 9\n return roundedNumber - remainder + 9;\n }\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest decimal cent. e.g. 1.53 = 1.50 / 1.57 = 1.60\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestDecimalCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.09\n if (input <= 0.1) {\n return 0.1;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n */\n return parseFloat((Math.round(input * 10) / 10).toFixed(1));\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest .50 or .00. e.g. 11.22 = 11 / 11.55 = 11.50 / 11.90 = 12\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestHalfUnitCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.5\n if (input <= 0.5) {\n return 0.5;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n *\n * Multiply by 2, round to the nearest integer, then divide by 2 to get the nearest .5 or .0\n * Return with fixed precision to avoid floating-point artifacts\n */\n return parseFloat((Math.round(input * 2) / 2).toFixed(2));\n};\n\nexport const Round = {\n /**\n * !!!!!!!!!!!!!!\n * ! Update 2024\n * ! We ar changing from `halfEven` (bankers rounding) to `halfAwayFromZero` (symmetric rounding) to match Avalara tax\n * @see https://knowledge.avalara.com/bundle/dqa1657870670369_dqa1657870670369/page/Change_how_AvaTax_rounds_the_tax_amount.html\n * @see https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n * !!!!!!!!!!!!!!\n *\n * OLD: halfEven docs\n * ⚠️ Instead of using Math.round, we HAVE to use this method to round the financial numbers everywhere where we CAN'T\n * deal with dinero.js (Dinero.js should be the priority). But often for converting from API requests we have to\n * normalize the values so we use this method.\n *\n * It just a re-export of the dinero.js halfEven (a.k.a bankers rounding) method which is the default rounding method.\n * @see https://github.com/dinerojs/dinero.js/blob/v2.0.0-alpha.8/packages/core/src/round/halfEven.ts\n *\n * Compared to Math.round (arithmetic rounding) it differentiates that it changes the `.5` round up or down behavior\n * based on if the rounded number would be an even number. So 1.5 would round to 2 while 2.5 would round to 2.\n * See the youtube link below for a brief exclamation on why it's important to use this method over regular rounding\n * (half-up):\n * https://youtu.be/yuRdYlZvs1E\n *\n * If you really want to get knee-deep in the rounding subject, you can read the following:\n * https://en.wikipedia.org/wiki/Rounding#Round_half_toward_zero\n */\n Financial: halfAwayFromZero,\n // https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n // TODO: maybe we should have separate rounding functions depending on the input value?\n // Reading from wiki \"Round half toward zero\" is better if the value is already \"normalized to cents\"\n // But the \"Round half to even\" seems better for when working with float like values\n // financialRound = Math.round;\n Shipping: down,\n Prettify: down,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyFull059: roundToNearestFull059,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyDecimalCents: roundToNearestDecimalCent,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyHalfUnitCents: roundToNearestHalfUnitCent,\n Subunit: halfUp,\n} satisfies Record<string, RoundingFn>;\n\n/**\n * Mapping of how prices should be rounded down to \"whole numbers\" after certain threshold\n */\nexport const prettifyPriceLookup = new Map([\n [USD.code, 20],\n [AED.code, 50],\n // Approximately every price above ~1.1 usd will be rounded in ZAR\n [ZAR.code, 20],\n]);\n\n/**\n * Map of dinero code to subunit digit count.\n */\nexport const smallestSubunitLookup = new Map<string, [Cents, RoundingFn]>([\n /**\n * TWD does not use subunits at all in day to day transactions.\n */\n [TWD.code, [0, Round.Subunit]],\n]);\n\n/**\n * Precompiled list for faster currency and locale lookups\n */\nexport const localizedCurrencyLookup = new Map<Currency, LocalizedCurrency>([\n [Currency.Aed, { currency: AED, locale: \"ar-AE\" }],\n [Currency.Bgn, { currency: BGN, locale: \"bg-BG\" }],\n [Currency.Cad, { currency: CAD, locale: \"en-CA\" }],\n [Currency.Chf, { currency: CHF, locale: \"it-CH\" }],\n [Currency.Czk, { currency: CZK, locale: \"cs-CZ\" }],\n [Currency.Dkk, { currency: DKK, locale: \"da-DK\" }],\n [Currency.Eur, { currency: EUR, locale: \"de-DE\" }],\n [Currency.Gbp, { currency: GBP, locale: \"en-GB\" }],\n [Currency.Hrk, { currency: HRK, locale: \"hr-HR\" }],\n [Currency.Huf, { currency: HUF, locale: \"hu-HU\" }],\n [Currency.Nok, { currency: NOK, locale: \"no-NO\" }],\n [Currency.Pln, { currency: PLN, locale: \"pl-PL\" }],\n [Currency.Ron, { currency: RON, locale: \"ro-RO\" }],\n [Currency.Sek, { currency: SEK, locale: \"sv-SE\" }],\n [Currency.Usd, { currency: USD, locale: \"en-US\" }],\n [Currency.Zar, { currency: ZAR, locale: \"en-ZA\" }],\n [Currency.Inr, { currency: INR, locale: \"en-IN\" }],\n [Currency.Sgd, { currency: SGD, locale: \"en-SG\" }],\n [Currency.Brl, { currency: BRL, locale: \"pt-BR\" }],\n // NOTE: en-JP Doesn't exist\n [Currency.Jpy, { currency: JPY, locale: \"en-JP\" }],\n // NOTE: en-TW Doesn't exist\n [Currency.Twd, { currency: TWD, locale: \"en-TW\" }],\n [Currency.Mxn, { currency: MXN, locale: \"es-MX\" }],\n [Currency.Php, { currency: PHP, locale: \"en-PH\" }],\n]);\n\n// #############################################################################\n// Tax Rate\n// #############################################################################\n/**\n * List of stores that require calculating per single item qty and then combining them to get the total tax amount for a\n * single line. Rest of the stores inherit default behavior that tax calculated on whole line item\n *\n * ! IMPORTANT: When changing need to sync that store.backend `AVATAX_CUSTOM_COMPANY_CODES` is updated to reflect the change\n *\n * FIXME: as PR for the change as unfinished currently disabled to enable the functionality that calculates tax per single item as requires\n * specific testing both for our custom tax and Avalara stores that use custom company codes. So the groundwork for\n * different tax calculations is there just need to enable on the share side and test if it works\n */\nexport const storesWithPerItemTaxRate = new Set([\n // #############################################################################\n // Stores with custom tax rates\n // #############################################################################\n // StoreId.Br,\n // StoreId.Tw,\n // #############################################################################\n // Stores with Avalara, but will have custom company codes to handle per-item tax rate\n // #############################################################################\n // StoreId.Jp,\n // StoreId.Sg,\n] as StoreId[]);\n\n/**\n * Dinero currency option block for working with tax rates within dinero\n */\nexport const TAX_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We expect the tax rate to be in the range of 0..1\n * 0 --> 0%\n * 1 --> 100%\n * 0.21 --> 21%\n * 0.2169 --> 21.69%\n * 0.12345678 --> 12.345678%\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 8,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n\n// #############################################################################\n// Exchange Rate\n// #############################################################################\n\nexport const EXCHANGE_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We support having certain decimal places for exchange rates\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 6,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n"],"names":["roundToNearestFull059","input","roundedNumber","Math","round","remainder","roundToNearestDecimalCent","parseFloat","toFixed","roundToNearestHalfUnitCent","Round","Financial","halfAwayFromZero","Shipping","down","Prettify","PrettifyFull059","PrettifyDecimalCents","PrettifyHalfUnitCents","Subunit","halfUp","prettifyPriceLookup","Map","USD","code","AED","ZAR","smallestSubunitLookup","TWD","localizedCurrencyLookup","Currency","Aed","currency","locale","Bgn","BGN","Cad","CAD","Chf","CHF","Czk","CZK","Dkk","DKK","Eur","EUR","Gbp","GBP","Hrk","HRK","Huf","HUF","Nok","NOK","Pln","PLN","Ron","RON","Sek","SEK","Usd","Zar","Inr","INR","Sgd","SGD","Brl","BRL","Jpy","JPY","Twd","Mxn","MXN","Php","PHP","storesWithPerItemTaxRate","Set","TAX_RATE_DINERO_CURRENCY","base","exponent","EXCHANGE_RATE_DINERO_CURRENCY"],"mappings":";;;;;;;AA8Ca,MAAAA,qBAAA,GAAqCC,KAAkB,IAAA;EAClE,IAAIA,UAAU,CAAG,EAAA;IACR,OAAA,CAAA;EACT;EAGA,IAAIA,SAAS,CAAG,E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wD,6BAAgC,GAAA;EAC3CF,IAAM,EAAA,EAAA;EAAA;AAAA;AAAA;AAAA;EAKNC,QAAU,EAAA,CAAA;EACVvD,IAAM,EAAA;EAAA;AACR,CAAA;;;;;;;;;;"}
|
|
@@ -7,7 +7,7 @@ const roundToNearestFull059 = input => {
|
|
|
7
7
|
if (input === 0) {
|
|
8
8
|
return 0;
|
|
9
9
|
}
|
|
10
|
-
if (input <=
|
|
10
|
+
if (input <= 5) {
|
|
11
11
|
return 5;
|
|
12
12
|
}
|
|
13
13
|
const roundedNumber = Math.round(input);
|
|
@@ -24,7 +24,7 @@ const roundToNearestDecimalCent = input => {
|
|
|
24
24
|
if (input === 0) {
|
|
25
25
|
return 0;
|
|
26
26
|
}
|
|
27
|
-
if (input
|
|
27
|
+
if (input <= 0.1) {
|
|
28
28
|
return 0.1;
|
|
29
29
|
}
|
|
30
30
|
return parseFloat((Math.round(input * 10) / 10).toFixed(1));
|
|
@@ -33,7 +33,7 @@ const roundToNearestHalfUnitCent = input => {
|
|
|
33
33
|
if (input === 0) {
|
|
34
34
|
return 0;
|
|
35
35
|
}
|
|
36
|
-
if (input
|
|
36
|
+
if (input <= 0.5) {
|
|
37
37
|
return 0.5;
|
|
38
38
|
}
|
|
39
39
|
return parseFloat((Math.round(input * 2) / 2).toFixed(2));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","sources":["../../../src/utils/money/constants.ts"],"sourcesContent":["import {\n AED,\n BGN,\n BRL,\n CAD,\n CHF,\n CZK,\n DKK,\n EUR,\n GBP,\n HRK,\n HUF,\n INR,\n JPY,\n MXN,\n NOK,\n PHP,\n PLN,\n RON,\n SEK,\n SGD,\n TWD,\n USD,\n ZAR,\n} from \"@dinero.js/currencies\";\nimport { down, halfAwayFromZero, halfUp } from \"dinero.js\";\n\nimport type { StoreId } from \"../../types\";\nimport { Currency } from \"../../types\";\nimport type {\n Cents,\n DinoCurrency,\n LocalizedCurrency,\n RoundingFn,\n} from \"./types\";\n\n// #############################################################################\n// Constants\n// #############################################################################\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to nearest FULL 0/5/9 (and strip cents)\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestFull059: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-3.00\n if (input <= 3) {\n return 5;\n }\n\n /**\n * Input comes as float, for this rounding we don't need cents, so round\n * to nearest full number\n */\n const roundedNumber = Math.round(input);\n\n // Determine nearest rounding value\n const remainder = roundedNumber % 10;\n if (remainder <= 2) {\n // Round down to nearest 0\n return roundedNumber - remainder;\n } else if (remainder <= 7) {\n // Round to nearest 5\n return roundedNumber - remainder + 5;\n } else {\n // Round up to nearest 9\n return roundedNumber - remainder + 9;\n }\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest decimal cent. e.g. 1.53 = 1.50 / 1.57 = 1.60\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestDecimalCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.09\n if (input < 0.1) {\n return 0.1;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n */\n return parseFloat((Math.round(input * 10) / 10).toFixed(1));\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest .50 or .00. e.g. 11.22 = 11 / 11.55 = 11.50 / 11.90 = 12\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestHalfUnitCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.5\n if (input < 0.5) {\n return 0.5;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n *\n * Multiply by 2, round to the nearest integer, then divide by 2 to get the nearest .5 or .0\n * Return with fixed precision to avoid floating-point artifacts\n */\n return parseFloat((Math.round(input * 2) / 2).toFixed(2));\n};\n\nexport const Round = {\n /**\n * !!!!!!!!!!!!!!\n * ! Update 2024\n * ! We ar changing from `halfEven` (bankers rounding) to `halfAwayFromZero` (symmetric rounding) to match Avalara tax\n * @see https://knowledge.avalara.com/bundle/dqa1657870670369_dqa1657870670369/page/Change_how_AvaTax_rounds_the_tax_amount.html\n * @see https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n * !!!!!!!!!!!!!!\n *\n * OLD: halfEven docs\n * ⚠️ Instead of using Math.round, we HAVE to use this method to round the financial numbers everywhere where we CAN'T\n * deal with dinero.js (Dinero.js should be the priority). But often for converting from API requests we have to\n * normalize the values so we use this method.\n *\n * It just a re-export of the dinero.js halfEven (a.k.a bankers rounding) method which is the default rounding method.\n * @see https://github.com/dinerojs/dinero.js/blob/v2.0.0-alpha.8/packages/core/src/round/halfEven.ts\n *\n * Compared to Math.round (arithmetic rounding) it differentiates that it changes the `.5` round up or down behavior\n * based on if the rounded number would be an even number. So 1.5 would round to 2 while 2.5 would round to 2.\n * See the youtube link below for a brief exclamation on why it's important to use this method over regular rounding\n * (half-up):\n * https://youtu.be/yuRdYlZvs1E\n *\n * If you really want to get knee-deep in the rounding subject, you can read the following:\n * https://en.wikipedia.org/wiki/Rounding#Round_half_toward_zero\n */\n Financial: halfAwayFromZero,\n // https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n // TODO: maybe we should have separate rounding functions depending on the input value?\n // Reading from wiki \"Round half toward zero\" is better if the value is already \"normalized to cents\"\n // But the \"Round half to even\" seems better for when working with float like values\n // financialRound = Math.round;\n Shipping: down,\n Prettify: down,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyFull059: roundToNearestFull059,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyDecimalCents: roundToNearestDecimalCent,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyHalfUnitCents: roundToNearestHalfUnitCent,\n Subunit: halfUp,\n} satisfies Record<string, RoundingFn>;\n\n/**\n * Mapping of how prices should be rounded down to \"whole numbers\" after certain threshold\n */\nexport const prettifyPriceLookup = new Map([\n [USD.code, 20],\n [AED.code, 50],\n // Approximately every price above ~1.1 usd will be rounded in ZAR\n [ZAR.code, 20],\n]);\n\n/**\n * Map of dinero code to subunit digit count.\n */\nexport const smallestSubunitLookup = new Map<string, [Cents, RoundingFn]>([\n /**\n * TWD does not use subunits at all in day to day transactions.\n */\n [TWD.code, [0, Round.Subunit]],\n]);\n\n/**\n * Precompiled list for faster currency and locale lookups\n */\nexport const localizedCurrencyLookup = new Map<Currency, LocalizedCurrency>([\n [Currency.Aed, { currency: AED, locale: \"ar-AE\" }],\n [Currency.Bgn, { currency: BGN, locale: \"bg-BG\" }],\n [Currency.Cad, { currency: CAD, locale: \"en-CA\" }],\n [Currency.Chf, { currency: CHF, locale: \"it-CH\" }],\n [Currency.Czk, { currency: CZK, locale: \"cs-CZ\" }],\n [Currency.Dkk, { currency: DKK, locale: \"da-DK\" }],\n [Currency.Eur, { currency: EUR, locale: \"de-DE\" }],\n [Currency.Gbp, { currency: GBP, locale: \"en-GB\" }],\n [Currency.Hrk, { currency: HRK, locale: \"hr-HR\" }],\n [Currency.Huf, { currency: HUF, locale: \"hu-HU\" }],\n [Currency.Nok, { currency: NOK, locale: \"no-NO\" }],\n [Currency.Pln, { currency: PLN, locale: \"pl-PL\" }],\n [Currency.Ron, { currency: RON, locale: \"ro-RO\" }],\n [Currency.Sek, { currency: SEK, locale: \"sv-SE\" }],\n [Currency.Usd, { currency: USD, locale: \"en-US\" }],\n [Currency.Zar, { currency: ZAR, locale: \"en-ZA\" }],\n [Currency.Inr, { currency: INR, locale: \"en-IN\" }],\n [Currency.Sgd, { currency: SGD, locale: \"en-SG\" }],\n [Currency.Brl, { currency: BRL, locale: \"pt-BR\" }],\n // NOTE: en-JP Doesn't exist\n [Currency.Jpy, { currency: JPY, locale: \"en-JP\" }],\n // NOTE: en-TW Doesn't exist\n [Currency.Twd, { currency: TWD, locale: \"en-TW\" }],\n [Currency.Mxn, { currency: MXN, locale: \"es-MX\" }],\n [Currency.Php, { currency: PHP, locale: \"en-PH\" }],\n]);\n\n// #############################################################################\n// Tax Rate\n// #############################################################################\n/**\n * List of stores that require calculating per single item qty and then combining them to get the total tax amount for a\n * single line. Rest of the stores inherit default behavior that tax calculated on whole line item\n *\n * ! IMPORTANT: When changing need to sync that store.backend `AVATAX_CUSTOM_COMPANY_CODES` is updated to reflect the change\n *\n * FIXME: as PR for the change as unfinished currently disabled to enable the functionality that calculates tax per single item as requires\n * specific testing both for our custom tax and Avalara stores that use custom company codes. So the groundwork for\n * different tax calculations is there just need to enable on the share side and test if it works\n */\nexport const storesWithPerItemTaxRate = new Set([\n // #############################################################################\n // Stores with custom tax rates\n // #############################################################################\n // StoreId.Br,\n // StoreId.Tw,\n // #############################################################################\n // Stores with Avalara, but will have custom company codes to handle per-item tax rate\n // #############################################################################\n // StoreId.Jp,\n // StoreId.Sg,\n] as StoreId[]);\n\n/**\n * Dinero currency option block for working with tax rates within dinero\n */\nexport const TAX_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We expect the tax rate to be in the range of 0..1\n * 0 --> 0%\n * 1 --> 100%\n * 0.21 --> 21%\n * 0.2169 --> 21.69%\n * 0.12345678 --> 12.345678%\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 8,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n\n// #############################################################################\n// Exchange Rate\n// #############################################################################\n\nexport const EXCHANGE_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We support having certain decimal places for exchange rates\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 6,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n"],"names":["roundToNearestFull059","input","roundedNumber","Math","round","remainder","roundToNearestDecimalCent","parseFloat","toFixed","roundToNearestHalfUnitCent","Round","Financial","halfAwayFromZero","Shipping","down","Prettify","PrettifyFull059","PrettifyDecimalCents","PrettifyHalfUnitCents","Subunit","halfUp","prettifyPriceLookup","Map","USD","code","AED","ZAR","smallestSubunitLookup","TWD","localizedCurrencyLookup","Currency","Aed","currency","locale","Bgn","BGN","Cad","CAD","Chf","CHF","Czk","CZK","Dkk","DKK","Eur","EUR","Gbp","GBP","Hrk","HRK","Huf","HUF","Nok","NOK","Pln","PLN","Ron","RON","Sek","SEK","Usd","Zar","Inr","INR","Sgd","SGD","Brl","BRL","Jpy","JPY","Twd","Mxn","MXN","Php","PHP","storesWithPerItemTaxRate","Set","TAX_RATE_DINERO_CURRENCY","base","exponent","EXCHANGE_RATE_DINERO_CURRENCY"],"mappings":";;;;;AA8Ca,MAAAA,qBAAA,GAAqCC,KAAkB,IAAA;EAClE,IAAIA,UAAU,CAAG,EAAA;IACR,OAAA,CAAA;EACT;EAGA,IAAIA,SAAS,CAAG,EAAA;IACP,OAAA,CAAA;EACT;EAMM,MAAAC,aAAA,GAAgBC,IAAK,CAAAC,KAAA,CAAMH,KAAK,CAAA;EAGtC,MAAMI,YAAYH,aAAgB,GAAA,EAAA;EAClC,IAAIG,aAAa,CAAG,EAAA;IAElB,OAAOH,aAAgB,GAAAG,SAAA;EAAA,CACzB,MAAA,IAAWA,aAAa,CAAG,EAAA;IAEzB,OAAOH,gBAAgBG,SAAY,GAAA,CAAA;EAAA,CAC9B,MAAA;IAEL,OAAOH,gBAAgBG,SAAY,GAAA,CAAA;EACrC;AACF,CAAA;AASa,MAAAC,yBAAA,GAAyCL,KAAkB,IAAA;EACtE,IAAIA,UAAU,CAAG,EAAA;IACR,OAAA,CAAA;EACT;EAGA,IAAIA,QAAQ,GAAK,EAAA;IACR,OAAA,GAAA;EACT;EAMO,OAAAM,UAAA,CAAA,CAAYJ,KAAKC,KAAM,CAAAH,KAAA,GAAQ,EAAE,CAAI,GAAA,EAAA,EAAIO,OAAQ,CAAA,CAAC,CAAC,CAAA;AAC5D,CA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.ts"],"sourcesContent":["import {\n AED,\n BGN,\n BRL,\n CAD,\n CHF,\n CZK,\n DKK,\n EUR,\n GBP,\n HRK,\n HUF,\n INR,\n JPY,\n MXN,\n NOK,\n PHP,\n PLN,\n RON,\n SEK,\n SGD,\n TWD,\n USD,\n ZAR,\n} from \"@dinero.js/currencies\";\nimport { down, halfAwayFromZero, halfUp } from \"dinero.js\";\n\nimport type { StoreId } from \"../../types\";\nimport { Currency } from \"../../types\";\nimport type {\n Cents,\n DinoCurrency,\n LocalizedCurrency,\n RoundingFn,\n} from \"./types\";\n\n// #############################################################################\n// Constants\n// #############################################################################\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to nearest FULL 0/5/9 (and strip cents)\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestFull059: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-5.00\n if (input <= 5) {\n return 5;\n }\n\n /**\n * Input comes as float, for this rounding we don't need cents, so round\n * to nearest full number\n */\n const roundedNumber = Math.round(input);\n\n // Determine nearest rounding value\n const remainder = roundedNumber % 10;\n if (remainder <= 2) {\n // Round down to nearest 0\n return roundedNumber - remainder;\n } else if (remainder <= 7) {\n // Round to nearest 5\n return roundedNumber - remainder + 5;\n } else {\n // Round up to nearest 9\n return roundedNumber - remainder + 9;\n }\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest decimal cent. e.g. 1.53 = 1.50 / 1.57 = 1.60\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestDecimalCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.09\n if (input <= 0.1) {\n return 0.1;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n */\n return parseFloat((Math.round(input * 10) / 10).toFixed(1));\n};\n\n/**\n * Custom rounding method to be used with dinero.js\n * This rounding method will round to\n * nearest .50 or .00. e.g. 11.22 = 11 / 11.55 = 11.50 / 11.90 = 12\n *\n * @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n */\nexport const roundToNearestHalfUnitCent: RoundingFn = (input: number) => {\n if (input === 0) {\n return 0;\n }\n\n // Special handling of 0.01-0.5\n if (input <= 0.5) {\n return 0.5;\n }\n\n /**\n * Input comes as float, just to be on the safe side use toFixed to mitigate\n * risk of running to floating point precision issues\n *\n * Multiply by 2, round to the nearest integer, then divide by 2 to get the nearest .5 or .0\n * Return with fixed precision to avoid floating-point artifacts\n */\n return parseFloat((Math.round(input * 2) / 2).toFixed(2));\n};\n\nexport const Round = {\n /**\n * !!!!!!!!!!!!!!\n * ! Update 2024\n * ! We ar changing from `halfEven` (bankers rounding) to `halfAwayFromZero` (symmetric rounding) to match Avalara tax\n * @see https://knowledge.avalara.com/bundle/dqa1657870670369_dqa1657870670369/page/Change_how_AvaTax_rounds_the_tax_amount.html\n * @see https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n * !!!!!!!!!!!!!!\n *\n * OLD: halfEven docs\n * ⚠️ Instead of using Math.round, we HAVE to use this method to round the financial numbers everywhere where we CAN'T\n * deal with dinero.js (Dinero.js should be the priority). But often for converting from API requests we have to\n * normalize the values so we use this method.\n *\n * It just a re-export of the dinero.js halfEven (a.k.a bankers rounding) method which is the default rounding method.\n * @see https://github.com/dinerojs/dinero.js/blob/v2.0.0-alpha.8/packages/core/src/round/halfEven.ts\n *\n * Compared to Math.round (arithmetic rounding) it differentiates that it changes the `.5` round up or down behavior\n * based on if the rounded number would be an even number. So 1.5 would round to 2 while 2.5 would round to 2.\n * See the youtube link below for a brief exclamation on why it's important to use this method over regular rounding\n * (half-up):\n * https://youtu.be/yuRdYlZvs1E\n *\n * If you really want to get knee-deep in the rounding subject, you can read the following:\n * https://en.wikipedia.org/wiki/Rounding#Round_half_toward_zero\n */\n Financial: halfAwayFromZero,\n // https://ui.slack.com/archives/C07P7L7S3CP/p1728313196140639\n // TODO: maybe we should have separate rounding functions depending on the input value?\n // Reading from wiki \"Round half toward zero\" is better if the value is already \"normalized to cents\"\n // But the \"Round half to even\" seems better for when working with float like values\n // financialRound = Math.round;\n Shipping: down,\n Prettify: down,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyFull059: roundToNearestFull059,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyDecimalCents: roundToNearestDecimalCent,\n /**\n * ! Disclaimer may not work for \"weird\" currencies as expected\n */\n PrettifyHalfUnitCents: roundToNearestHalfUnitCent,\n Subunit: halfUp,\n} satisfies Record<string, RoundingFn>;\n\n/**\n * Mapping of how prices should be rounded down to \"whole numbers\" after certain threshold\n */\nexport const prettifyPriceLookup = new Map([\n [USD.code, 20],\n [AED.code, 50],\n // Approximately every price above ~1.1 usd will be rounded in ZAR\n [ZAR.code, 20],\n]);\n\n/**\n * Map of dinero code to subunit digit count.\n */\nexport const smallestSubunitLookup = new Map<string, [Cents, RoundingFn]>([\n /**\n * TWD does not use subunits at all in day to day transactions.\n */\n [TWD.code, [0, Round.Subunit]],\n]);\n\n/**\n * Precompiled list for faster currency and locale lookups\n */\nexport const localizedCurrencyLookup = new Map<Currency, LocalizedCurrency>([\n [Currency.Aed, { currency: AED, locale: \"ar-AE\" }],\n [Currency.Bgn, { currency: BGN, locale: \"bg-BG\" }],\n [Currency.Cad, { currency: CAD, locale: \"en-CA\" }],\n [Currency.Chf, { currency: CHF, locale: \"it-CH\" }],\n [Currency.Czk, { currency: CZK, locale: \"cs-CZ\" }],\n [Currency.Dkk, { currency: DKK, locale: \"da-DK\" }],\n [Currency.Eur, { currency: EUR, locale: \"de-DE\" }],\n [Currency.Gbp, { currency: GBP, locale: \"en-GB\" }],\n [Currency.Hrk, { currency: HRK, locale: \"hr-HR\" }],\n [Currency.Huf, { currency: HUF, locale: \"hu-HU\" }],\n [Currency.Nok, { currency: NOK, locale: \"no-NO\" }],\n [Currency.Pln, { currency: PLN, locale: \"pl-PL\" }],\n [Currency.Ron, { currency: RON, locale: \"ro-RO\" }],\n [Currency.Sek, { currency: SEK, locale: \"sv-SE\" }],\n [Currency.Usd, { currency: USD, locale: \"en-US\" }],\n [Currency.Zar, { currency: ZAR, locale: \"en-ZA\" }],\n [Currency.Inr, { currency: INR, locale: \"en-IN\" }],\n [Currency.Sgd, { currency: SGD, locale: \"en-SG\" }],\n [Currency.Brl, { currency: BRL, locale: \"pt-BR\" }],\n // NOTE: en-JP Doesn't exist\n [Currency.Jpy, { currency: JPY, locale: \"en-JP\" }],\n // NOTE: en-TW Doesn't exist\n [Currency.Twd, { currency: TWD, locale: \"en-TW\" }],\n [Currency.Mxn, { currency: MXN, locale: \"es-MX\" }],\n [Currency.Php, { currency: PHP, locale: \"en-PH\" }],\n]);\n\n// #############################################################################\n// Tax Rate\n// #############################################################################\n/**\n * List of stores that require calculating per single item qty and then combining them to get the total tax amount for a\n * single line. Rest of the stores inherit default behavior that tax calculated on whole line item\n *\n * ! IMPORTANT: When changing need to sync that store.backend `AVATAX_CUSTOM_COMPANY_CODES` is updated to reflect the change\n *\n * FIXME: as PR for the change as unfinished currently disabled to enable the functionality that calculates tax per single item as requires\n * specific testing both for our custom tax and Avalara stores that use custom company codes. So the groundwork for\n * different tax calculations is there just need to enable on the share side and test if it works\n */\nexport const storesWithPerItemTaxRate = new Set([\n // #############################################################################\n // Stores with custom tax rates\n // #############################################################################\n // StoreId.Br,\n // StoreId.Tw,\n // #############################################################################\n // Stores with Avalara, but will have custom company codes to handle per-item tax rate\n // #############################################################################\n // StoreId.Jp,\n // StoreId.Sg,\n] as StoreId[]);\n\n/**\n * Dinero currency option block for working with tax rates within dinero\n */\nexport const TAX_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We expect the tax rate to be in the range of 0..1\n * 0 --> 0%\n * 1 --> 100%\n * 0.21 --> 21%\n * 0.2169 --> 21.69%\n * 0.12345678 --> 12.345678%\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 8,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n\n// #############################################################################\n// Exchange Rate\n// #############################################################################\n\nexport const EXCHANGE_RATE_DINERO_CURRENCY = {\n base: 10,\n /**\n * We support having certain decimal places for exchange rates\n * !!! Don't change as this value is tied to store.backend DB schema !!!\n */\n exponent: 6,\n code: \"\", // Not important\n} satisfies DinoCurrency;\n"],"names":["roundToNearestFull059","input","roundedNumber","Math","round","remainder","roundToNearestDecimalCent","parseFloat","toFixed","roundToNearestHalfUnitCent","Round","Financial","halfAwayFromZero","Shipping","down","Prettify","PrettifyFull059","PrettifyDecimalCents","PrettifyHalfUnitCents","Subunit","halfUp","prettifyPriceLookup","Map","USD","code","AED","ZAR","smallestSubunitLookup","TWD","localizedCurrencyLookup","Currency","Aed","currency","locale","Bgn","BGN","Cad","CAD","Chf","CHF","Czk","CZK","Dkk","DKK","Eur","EUR","Gbp","GBP","Hrk","HRK","Huf","HUF","Nok","NOK","Pln","PLN","Ron","RON","Sek","SEK","Usd","Zar","Inr","INR","Sgd","SGD","Brl","BRL","Jpy","JPY","Twd","Mxn","MXN","Php","PHP","storesWithPerItemTaxRate","Set","TAX_RATE_DINERO_CURRENCY","base","exponent","EXCHANGE_RATE_DINERO_CURRENCY"],"mappings":";;;;;AA8Ca,MAAAA,qBAAA,GAAqCC,KAAkB,IAAA;EAClE,IAAIA,UAAU,CAAG,EAAA;IACR,OAAA,CAAA;EACT;EAGA,IAAIA,SAAS,CAAG,EAAA;IACP,OAAA,CAAA;EACT;EAMM,MAAAC,aAAA,GAAgBC,IAAK,CAAAC,KAAA,CAAMH,KAAK,CAAA;EAGtC,MAAMI,YAAYH,aAAgB,GAAA,EAAA;EAClC,IAAIG,aAAa,CAAG,EAAA;IAElB,OAAOH,aAAgB,GAAAG,SAAA;EAAA,CACzB,MAAA,IAAWA,aAAa,CAAG,EAAA;IAEzB,OAAOH,gBAAgBG,SAAY,GAAA,CAAA;EAAA,CAC9B,MA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2B,GAAA;EACtCC,IAAM,EAAA,EAAA;EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;EAUNC,QAAU,EAAA,CAAA;EACVvD,IAAM,EAAA;EAAA;AACR,CAAA;AAMO,MAAMwD,6BAAgC,GAAA;EAC3CF,IAAM,EAAA,EAAA;EAAA;AAAA;AAAA;AAAA;EAKNC,QAAU,EAAA,CAAA;EACVvD,IAAM,EAAA;EAAA;AACR,CAAA;"}
|
|
@@ -47,7 +47,8 @@ function formatPriceRaw(dinero, locale, options) {
|
|
|
47
47
|
*/
|
|
48
48
|
formatted.replace(
|
|
49
49
|
// For some reason `\.` need to be double-escaped `\\` when creating the regex from template string
|
|
50
|
-
new RegExp(`(\\.|,)${
|
|
50
|
+
new RegExp(`(\\.|,)${
|
|
51
|
+
// Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
|
|
51
52
|
options?.removeFractions ? "\\d" : 0}{0,${currency.exponent}}(\\s\\D)?$`),
|
|
52
53
|
// In the replaced using "last capture group" (if-exists) so we restore the trailing currency sign
|
|
53
54
|
"$2")) : formatted;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.js","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,SAAAA,CAAAA,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;EACT;EAEYA,SAAA,GAAA,IAAIC,IAAK,CAAAC,YAAA,CAAaJ,MAAQ,EAAA;I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../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;;;AAaa,MAAAA,oBAAA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,eAAe,CAAA;QACjD;MACF;IACA;MAAS;QAEH,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAd,KAAK,CAAG,EAAA;UAChB,OAAAA,KAAA;QACT;QAEA,MAAMe,mCAAmCC,SAAAA,CAAAA,mBAAoB,CAAAjD,GAAA,CAC3DkC,UAAUxB,QAAS,CAAAS,IAAA,CACrB;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,SAAO,CAAAA,MAAA,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;;;;"}
|
|
@@ -45,7 +45,8 @@ function formatPriceRaw(dinero, locale, options) {
|
|
|
45
45
|
*/
|
|
46
46
|
formatted.replace(
|
|
47
47
|
// For some reason `\.` need to be double-escaped `\\` when creating the regex from template string
|
|
48
|
-
new RegExp(`(\\.|,)${
|
|
48
|
+
new RegExp(`(\\.|,)${
|
|
49
|
+
// Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding
|
|
49
50
|
options?.removeFractions ? "\\d" : 0}{0,${currency.exponent}}(\\s\\D)?$`),
|
|
50
51
|
// In the replaced using "last capture group" (if-exists) so we restore the trailing currency sign
|
|
51
52
|
"$2")) : formatted;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.mjs","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;EACT;EAEYA,SAAA,GAAA,IAAIC,IAAK,CAAAC,YAAA,CAAaJ,MAAQ,EAAA;IACxCK,KAAO,EAAA,UAAA;IACPC,QAAU,EAAAZ,YAAA;IAAA;AAAA;AAAA;AAAA;AAAA;IAMVa,YAAc,EAAA,UAAA;IACdC,eAAiB,EAAA;EAAA,CAClB,CAAA;EACsBX,sBAAA,CAAAY,GAAA,CAAIR,UAAUC,SAAS,CAAA;EAEvC,OAAAA,SAAA;AACT,CAAA;AAoCgB,SAAAQ,cAAAA,CACdC,MACA,EAAAX,MAAA,EACAY,OACQ,EAAA;EACR,OAAOC,SAASF,MAAQ,EAAA,CAAC;IAAEG,MAAA;IAAQR;GAAe,KAAA;IAChD,MAAMJ,SAAY,GAAAH,oBAAA,CAAqBC,MAAQ,EAAAM,QAAA,CAASS,IAAI,CAAA;IACtD,MAAAC,SAAA,GAAYd,SAAU,CAAAe,MAAA,CAAOH,MAAM,CAAA;IAElC,OAAAF,OAAA,EAASM,mBAAmBN,OAAS,EAAAO,mBAAA;IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;IAQxCH,SAAU,CAAAI,OAAA;IAAA;IAER,IAAIC,MAAA,CACF
|
|
1
|
+
{"version":3,"file":"format.mjs","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN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subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,SAAA,CAAAA,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AAUa,MAAAM,iBAAA,GAAqBH,SAAqC,IAAA;EAC/D,MAAAI,cAAA,GAAiBC,YAAAA,CAAAA,sBAAuB,CAAAN,GAAA,CAAIC,SAAQ,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;EAAA,CACpB,CAAA;AACH,CAAA;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,SAAA,CAAAA,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV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