Skip to content

Commit

Permalink
feat(tax): add endpoints to manage tax rate rules (#6557)
Browse files Browse the repository at this point in the history
**What**
Adds endpoints to manage tax rules on a tax rate:
- Create a tax rule: POST /admin/tax-rates/:id/rules 
- Delete a tax rule: DELETE /admin/tax-rates/:id/rules/:rule_id
- Replace tax rules: POST /admin/tax-rates/:id -- with { rules: [...] } in body.

### Noteworthy things I bumped into

**Updating nested relationships**
A TaxRate can have multiple TaxRules and in this PR we enable users to replace all TaxRules associated with a TaxRate in one operation. If working with the module directly this can be done with:

```javascript
taxModuleService.update(rateId, { rules: [{ ... }] })
```

Internally in the `update` function the TaxModule first soft deletes any TaxRules that exist on the TaxRate and then creates new TaxRules for the passed rules ([see test](https://github.com/medusajs/medusa/pull/6557/files#diff-cdcbab80ac7928b80648088ec57a3ab09dddd4409d6afce034f2caff08ee022bR78)).

A challenge arises when doing this in a compensatable way in a workflow. To see this imagine the following:
1. `updateTaxRatesWorkflow` gets the current data for the tax rates to update. This includes the tax rates' rules.
2. `updateTaxRatesWorkflow` calls `taxModuleService.update` with new rules. 
3. Internally, the tax module deletes the rules in 1. and creates new rules.
4. Imagine an error happens in a following step and the workflow has to compensate.
5. The workflow uses the data from 1. and calls upsert. The tax module may correctly update the previous tax rules so they are no longer soft deleted. However, upsert (at least not by default) doesn't delete the new rules that were created in 2.

As illustrated by 5. compensating the update is not pretty. To get around this I instead opted to let the workflow handle setting the rules for a rate that makes the compensation more straightforward to handle. [See workflow here](https://github.com/medusajs/medusa/pull/6557/files#diff-ff19e1f2fa32289aefff90d33c05c154f9605a3c5da6a62683071a1fcaedfd7bR89).

**Using nested workflows**
Initially, I wanted to use the `setTaxRateRulesWorkflow` within the `updateTaxRatesWorkflow`. And this worked great for the invoke phase. However, when I needed to compensate the update workflow (and hence also had to compensate the set rules workflow), I found that the workflow engine no longer had the set rules transaction in memory and therefore could not roll it back. ([This is where I try to rollback](https://github.com/medusajs/medusa/pull/6557/files#diff-ff19e1f2fa32289aefff90d33c05c154f9605a3c5da6a62683071a1fcaedfd7bR62), but the transaction id can't be found).

I therefore opted to copy the steps from the set tax rate rules workflow into the update tax rates workflow; however, once we figure out a good way to ensure we can compensate nested workflows we should move to the nested workflow instead. 

This also made me realize that the current implementation of workflows that use `refreshCartPromotions` may create inconsistencies in case of failures (cc: @riqwan).
  • Loading branch information
srindom authored Mar 4, 2024
1 parent d550be3 commit 555eb41
Show file tree
Hide file tree
Showing 25 changed files with 933 additions and 13 deletions.
135 changes: 135 additions & 0 deletions integration-tests/modules/__tests__/tax/admin/tax.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,4 +373,139 @@ describe("Taxes - Admin", () => {
expect(rates.length).toEqual(1)
expect(rates[0].deleted_at).not.toBeNull()
})

it("can create a tax rate add rules and remove them", async () => {
const api = useApi() as any
const regionRes = await api.post(
`/admin/tax-regions`,
{
country_code: "us",
default_tax_rate: { code: "default", rate: 2, name: "default rate" },
},
adminHeaders
)

const usRegionId = regionRes.data.tax_region.id
const rateRes = await api.post(
`/admin/tax-rates`,
{
tax_region_id: usRegionId,
code: "RATE2",
name: "another rate",
rate: 10,
rules: [{ reference: "product", reference_id: "prod_1234" }],
},
adminHeaders
)
const rateId = rateRes.data.tax_rate.id
let rules = await service.listTaxRateRules({ tax_rate_id: rateId })

expect(rules).toEqual([
{
id: expect.any(String),
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_1234",
created_by: "admin_user",
created_at: expect.any(Date),
updated_at: expect.any(Date),
deleted_at: null,
tax_rate: { id: rateId },
metadata: null,
},
])

await api.post(
`/admin/tax-rates/${rateId}/rules`,
{
reference: "product",
reference_id: "prod_1111",
},
adminHeaders
)

await api.post(
`/admin/tax-rates/${rateId}/rules`,
{
reference: "product",
reference_id: "prod_2222",
},
adminHeaders
)
rules = await service.listTaxRateRules({ tax_rate_id: rateId })
expect(rules).toEqual(
expect.arrayContaining([
expect.objectContaining({
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_1234",
created_by: "admin_user",
}),
expect.objectContaining({
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_1111",
created_by: "admin_user",
}),
expect.objectContaining({
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_2222",
created_by: "admin_user",
}),
])
)

const toDeleteId = rules.find((r) => r.reference_id === "prod_1111")!.id
await api.delete(
`/admin/tax-rates/${rateId}/rules/${toDeleteId}`,
adminHeaders
)

rules = await service.listTaxRateRules({ tax_rate_id: rateId })
expect(rules.length).toEqual(2)

await api.post(
`/admin/tax-rates/${rateId}`,
{
rules: [
{ reference: "product", reference_id: "prod_3333" },
{ reference: "product", reference_id: "prod_4444" },
{ reference: "product", reference_id: "prod_5555" },
{ reference: "product", reference_id: "prod_6666" },
],
},
adminHeaders
)
rules = await service.listTaxRateRules({ tax_rate_id: rateId })
expect(rules.length).toEqual(4)
expect(rules).toEqual(
expect.arrayContaining([
expect.objectContaining({
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_3333",
created_by: "admin_user",
}),
expect.objectContaining({
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_4444",
created_by: "admin_user",
}),
expect.objectContaining({
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_5555",
created_by: "admin_user",
}),
expect.objectContaining({
tax_rate_id: rateId,
reference: "product",
reference_id: "prod_6666",
created_by: "admin_user",
}),
])
)
})
})
209 changes: 209 additions & 0 deletions integration-tests/modules/__tests__/tax/workflow/tax.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import path from "path"
import { ITaxModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"

import { createAdminUser } from "../../../helpers/create-admin-user"
import { initDb, useDb } from "../../../../environment-helpers/use-db"
import { getContainer } from "../../../../environment-helpers/use-container"
import { startBootstrapApp } from "../../../../environment-helpers/bootstrap-app"
import { useApi } from "../../../../environment-helpers/use-api"
import {
createTaxRateRulesStepId,
maybeSetTaxRateRulesStepId,
updateTaxRatesStepId,
updateTaxRatesWorkflow,
} from "@medusajs/core-flows"

jest.setTimeout(50000)

const env = { MEDUSA_FF_MEDUSA_V2: true }
const adminHeaders = {
headers: { "x-medusa-access-token": "test_token" },
}

describe("Taxes - Workflow", () => {
let dbConnection
let appContainer
let shutdownServer
let service: ITaxModuleService

beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", "..", ".."))
dbConnection = await initDb({ cwd, env } as any)
shutdownServer = await startBootstrapApp({ cwd, env })
appContainer = getContainer()
service = appContainer.resolve(ModuleRegistrationName.TAX)
})

beforeEach(async () => {
await createAdminUser(dbConnection, adminHeaders)
})

afterAll(async () => {
const db = useDb()
await db.shutdown()
await shutdownServer()
})

afterEach(async () => {
const db = useDb()
await db.teardown()
})

it("compensates rules correctly", async () => {
const taxRegion = await service.createTaxRegions({
country_code: "us",
})

const [rateOne, rateTwo] = await service.create([
{
tax_region_id: taxRegion.id,
rate: 10,
code: "standard",
name: "Standard",
rules: [
{ reference: "shipping", reference_id: "shipping_12354" },
{ reference: "shipping", reference_id: "shipping_11111" },
{ reference: "shipping", reference_id: "shipping_22222" },
],
},
{
tax_region_id: taxRegion.id,
rate: 2,
code: "reduced",
name: "Reduced",
rules: [
{ reference: "product", reference_id: "product_12354" },
{ reference: "product", reference_id: "product_11111" },
{ reference: "product", reference_id: "product_22222" },
],
},
])

const workflow = updateTaxRatesWorkflow(appContainer)

workflow.appendAction("throw", createTaxRateRulesStepId, {
invoke: async function failStep() {
throw new Error(`Failed to update`)
},
})

await workflow.run({
input: {
selector: { tax_region_id: taxRegion.id },
update: {
rate: 2,
rules: [
{ reference: "product", reference_id: "product_12354" },
{ reference: "shipping", reference_id: "shipping_12354" },
],
},
},
throwOnError: false,
})

const taxRateRules = await service.listTaxRateRules({
tax_rate: { tax_region_id: taxRegion.id },
})

expect(taxRateRules.length).toEqual(6)
expect(taxRateRules).toEqual(
expect.arrayContaining([
expect.objectContaining({
tax_rate_id: rateOne.id,
reference_id: "shipping_12354",
}),
expect.objectContaining({
tax_rate_id: rateOne.id,
reference_id: "shipping_11111",
}),
expect.objectContaining({
tax_rate_id: rateOne.id,
reference_id: "shipping_22222",
}),
expect.objectContaining({
tax_rate_id: rateTwo.id,
reference_id: "product_12354",
}),
expect.objectContaining({
tax_rate_id: rateTwo.id,
reference_id: "product_11111",
}),
expect.objectContaining({
tax_rate_id: rateTwo.id,
reference_id: "product_22222",
}),
])
)
})

it("creates rules correctly", async () => {
const taxRegion = await service.createTaxRegions({
country_code: "us",
})

const [rateOne, rateTwo] = await service.create([
{
tax_region_id: taxRegion.id,
rate: 10,
code: "standard",
name: "Standard",
rules: [
{ reference: "shipping", reference_id: "shipping_12354" },
{ reference: "shipping", reference_id: "shipping_11111" },
{ reference: "shipping", reference_id: "shipping_22222" },
],
},
{
tax_region_id: taxRegion.id,
rate: 2,
code: "reduced",
name: "Reduced",
rules: [
{ reference: "product", reference_id: "product_12354" },
{ reference: "product", reference_id: "product_11111" },
{ reference: "product", reference_id: "product_22222" },
],
},
])

await updateTaxRatesWorkflow(appContainer).run({
input: {
selector: { tax_region_id: taxRegion.id },
update: {
rate: 2,
rules: [
{ reference: "product", reference_id: "product_12354" },
{ reference: "shipping", reference_id: "shipping_12354" },
],
},
},
})

const taxRateRules = await service.listTaxRateRules({
tax_rate: { tax_region_id: taxRegion.id },
})

expect(taxRateRules.length).toEqual(4)
expect(taxRateRules).toEqual(
expect.arrayContaining([
expect.objectContaining({
tax_rate_id: rateOne.id,
reference_id: "shipping_12354",
}),
expect.objectContaining({
tax_rate_id: rateTwo.id,
reference_id: "shipping_12354",
}),
expect.objectContaining({
tax_rate_id: rateOne.id,
reference_id: "product_12354",
}),
expect.objectContaining({
tax_rate_id: rateTwo.id,
reference_id: "product_12354",
}),
])
)
})
})
31 changes: 31 additions & 0 deletions packages/core-flows/src/tax/steps/create-tax-rate-rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { CreateTaxRateRuleDTO, ITaxModuleService } from "@medusajs/types"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"

export const createTaxRateRulesStepId = "create-tax-rate-rules"
export const createTaxRateRulesStep = createStep(
createTaxRateRulesStepId,
async (data: CreateTaxRateRuleDTO[], { container }) => {
const service = container.resolve<ITaxModuleService>(
ModuleRegistrationName.TAX
)

const created = await service.createTaxRateRules(data)

return new StepResponse(
created,
created.map((rule) => rule.id)
)
},
async (createdIds, { container }) => {
if (!createdIds?.length) {
return
}

const service = container.resolve<ITaxModuleService>(
ModuleRegistrationName.TAX
)

await service.deleteTaxRateRules(createdIds)
}
)
Loading

0 comments on commit 555eb41

Please sign in to comment.