fix(medusa): Proper fix of the cart service

This commit is contained in:
adrien2p
2022-05-06 10:31:02 +02:00
parent 32a65d27fc
commit f5edaf51ea
2 changed files with 22 additions and 31 deletions

View File

@@ -276,7 +276,7 @@ describe("CartService", () => {
expect(cartRepository.save).toHaveBeenCalledTimes(1)
})
it("successfully creates a cart with a shipping address id", async () => {
it("successfully creates a cart with a shipping address id but no shippings_address", async () => {
await cartService.create({
region_id: IdMap.getId("testRegion"),
email: "email@test.com",
@@ -309,7 +309,7 @@ describe("CartService", () => {
expect(cartRepository.save).toHaveBeenCalledTimes(1)
})
it("creates a cart with a prefilled shipping address", async () => {
it("creates a cart with a prefilled shipping address but a country not part of the region", async () => {
const res = cartService.create({
region_id: IdMap.getId("testRegion"),
shipping_address: {

View File

@@ -393,41 +393,32 @@ class CartService extends BaseService {
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 (!rawCart.shipping_address && region.countries.length === 1) {
// Preselect the country if the region only has 1
// and create address entity
if (!data.shipping_address && !data.shipping_address_id) {
if (region.countries.length === 1) {
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 = addr
}
rawCart.shipping_address = data.shipping_address
}
const remainingFields: (keyof Cart)[] = [