chore: remove pricing conversions on admin (#7665)

This commit is contained in:
Frane Polić authored and GitHub committed 2024-06-10 17:38:35 +02:00
1 parent f08f0d6cc9
commit 3b8160b564
7 files changed
+25 -103

No files matched your search

@@ -4,47 +4,6 @@ export const getDecimalDigits = (currency: string) => {
return currencies[currency.toUpperCase()]?.decimal_digits ?? 0 return currencies[currency.toUpperCase()]?.decimal_digits ?? 0
} }
/**
* Converts an amount from the database format (cents) to the presentational format
*
* @param amount - The amount to format
* @param currency - The currency code to format the amount in
* @returns The formatted amount
*
* @example
* getPresentationalAmount(1000, "usd") // 10
* getPresentationalAmount(1000, "jpy") // 1000
*/
export const getPresentationalAmount = (amount: number, currency: string) => {
const decimalDigits = getDecimalDigits(currency)
if (decimalDigits === undefined) {
throw new Error("Currency has no decimal digits")
}
return amount / 10 ** decimalDigits
}
/**
* Converts an amount to the database format (cents)
* @param amount - The amount to convert to the database amount
* @param currency - The currency code to convert the amount to
* @returns The amount in the database format
*
* @example
* getDbAmount(10.5, "usd") // 1050
* getDbAmount(10, "jpy") // 10
*/
export const getDbAmount = (amount: number, currency: string) => {
const decimalDigits = getDecimalDigits(currency)
if (decimalDigits === undefined) {
throw new Error("Currency has no decimal digits")
}
return amount * 10 ** decimalDigits
}
/** /**
* Returns a formatted amount based on the currency code using the browser's locale * Returns a formatted amount based on the currency code using the browser's locale
* @param amount - The amount to format * @param amount - The amount to format
@@ -52,8 +11,8 @@ export const getDbAmount = (amount: number, currency: string) => {
* @returns - The formatted amount * @returns - The formatted amount
* *
* @example * @example
* getFormattedAmount(1000, "usd") // '$10.00' if the browser's locale is en-US * getFormattedAmount(10, "usd") // '$10.00' if the browser's locale is en-US
* getFormattedAmount(1000, "usd") // '10,00 $' if the browser's locale is fr-FR * getFormattedAmount(10, "usd") // '10,00 $' if the browser's locale is fr-FR
*/ */
export const getLocaleAmount = (amount: number, currencyCode: string) => { export const getLocaleAmount = (amount: number, currencyCode: string) => {
const formatter = new Intl.NumberFormat(undefined, { const formatter = new Intl.NumberFormat(undefined, {
@@ -62,7 +21,7 @@ export const getLocaleAmount = (amount: number, currencyCode: string) => {
currency: currencyCode, currency: currencyCode,
}) })
return formatter.format(getPresentationalAmount(amount, currencyCode)) return formatter.format(amount)
} }
export const getNativeSymbol = (currencyCode: string) => { export const getNativeSymbol = (currencyCode: string) => {
@@ -84,9 +43,8 @@ export const getNativeSymbol = (currencyCode: string) => {
export const getStylizedAmount = (amount: number, currencyCode: string) => { export const getStylizedAmount = (amount: number, currencyCode: string) => {
const symbol = getNativeSymbol(currencyCode) const symbol = getNativeSymbol(currencyCode)
const decimalDigits = getDecimalDigits(currencyCode) const decimalDigits = getDecimalDigits(currencyCode)
const presentationAmount = getPresentationalAmount(amount, currencyCode)
const total = presentationAmount.toLocaleString(undefined, { const total = amount.toLocaleString(undefined, {
minimumFractionDigits: decimalDigits, minimumFractionDigits: decimalDigits,
maximumFractionDigits: decimalDigits, maximumFractionDigits: decimalDigits,
}) })
@@ -28,8 +28,8 @@ import { useRegions } from "../../../../../hooks/api/regions"
import { useCreateShippingOptions } from "../../../../../hooks/api/shipping-options" import { useCreateShippingOptions } from "../../../../../hooks/api/shipping-options"
import { useShippingProfiles } from "../../../../../hooks/api/shipping-profiles" import { useShippingProfiles } from "../../../../../hooks/api/shipping-profiles"
import { formatProvider } from "../../../../../lib/format-provider" import { formatProvider } from "../../../../../lib/format-provider"
import { getDbAmount } from "../../../../../lib/money-amount-helpers"
import { CreateShippingOptionsPricesForm } from "./create-shipping-options-prices-form" import { CreateShippingOptionsPricesForm } from "./create-shipping-options-prices-form"
import { castNumber } from "../../../../../lib/cast-number"
enum Tab { enum Tab {
DETAILS = "details", DETAILS = "details",
@@ -103,8 +103,7 @@ export function CreateShippingOptionsForm({
const handleSubmit = form.handleSubmit(async (data) => { const handleSubmit = form.handleSubmit(async (data) => {
const currencyPrices = Object.entries(data.currency_prices) const currencyPrices = Object.entries(data.currency_prices)
.map(([code, value]) => { .map(([code, value]) => {
const amount = const amount = value === "" ? undefined : castNumber(value)
value === "" ? undefined : getDbAmount(Number(value), code)
return { return {
currency_code: code, currency_code: code,
@@ -119,8 +118,7 @@ export function CreateShippingOptionsForm({
.map(([region_id, value]) => { .map(([region_id, value]) => {
const code = regionsMap.get(region_id) const code = regionsMap.get(region_id)
const amount = const amount = value === "" ? undefined : castNumber(value)
value === "" ? undefined : getDbAmount(Number(value), code)
return { return {
region_id, region_id,
@@ -25,11 +25,8 @@ import { useCurrencies } from "../../../../../hooks/api/currencies"
import { useRegions } from "../../../../../hooks/api/regions" import { useRegions } from "../../../../../hooks/api/regions"
import { useUpdateShippingOptions } from "../../../../../hooks/api/shipping-options" import { useUpdateShippingOptions } from "../../../../../hooks/api/shipping-options"
import { useStore } from "../../../../../hooks/api/store" import { useStore } from "../../../../../hooks/api/store"
import {
getDbAmount,
getPresentationalAmount,
} from "../../../../../lib/money-amount-helpers"
import { ExtendedProductDTO } from "../../../../../types/api-responses" import { ExtendedProductDTO } from "../../../../../types/api-responses"
import { castNumber } from "../../../../../lib/cast-number.ts"
const getInitialCurrencyPrices = (prices: PriceDTO[]) => { const getInitialCurrencyPrices = (prices: PriceDTO[]) => {
const ret: Record<string, number> = {} const ret: Record<string, number> = {}
@@ -38,10 +35,7 @@ const getInitialCurrencyPrices = (prices: PriceDTO[]) => {
// this is a region price // this is a region price
return return
} }
ret[p.currency_code!] = getPresentationalAmount( ret[p.currency_code!] = castNumber(p.amount)
p.amount as number,
p.currency_code!
)
}) })
return ret return ret
} }
@@ -51,10 +45,7 @@ const getInitialRegionPrices = (prices: PriceDTO[]) => {
prices.forEach((p) => { prices.forEach((p) => {
if (p.price_rules!.length) { if (p.price_rules!.length) {
const regionId = p.price_rules![0].value const regionId = p.price_rules![0].value
ret[regionId] = getPresentationalAmount( ret[regionId] = castNumber(p.amount)
p.amount as number,
p.currency_code!
)
} }
}) })
@@ -145,7 +136,7 @@ export function EditShippingOptionsPricingForm({
return undefined return undefined
} }
const amount = getDbAmount(Number(value), code) const amount = castNumber(value)
const priceRecord = { const priceRecord = {
currency_code: code, currency_code: code,
@@ -12,7 +12,6 @@ import {
} from "../../../../../components/route-modal" } from "../../../../../components/route-modal"
import { useCreatePriceList } from "../../../../../hooks/api/price-lists" import { useCreatePriceList } from "../../../../../hooks/api/price-lists"
import { castNumber } from "../../../../../lib/cast-number" import { castNumber } from "../../../../../lib/cast-number"
import { getDbAmount } from "../../../../../lib/money-amount-helpers"
import { PricingDetailsForm } from "./pricing-details-form" import { PricingDetailsForm } from "./pricing-details-form"
import { PricingPricesForm } from "./pricing-prices-form" import { PricingPricesForm } from "./pricing-prices-form"
import { PricingProductsForm } from "./pricing-products-form" import { PricingProductsForm } from "./pricing-products-form"
@@ -89,10 +88,7 @@ export const PricingCreateForm = () => {
} }
prices.push({ prices.push({
amount: getDbAmount( amount: castNumber(currencyPrice.amount),
castNumber(currencyPrice.amount),
currencyCode
),
currency_code: currencyCode, currency_code: currencyCode,
// @ts-expect-error type is wrong // @ts-expect-error type is wrong
variant_id: variantId, variant_id: variantId,
@@ -127,13 +123,10 @@ export const PricingCreateForm = () => {
) => { ) => {
form.clearErrors(fields) form.clearErrors(fields)
const values = fields.reduce( const values = fields.reduce((acc, key) => {
(acc, key) => { acc[key] = form.getValues(key)
acc[key] = form.getValues(key) return acc
return acc }, {} as Record<string, unknown>)
},
{} as Record<string, unknown>
)
const validationResult = schema.safeParse(values) const validationResult = schema.safeParse(values)
@@ -23,10 +23,6 @@ import {
} from "../../../../../hooks/api/price-lists" } from "../../../../../hooks/api/price-lists"
import { useStore } from "../../../../../hooks/api/store" import { useStore } from "../../../../../hooks/api/store"
import { castNumber } from "../../../../../lib/cast-number" import { castNumber } from "../../../../../lib/cast-number"
import {
getDbAmount,
getPresentationalAmount,
} from "../../../../../lib/money-amount-helpers"
import { ExtendedProductDTO } from "../../../../../types/api-responses" import { ExtendedProductDTO } from "../../../../../types/api-responses"
import { usePriceListGridColumns } from "../../../common/hooks/use-price-list-grid-columns" import { usePriceListGridColumns } from "../../../common/hooks/use-price-list-grid-columns"
import { import {
@@ -268,13 +264,8 @@ function initDefaultValues(
variants[variant.id] = { variants[variant.id] = {
currency_prices: currencyPrices.reduce( currency_prices: currencyPrices.reduce(
(prices, { currency_code, amount, id }) => { (prices, { currency_code, amount, id }) => {
const presentationAmount = getPresentationalAmount(
amount,
currency_code
).toString()
prices[currency_code] = { prices[currency_code] = {
amount: presentationAmount, amount: amount.toString(),
id, id,
} }
return prices return prices
@@ -350,15 +341,14 @@ function sortPrices(
// If the price has not changed, we don't need to update it // If the price has not changed, we don't need to update it
if ( if (
originalPrice && originalPrice &&
originalPrice.amount === originalPrice.amount === castNumber(currencyPrice.amount)
getDbAmount(castNumber(currencyPrice.amount), currencyCode)
) { ) {
continue continue
} }
pricesToUpdate.push({ pricesToUpdate.push({
id: currencyPrice.id, id: currencyPrice.id,
amount: getDbAmount(castNumber(currencyPrice.amount), currencyCode), amount: castNumber(currencyPrice.amount),
currency_code: currencyCode, currency_code: currencyCode,
// @ts-expect-error type is wrong // @ts-expect-error type is wrong
variant_id: variantId, variant_id: variantId,
@@ -374,7 +364,7 @@ function sortPrices(
if (!currencyPrice.id && currencyPrice.amount) { if (!currencyPrice.id && currencyPrice.amount) {
pricesToCreate.push({ pricesToCreate.push({
amount: getDbAmount(castNumber(currencyPrice.amount), currencyCode), amount: castNumber(currencyPrice.amount),
currency_code: currencyCode, currency_code: currencyCode,
// @ts-expect-error type is wrong // @ts-expect-error type is wrong
variant_id: variantId, variant_id: variantId,
@@ -1,7 +1,6 @@
import { CreateProductDTO } from "@medusajs/types" import { CreateProductDTO } from "@medusajs/types"
import { ProductCreateSchemaType } from "./types" import { ProductCreateSchemaType } from "./types"
import { getDbAmount } from "../../../lib/money-amount-helpers.ts" import { castNumber } from "../../../lib/cast-number"
import { castNumber } from "../../../lib/cast-number.ts"
export const normalizeProductFormValues = ( export const normalizeProductFormValues = (
values: ProductCreateSchemaType & { status: CreateProductDTO["status"] } values: ProductCreateSchemaType & { status: CreateProductDTO["status"] }
@@ -64,7 +63,7 @@ export const normalizeVariants = (
} else { } else {
return { return {
currency_code: key, currency_code: key,
amount: getDbAmount(castNumber(value), key), amount: castNumber(value),
} }
} }
}) })
@@ -7,11 +7,7 @@ import { RouteFocusModal, useRouteModal } from "../../../components/route-modal"
import { useUpdateProductVariantsBatch } from "../../../hooks/api/products" import { useUpdateProductVariantsBatch } from "../../../hooks/api/products"
import { ExtendedProductDTO } from "../../../types/api-responses" import { ExtendedProductDTO } from "../../../types/api-responses"
import { VariantPricingForm } from "../common/variant-pricing-form" import { VariantPricingForm } from "../common/variant-pricing-form"
import { import { castNumber } from "../../../lib/cast-number"
getDbAmount,
getPresentationalAmount,
} from "../../../lib/money-amount-helpers.ts"
import { castNumber } from "../../../lib/cast-number.ts"
export const UpdateVariantPricesSchema = zod.object({ export const UpdateVariantPricesSchema = zod.object({
variants: zod.array( variants: zod.array(
@@ -35,10 +31,7 @@ export const PricingEdit = ({ product }: { product: ExtendedProductDTO }) => {
variants: product.variants.map((variant: any) => ({ variants: product.variants.map((variant: any) => ({
title: variant.title, title: variant.title,
prices: variant.prices.reduce((acc: any, price: any) => { prices: variant.prices.reduce((acc: any, price: any) => {
acc[price.currency_code] = getPresentationalAmount( acc[price.currency_code] = price.amount
price.amount,
price.currency_code
)
return acc return acc
}, {}), }, {}),
})) as any, })) as any,
@@ -57,7 +50,7 @@ export const PricingEdit = ({ product }: { product: ExtendedProductDTO }) => {
prices: Object.entries(variant.prices || {}).map( prices: Object.entries(variant.prices || {}).map(
([key, value]: any) => ({ ([key, value]: any) => ({
currency_code: key, currency_code: key,
amount: getDbAmount(castNumber(value), key), amount: castNumber(value),
}) })
), ),
})), })),