fix(region): Soft deleting region unsets region on countries (#7786)

**What**

Unset `region_id` on countries when soft deleting the associated region. Otherwise, countries cannot be added to new or other regions

Alternatively, we hard delete the region, which will trigger the DB level cascade

In both cases, we cannot easily restore the region countries.
This commit is contained in:
Oli Juhl authored and GitHub committed 2024-06-26 16:44:16 +00:00
1 parent 5ee97d0e97
commit b5f248f154
2 files changed
+44 -1

No files matched your search

@@ -1,6 +1,6 @@
import { IRegionModuleService } from "@medusajs/types" import { IRegionModuleService } from "@medusajs/types"
import { moduleIntegrationTestRunner } from "medusa-test-utils"
import { Modules } from "@medusajs/utils" import { Modules } from "@medusajs/utils"
import { moduleIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(30000) jest.setTimeout(30000)
@@ -368,6 +368,28 @@ moduleIntegrationTestRunner<IRegionModuleService>({
expect(resp.countries).toHaveLength(2) expect(resp.countries).toHaveLength(2)
}) })
it("should unset the region ID on the country when soft deleting a region", async () => {
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
await service.softDeleteRegions([createdRegion.id])
const newRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
const resp = await service.retrieveRegion(newRegion.id, {
relations: ["countries"],
})
expect(resp.countries).toHaveLength(2)
})
}) })
}, },
}) })
@@ -9,6 +9,7 @@ import {
ModulesSdkTypes, ModulesSdkTypes,
RegionCountryDTO, RegionCountryDTO,
RegionDTO, RegionDTO,
SoftDeleteReturn,
UpdateRegionDTO, UpdateRegionDTO,
UpsertRegionDTO, UpsertRegionDTO,
} from "@medusajs/types" } from "@medusajs/types"
@@ -129,6 +130,26 @@ export default class RegionModuleService
return result return result
} }
@InjectManager("baseRepository_")
// @ts-ignore
async softDeleteRegions(
ids: string | object | string[] | object[],
config?: SoftDeleteReturn<string>,
@MedusaContext() sharedContext: Context = {}
): Promise<Record<string, string[]> | void> {
const result = await super.softDeleteRegions(ids, config, sharedContext)
// Note: You cannot revert the state of a region by simply restoring it. The association with countries is lost.
await super.updateCountries(
{
selector: { region_id: ids },
data: { region_id: null },
},
sharedContext
)
return result
}
async upsertRegions( async upsertRegions(
data: UpsertRegionDTO[], data: UpsertRegionDTO[],
sharedContext?: Context sharedContext?: Context