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(core-flows,types,utils): make payment optional when cart balance is 0 #11792

Open
wants to merge 1 commit into
base: feat/customer-address
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
53 changes: 50 additions & 3 deletions integration-tests/http/__tests__/cart/store/cart.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1085,7 +1085,9 @@ medusaIntegrationTestRunner({
{ option_id: shippingOption.id },
storeHeaders
)
})

it("should successfully complete cart", async () => {
const paymentCollection = (
await api.post(
`/store/payment-collections`,
Expand All @@ -1099,9 +1101,7 @@ medusaIntegrationTestRunner({
{ provider_id: "pp_system_default" },
storeHeaders
)
})

it("should successfully complete cart", async () => {
createCartCreditLinesWorkflow.run({
input: [
{
Expand Down Expand Up @@ -1144,6 +1144,53 @@ medusaIntegrationTestRunner({
)
})

it("should successfully complete cart with credit lines alone", async () => {
const oldCart = (
await api.get(`/store/carts/${cart.id}`, storeHeaders)
).data.cart

createCartCreditLinesWorkflow.run({
input: [
{
cart_id: oldCart.id,
amount: oldCart.total,
currency_code: "usd",
reference: "test",
reference_id: "test",
},
],
container: appContainer,
})

const response = await api.post(
`/store/carts/${cart.id}/complete`,
{},
storeHeaders
)

expect(response.status).toEqual(200)
expect(response.data.order).toEqual(
expect.objectContaining({
id: expect.any(String),
currency_code: "usd",
credit_lines_total: 2395,
discount_total: 100,
credit_lines: [
expect.objectContaining({
amount: 2395,
}),
],
items: expect.arrayContaining([
expect.objectContaining({
unit_price: 1500,
compare_at_unit_price: null,
quantity: 1,
}),
]),
})
)
})

it("should successfully complete cart without shipping for digital products", async () => {
/**
* Product has a shipping profile so cart item should not require shipping
Expand Down Expand Up @@ -1181,7 +1228,7 @@ medusaIntegrationTestRunner({
)
).data.product

let cart = (
cart = (
await api.post(
`/store/carts`,
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CartWorkflowDTO } from "@medusajs/framework/types"
import {
isPresent,
MathBN,
MedusaError,
PaymentSessionStatus,
} from "@medusajs/framework/utils"
Expand All @@ -20,13 +21,13 @@ export const validateCartPaymentsStepId = "validate-cart-payments"
/**
* This step validates a cart's payment sessions. Their status must
* be `pending` or `requires_more`. If not valid, the step throws an error.
*
*
* :::tip
*
*
* You can use the {@link retrieveCartStep} to retrieve a cart's details.
*
*
* :::
*
*
* @example
* const data = validateCartPaymentsStep({
* // retrieve the details of the cart from another workflow
Expand All @@ -38,9 +39,20 @@ export const validateCartPaymentsStep = createStep(
validateCartPaymentsStepId,
async (data: ValidateCartPaymentsStepInput) => {
const {
cart: { payment_collection: paymentCollection },
cart: {
payment_collection: paymentCollection,
total,
credit_lines_total,
},
} = data

const canSkipPayment =
MathBN.convert(credit_lines_total).gte(0) && MathBN.convert(total).lte(0)

if (canSkipPayment) {
return new StepResponse([])
}

if (!isPresent(paymentCollection)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
Expand Down
37 changes: 24 additions & 13 deletions packages/core/core-flows/src/cart/workflows/complete-cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,16 @@ export const completeCartWorkflow = createWorkflow(

const cartToOrder = transform({ cart, payment }, ({ cart, payment }) => {
const transactions =
payment?.captures?.map((capture) => {
return {
amount: capture.raw_amount ?? capture.amount,
currency_code: payment.currency_code,
reference: "capture",
reference_id: capture.id,
}
}) ?? []
(payment &&
payment?.captures?.map((capture) => {
return {
amount: capture.raw_amount ?? capture.amount,
currency_code: payment.currency_code,
reference: "capture",
reference_id: capture.id,
}
})) ??
[]

const allItems = (cart.items ?? []).map((item) => {
const input: PrepareLineItemDataInput = {
Expand Down Expand Up @@ -282,19 +284,28 @@ export const completeCartWorkflow = createWorkflow(
}
})

parallelize(
createRemoteLinkStep([
const linksToCreate = transform({ cart }, ({ cart }) => {
const links: Record<string, any>[] = [
{
[Modules.ORDER]: { order_id: createdOrder.id },
[Modules.CART]: { cart_id: cart.id },
},
{
]

if (cart.payment_collection) {
links.push({
[Modules.ORDER]: { order_id: createdOrder.id },
[Modules.PAYMENT]: {
payment_collection_id: cart.payment_collection.id,
},
},
]),
})
}

return links
})

parallelize(
createRemoteLinkStep(linksToCreate),
updateCartsStep([updateCompletedAt]),
reserveInventoryStep(formatedInventoryItems),
emitEventStep({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ export const authorizePaymentSessionStep = createStep(
Modules.PAYMENT
)

if (!input.id) {
return new StepResponse(null)
}

try {
payment = await paymentModule.authorizePaymentSession(
input.id,
Expand Down
10 changes: 10 additions & 0 deletions packages/core/types/src/cart/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,16 @@ export interface CartDTO {
* The raw original shipping tax total of the cart.
*/
raw_original_shipping_tax_total: BigNumberRawValue

/**
* The raw credit lines total of the cart.
*/
raw_credit_lines_total: BigNumberRawValue

/**
* The credit lines total of the cart.
*/
credit_lines_total: BigNumberValue
}

/**
Expand Down
4 changes: 1 addition & 3 deletions packages/core/utils/src/totals/cart/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,6 @@ export function decorateCartTotals(
taxRate: creditLinesSumTaxRate,
})

subtotal = MathBN.sub(subtotal, creditLinesSubtotal)

const taxTotal = MathBN.add(itemsTaxTotal, shippingTaxTotal)

const originalTaxTotal = MathBN.add(
Expand All @@ -222,7 +220,7 @@ export function decorateCartTotals(

// TODO: subtract (cart.gift_card_total + cart.gift_card_tax_total)
const tempTotal = MathBN.add(subtotal, taxTotal)
const total = MathBN.sub(tempTotal, discountSubtotal)
const total = MathBN.sub(tempTotal, discountSubtotal, creditLinesTotal)

const cart = cartLike as any

Expand Down