Merge pull request #1475 from medusajs/fix-cartServiceCreateLostShippingAddress

This commit is contained in:
Adrien de Peretti
2022-05-11 22:02:24 +02:00
committed by GitHub
5 changed files with 42 additions and 48 deletions
+17 -3
View File
@@ -204,7 +204,21 @@ describe("CartService", () => {
},
}
const addressRepository = MockRepository({ create: (c) => c })
const addressRepository = MockRepository({
create: (c) => c,
findOne: (id) => {
return {
id,
first_name: "LeBron",
last_name: "James",
address_1: "Dunk St",
city: "Dunkville",
province: "CA",
postal_code: "12345",
country_code: "us",
}
}
})
const cartRepository = MockRepository()
const customerService = {
retrieveByEmail: jest.fn().mockReturnValue(
@@ -262,7 +276,7 @@ describe("CartService", () => {
expect(cartRepository.save).toHaveBeenCalledTimes(1)
})
it("creates a cart with a prefilled shipping address", async () => {
it("should throw shipping country not in region", async () => {
const res = cartService.create({
region_id: IdMap.getId("testRegion"),
shipping_address: {
@@ -279,7 +293,7 @@ describe("CartService", () => {
await expect(res).rejects.toThrow("Shipping country not in region")
})
it("creates a cart with a prefilled shipping address", async () => {
it("a cart with a prefilled shipping address", async () => {
await cartService.create({
region_id: IdMap.getId("testRegion"),
shipping_address: {
+19 -28
View File
@@ -362,41 +362,32 @@ class CartService extends TransactionBaseService<CartService> {
rawCart.region_id = region.id
if (data.shipping_address_id !== undefined) {
const shippingAddress = data.shipping_address_id
? await addressRepo.findOne(data.shipping_address_id)
: null
if (
shippingAddress &&
!regCountries.includes(shippingAddress.country_code)
) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Shipping country not in region"
)
}
rawCart.shipping_address = shippingAddress
}
if (!data.shipping_address) {
if (!data.shipping_address && !data.shipping_address_id) {
if (region.countries.length === 1) {
// Preselect the country if the region only has 1
// and create address entity
rawCart.shipping_address = addressRepo.create({
country_code: regCountries[0],
})
}
} else {
if (!regCountries.includes(data.shipping_address.country_code)) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Shipping country not in region"
)
if (data.shipping_address) {
if (!regCountries.includes(data.shipping_address.country_code)) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Shipping country not in region"
)
}
rawCart.shipping_address = data.shipping_address
}
if (data.shipping_address_id) {
const addr = await addressRepo.findOne(data.shipping_address_id)
if (addr && !regCountries.includes(addr.country_code)) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Shipping country not in region"
)
}
rawCart.shipping_address_id = data.shipping_address_id
}
rawCart.shipping_address = data.shipping_address
}
const remainingFields: (keyof Cart)[] = [