fix(medusa): cart to be created with a country code (#2197)

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Sebastian Rindom
2022-09-13 21:19:06 +02:00
committed by GitHub
parent 3767cf26f7
commit eb3b02baf4
2 changed files with 43 additions and 18 deletions

View File

@@ -0,0 +1,5 @@
---
"@medusajs/medusa": patch
---
Create cart with country code in shipping address

View File

@@ -1,4 +1,7 @@
import { CartService, LineItemService, RegionService } from "../../../../services"
import { EntityManager } from "typeorm"
import { MedusaError } from "medusa-core-utils"
import reqIp from "request-ip"
import { Type } from "class-transformer"
import {
IsArray,
IsInt,
@@ -7,18 +10,20 @@ import {
IsString,
ValidateNested,
} from "class-validator"
import { defaultStoreCartFields, defaultStoreCartRelations, } from "."
import { Cart } from "../../../../models";
import { EntityManager } from "typeorm"
import { FeatureFlagDecorators } from "../../../../utils/feature-flag-decorators";
import {
CartService,
LineItemService,
RegionService,
} from "../../../../services"
import { defaultStoreCartFields, defaultStoreCartRelations } from "."
import { Cart } from "../../../../models"
import { FeatureFlagDecorators } from "../../../../utils/feature-flag-decorators"
import { FlagRouter } from "../../../../utils/flag-router"
import { MedusaError } from "medusa-core-utils"
import SalesChannelFeatureFlag from "../../../../loaders/feature-flags/sales-channels";
import { Type } from "class-transformer"
import SalesChannelFeatureFlag from "../../../../loaders/feature-flags/sales-channels"
import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals"
import reqIp from "request-ip"
import { isDefined } from "../../../../utils";
import { CartCreateProps } from "../../../../types/cart"
import { isDefined } from "../../../../utils"
/**
* @oas [post] /carts
@@ -131,16 +136,31 @@ export default async (req, res) => {
regionId = regions[0].id
}
const toCreate: Partial<CartCreateProps> = {
region_id: regionId,
sales_channel_id: validated.sales_channel_id,
context: {
...reqContext,
...validated.context,
},
}
if (req.user && req.user.customer_id) {
const customerService = req.scope.resolve("customerService")
const customer = await customerService.retrieve(req.user.customer_id)
toCreate["customer_id"] = customer.id
toCreate["email"] = customer.email
}
if (validated.country_code) {
toCreate["shipping_address"] = {
country_code: validated.country_code.toLowerCase(),
}
}
let cart: Cart
await entityManager.transaction(async (manager) => {
cart = await cartService.withTransaction(manager).create({
...validated,
context: {
...reqContext,
...validated.context,
},
region_id: regionId,
})
cart = await cartService.withTransaction(manager).create(toCreate)
if (validated.items) {
await Promise.all(