Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add BigNumber implementation #6253

Merged
merged 36 commits into from
Feb 9, 2024
Merged

feat: Add BigNumber implementation #6253

merged 36 commits into from
Feb 9, 2024

Conversation

olivermrbl
Copy link
Contributor

@olivermrbl olivermrbl commented Jan 29, 2024

This is a proposal - not necessarily the end result - to kick off the discussion about the implementation of the new totals utilities

What

Introduces a BigNumber class implementation, enabling us to work with high-precision numeric values.

Scope

  • Introduce the BigNumber class
  • Remain somewhat backward-compatible (in behavior)
  • Establish a foundation for handling high-precision values in more complex scenarios

Not in scope

  • The implementation will not address complex use cases. However, the concept introduced now should be open for extensibility, so this can be added later without major changes to the calculation logic

How

There are significant changes to three areas in this PR:

  • Schemas
  • (De)-Serialization
  • Totals calculations

Schemas

Domains that need high-precision values will have two DB columns for each value in the database: a standard numeric column and a raw value column.

The standard column is for basic operations like sorting and filtering in the database and is what should be publicly exposed in our API.

The raw value is initially used solely for precise calculations and is stored as a JSONB column. Keeping it as JSONB is flexible and will allow us to extend the concept in future iterations. As of now, the raw value will only require a single property value.

(De)-Serialization

We cast the raw JSONB value to a BigNumberRawValue when reading from the database.

We serialize the standard value to a BigNumber when reading from the database.

We use the standard numeric value to construct the raw value upon writing to the database.

For example, the unit price and raw unit price on line items will be inserted as follows:

@BeforeCreate()
onCreate() {
  this.id = generateEntityId(this.id, "cali")
  
  const asBigNumber = new BigNumber(this.raw_unit_price ?? this.unit_price)
  
  this.unit_price = asBigNumber.numeric
  this.raw_unit_price = asBigNumber.raw
}

Totals calculations

For totals calculations, we will use the bignumber.js library. The library ships with a BigNumber class with arithmetic methods for precise calculations.

When we need to perform a calculation, we construct the BigNumber class from the library using the raw value from the database.

Let's have a look at an oversimplified example:

// create cart with line items
const [createdCart] = await service.create([
  {
    currency_code: "eur",
    items: [
      // li_1234
      {
        title: "test",
        quantity: 2,
        unit_price: 100,
      },
      // li_4321
      {
        title: "test",
        quantity: 3,
        // raw price creation
        unit_price: 200,
      },
    ],
  },
])
// calculating line item totals
import BN from "bignumber.js"

const lineItem1 = await service.retrieveLineItem("li_1234")
const lineItem2 = await service.retrieveLineItem("li_4321")

const bnUnitPrice1 = new BN(lineItem1.unit_price.raw)
const bnUnitPrice2 = new BN(lineItem2.unit_price.raw)

const line1Total = bnUnitPrice1.multipliedBy(lineItem1.quantity)
const line2Total = bnUnitPrice2.multipliedBy(lineItem2.quantity)

const total = line1Total.plus(line2Total)

A note on backward compatibility
Our BigNumber implementation is built to support the existing behavior of numeric values in the database. So even though we serialize the value to a BigNumber, you will still be able to treat it as a standard number, as we've always done.

For example, the following works perfectly fine:

const lineItem = await service.createLineItem({
  title: "test",
  quantity: 2,
  unit_price: 100,
})

console.log(lineItem.unit_price) // will print `100`

However, the type of unit_price will be number | BigNumber.

Copy link

changeset-bot bot commented Jan 29, 2024

⚠️ No Changeset found

Latest commit: b7c91fd

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Jan 29, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
medusa-dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 9, 2024 10:26am
3 Ignored Deployments
Name Status Preview Comments Updated (UTC)
api-reference ⬜️ Ignored (Inspect) Feb 9, 2024 10:26am
docs-ui ⬜️ Ignored (Inspect) Visit Preview Feb 9, 2024 10:26am
medusa-docs ⬜️ Ignored (Inspect) Visit Preview Feb 9, 2024 10:26am

Copy link
Contributor

@carlos-r-l-rodrigues carlos-r-l-rodrigues left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amazing 🔥

Comment on lines +152 to +155
const val = new BigNumber(this.raw_unit_price ?? this.unit_price)

this.unit_price = val.numeric
this.raw_unit_price = val.raw!
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe we can create a util to do that for 1 or N fields.

modelToBigNumber(this, "unit_price")
or
modelToBigNumber(this, ["unit_price", "quantity"])

subliminal suggestion to set quantity as BigNumber 😆

packages/utils/src/totals/index.ts Outdated Show resolved Hide resolved
@olivermrbl olivermrbl changed the title [proposal] feat: Add BigNumber implementation feat: Add BigNumber implementation Feb 2, 2024
@kodiakhq kodiakhq bot merged commit 94062d2 into develop Feb 9, 2024
17 checks passed
@kodiakhq kodiakhq bot deleted the feat/bignumber branch February 9, 2024 10:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants