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
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
cb8dd58
wo
olivermrbl Jan 23, 2024
39da2ee
wip use raw
olivermrbl Jan 23, 2024
e091c23
init testing
olivermrbl Jan 23, 2024
023e9f5
resolve conflicts
olivermrbl Jan 24, 2024
bf7a176
tes
olivermrbl Jan 24, 2024
5d539fa
add bignum calcs
olivermrbl Jan 25, 2024
a274fd8
feat: BigNumber support
olivermrbl Jan 25, 2024
289dd81
fix module
olivermrbl Jan 25, 2024
65836ec
revert changes in payment
olivermrbl Jan 25, 2024
01912bc
add bignum file
olivermrbl Jan 25, 2024
bb01f99
fix precision
olivermrbl Jan 25, 2024
2fcc3ed
Slim down bignum
olivermrbl Jan 25, 2024
1f21e56
Slim down bignum
olivermrbl Jan 25, 2024
08871b1
add test
olivermrbl Jan 26, 2024
82ecc04
remove bignum-precision.rs
olivermrbl Jan 28, 2024
aca7b68
Rename file
olivermrbl Jan 28, 2024
2838450
clean up
olivermrbl Jan 28, 2024
fe2d325
remove irrelevant test
olivermrbl Jan 28, 2024
4232740
fix db hook
olivermrbl Jan 28, 2024
234ef3d
wip: onUpdate
olivermrbl Jan 28, 2024
ea5db56
serialize
olivermrbl Jan 29, 2024
26f7bd1
clean
olivermrbl Jan 29, 2024
fe4175c
clean up
olivermrbl Jan 30, 2024
9e51796
resolve conflicts
olivermrbl Jan 30, 2024
420ea4d
remove onloads
olivermrbl Jan 30, 2024
3c2030c
add line item subtotal
olivermrbl Feb 1, 2024
b556f1f
use raw values
olivermrbl Feb 1, 2024
32ca8cc
update approach
olivermrbl Feb 1, 2024
3df796c
util + clean up
olivermrbl Feb 1, 2024
e94bbaf
add util
olivermrbl Feb 2, 2024
b717c3c
camelize
olivermrbl Feb 2, 2024
292b6e3
merge conflicts
olivermrbl Feb 2, 2024
921da4f
resolve conflicts
olivermrbl Feb 2, 2024
1e2d410
remove unused file
olivermrbl Feb 2, 2024
a9f3308
Update migration
olivermrbl Feb 2, 2024
b7c91fd
Merge branch 'develop' into feat/bignumber
olivermrbl Feb 9, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,55 @@ describe("Cart Module Service", () => {
)
})

it.only("should create a line item with prices in different shapes", async () => {
// TODO: Will be removed. This is here for demoing purposes
const [createdCart] = await service.create([
{
currency_code: "eur",
items: [
{
title: "one",
quantity: 1,
// proof of backward compatibility
unit_price: 100,
},
// {
// title: "two",
// quantity: 1,
// // raw price creation
// unit_price: { value: "1234.1234" },
// },
{
title: "three",
quantity: 1,
// string price creation
unit_price: "200",
},
],
},
])

const cart = await service.retrieve(createdCart.id, {
relations: ["items", "items.adjustments"],
})

const itemOne = cart.items?.find((el) => el.title === "one")
const itemThree = cart.items?.find((el) => el.title === "three")

expect(JSON.parse(JSON.stringify(itemOne))).toEqual(
expect.objectContaining({
unit_price: 100,
title: "one",
})
)
expect(JSON.parse(JSON.stringify(itemThree))).toEqual(
expect.objectContaining({
unit_price: 200,
title: "three",
})
)
})

it("should create a cart successfully", async () => {
const [createdCart] = await service.create([
{
Expand Down Expand Up @@ -481,14 +530,14 @@ describe("Cart Module Service", () => {
const error = await service
.addLineItems(createdCart.id, [
{
quantity: 1,
unit_price: 10,
title: "test",
},
] as any)
.catch((e) => e)

expect(error.message).toContain(
"Value for LineItem.unit_price is required, 'undefined' found"
"Value for LineItem.quantity is required, 'undefined' found"
)
})

Expand All @@ -503,14 +552,14 @@ describe("Cart Module Service", () => {
.addLineItems([
{
cart_id: createdCart.id,
quantity: 1,
unit_price: 10,
title: "test",
},
] as any)
.catch((e) => e)

expect(error.message).toContain(
"Value for LineItem.unit_price is required, 'undefined' found"
"Value for LineItem.quantity is required, 'undefined' found"
)
})
})
Expand Down
38 changes: 30 additions & 8 deletions packages/cart/src/models/line-item.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { DAL } from "@medusajs/types"
import { generateEntityId } from "@medusajs/utils"
import { BigNumberRawValue, DAL } from "@medusajs/types"
import { BigNumber, generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
BeforeUpdate,
Cascade,
Check,
Collection,
Entity,
ManyToOne,
Expand Down Expand Up @@ -109,12 +109,16 @@ export default class LineItem {
is_tax_inclusive = false

@Property({ columnType: "numeric", nullable: true })
compare_at_unit_price: number | null = null
compare_at_unit_price?: BigNumber | number | null = null

// TODO: Rework when BigNumber has been introduced
@Property({ columnType: "numeric", serializer: Number })
@Check({ expression: "unit_price >= 0" }) // TODO: Validate that numeric types work with the expression
unit_price: number
@Property({ columnType: "jsonb", nullable: true })
raw_compare_at_unit_price: BigNumberRawValue | null = null

@Property({ columnType: "numeric" })
unit_price: BigNumber | number
olivermrbl marked this conversation as resolved.
Show resolved Hide resolved

@Property({ columnType: "jsonb" })
raw_unit_price: BigNumberRawValue

@OneToMany(() => LineItemTaxLine, (taxLine) => taxLine.item, {
cascade: [Cascade.REMOVE],
Expand Down Expand Up @@ -144,10 +148,28 @@ export default class LineItem {
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "cali")

const val = new BigNumber(this.raw_unit_price ?? this.unit_price)

this.unit_price = val.numeric
this.raw_unit_price = val.raw!
Comment on lines +152 to +155
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 😆

}

@BeforeUpdate()
onUpdate() {
const val = new BigNumber(this.raw_unit_price ?? this.unit_price)

this.unit_price = val.numeric
this.raw_unit_price = val.raw as BigNumberRawValue
}

@OnInit()
onInit() {
this.id = generateEntityId(this.id, "cali")

const val = new BigNumber(this.raw_unit_price ?? this.unit_price)

this.unit_price = val.numeric
this.raw_unit_price = val.raw!
}
}
29 changes: 26 additions & 3 deletions packages/cart/src/models/shipping-method.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { generateEntityId } from "@medusajs/utils"
import { BigNumberRawValue } from "@medusajs/types"
import { BigNumber, generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Cascade,
Expand All @@ -11,6 +12,7 @@ import {
PrimaryKey,
Property,
} from "@mikro-orm/core"
import { BeforeUpdate } from "typeorm"
import Cart from "./cart"
import ShippingMethodAdjustment from "./shipping-method-adjustment"
import ShippingMethodTaxLine from "./shipping-method-tax-line"
Expand All @@ -37,8 +39,11 @@ export default class ShippingMethod {
@Property({ columnType: "jsonb", nullable: true })
description: string | null = null

@Property({ columnType: "numeric", serializer: Number })
amount: number
@Property({ columnType: "numeric" })
amount: BigNumber | number

@Property({ columnType: "jsonb" })
raw_amount: BigNumberRawValue

@Property({ columnType: "boolean" })
is_tax_inclusive = false
Expand Down Expand Up @@ -92,10 +97,28 @@ export default class ShippingMethod {
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "casm")

const val = new BigNumber(this.raw_amount ?? this.amount)

this.amount = val.numeric
this.raw_amount = val.raw!
}

@BeforeUpdate()
onUpdate() {
const val = new BigNumber(this.raw_amount ?? this.amount)

this.amount = val.numeric
this.raw_amount = val.raw as BigNumberRawValue
}

@OnInit()
onInit() {
this.id = generateEntityId(this.id, "casm")

const val = new BigNumber(this.raw_amount ?? this.amount)

this.amount = val.numeric
this.raw_amount = val.raw!
}
}
21 changes: 18 additions & 3 deletions packages/cart/src/services/cart-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
InjectTransactionManager,
MedusaContext,
MedusaError,
decorateCartTotals,
isObject,
isString,
} from "@medusajs/utils"
Expand Down Expand Up @@ -86,12 +87,26 @@ export default class CartModuleService implements ICartModuleService {
id: string,
config: FindConfig<CartTypes.CartDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.CartDTO> {
// TODO: Will be reworked. This is here for demoing purposes
return this.retrieveWithTotals(id, config, sharedContext)
}

// TODO: Will be reworked. This is here for demoing purposes
@InjectManager("baseRepository_")
async retrieveWithTotals(
id: string,
config: FindConfig<CartTypes.CartDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.CartDTO> {
const cart = await this.cartService_.retrieve(id, config, sharedContext)

return await this.baseRepository_.serialize<CartTypes.CartDTO>(cart, {
populate: true,
})
const serialized = await this.baseRepository_.serialize<CartTypes.CartDTO>(
cart,
{ populate: true }
)

return decorateCartTotals(serialized)
}

@InjectManager("baseRepository_")
Expand Down
4 changes: 3 additions & 1 deletion packages/cart/src/services/line-item.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { DAL } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import {
ModulesSdkUtils
} from "@medusajs/utils"
import { LineItem } from "@models"
import { CreateLineItemDTO, UpdateLineItemDTO } from "@types"

Expand Down
2 changes: 1 addition & 1 deletion packages/cart/src/types/line-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ interface PartialUpsertLineItemDTO {
export interface CreateLineItemDTO extends PartialUpsertLineItemDTO {
title: string
quantity: number
unit_price: number
unit_price: number | string
cart_id: string
}

Expand Down
10 changes: 5 additions & 5 deletions packages/medusa/src/services/new-totals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export default class NewTotalsService extends TransactionBaseService {

/**
* Calculate and return the items totals for either the legacy calculation or the new calculation
* @param items
* @param param1
* @param items
* @param param1
*/
async getLineItemTotals(
items: LineItem | LineItem[],
Expand Down Expand Up @@ -136,9 +136,9 @@ export default class NewTotalsService extends TransactionBaseService {

/**
* Calculate and return the totals for an item
* @param item
* @param param1
* @returns
* @param item
* @param param1
* @returns
*/
protected async getLineItemTotals_(
item: LineItem,
Expand Down
3 changes: 1 addition & 2 deletions packages/payment/src/models/capture.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Entity,
Expand All @@ -7,8 +8,6 @@ import {
PrimaryKey,
Property,
} from "@mikro-orm/core"

import { generateEntityId } from "@medusajs/utils"
import Payment from "./payment"

type OptionalCaptureProps = "created_at"
Expand Down
36 changes: 21 additions & 15 deletions packages/types/src/cart/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,23 @@ export interface CartShippingMethodDTO {
discount_tax_total: number
}

export interface CartLineItemDTO {
export interface CartLineItemTotalsDTO {
original_total: number
original_subtotal: number
original_tax_total: number

item_total: number
item_subtotal: number
item_tax_total: number

total: number
subtotal: number
tax_total: number
discount_total: number
discount_tax_total: number
}

export interface CartLineItemDTO extends CartLineItemTotalsDTO {
/**
* The ID of the line item.
*/
Expand Down Expand Up @@ -384,20 +400,6 @@ export interface CartLineItemDTO {
* When the line item was updated.
*/
updated_at?: Date

original_total: number
original_subtotal: number
original_tax_total: number

item_total: number
item_subtotal: number
item_tax_total: number

total: number
subtotal: number
tax_total: number
discount_total: number
discount_tax_total: number
}

export interface CartDTO {
Expand Down Expand Up @@ -478,8 +480,12 @@ export interface CartDTO {
subtotal: number
tax_total: number
discount_total: number
raw_discount_total: any
discount_tax_total: number

gift_card_total: number
gift_card_tax_total: number

shipping_total: number
shipping_subtotal: number
shipping_tax_total: number
Expand Down
2 changes: 1 addition & 1 deletion packages/types/src/cart/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export interface CreateLineItemDTO {
is_tax_inclusive?: boolean

compare_at_unit_price?: number
unit_price: number
unit_price: number | string

tax_lines?: CreateTaxLineDTO[]
adjustments?: CreateAdjustmentDTO[]
Expand Down
2 changes: 2 additions & 0 deletions packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ export * from "./sales-channel"
export * from "./search"
export * from "./shared-context"
export * from "./stock-location"
export * from "./totals"
export * from "./transaction-base"
export * from "./workflow"

4 changes: 4 additions & 0 deletions packages/types/src/totals/big-number.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type BigNumberRawValue = {
value: string | number
[key: string]: unknown
}
2 changes: 2 additions & 0 deletions packages/types/src/totals/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./big-number";

1 change: 1 addition & 0 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@mikro-orm/migrations": "5.9.7",
"@mikro-orm/postgresql": "5.9.7",
"awilix": "^8.0.1",
"bignumber.js": "^9.1.2",
"knex": "2.4.2",
"ulid": "^2.3.0"
},
Expand Down
Loading