Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(medusa): Support batch remove resources on discount condition #2444

Merged
merged 3 commits into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/sixty-paws-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@medusajs/medusa-js": patch
"medusa-react": patch
"@medusajs/medusa": patch
---

feat(medusa): Support batch remove resources on discount condition
131 changes: 131 additions & 0 deletions integration-tests/api/__tests__/admin/discount.js
Original file line number Diff line number Diff line change
Expand Up @@ -2319,4 +2319,135 @@ describe("/admin/discounts", () => {
)
})
})

describe("DELETE /admin/discounts/:id/conditions/:condition_id/batch", () => {
let prod1
let prod2
let prod3
let prod4

beforeEach(async () => {
await adminSeeder(dbConnection)

prod1 = await simpleProductFactory(dbConnection, { type: "pants" })
prod2 = await simpleProductFactory(dbConnection, { type: "pants2" })
prod3 = await simpleProductFactory(dbConnection, { type: "pants3" })
prod4 = await simpleProductFactory(dbConnection, { type: "pants4" })

await simpleDiscountFactory(dbConnection, {
id: "test-discount",
code: "TEST",
rule: {
type: "percentage",
value: "10",
allocation: "total",
conditions: [
{
id: "test-condition",
type: "products",
operator: "in",
products: [prod1.id, prod2.id, prod3.id, prod4.id],
},
],
},
})

await simpleDiscountFactory(dbConnection, {
id: "test-discount-2",
code: "TEST2",
rule: {
type: "percentage",
value: "10",
allocation: "total",
conditions: [
{
id: "test-condition-2",
type: "products",
operator: "in",
products: [],
},
],
},
})
})

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

it("should update a condition with batch items to delete", async () => {
const api = useApi()

const discount = await api.get(
"/admin/discounts/test-discount",
adminReqConfig
)

const cond = discount.data.discount.rule.conditions[0]

const response = await api.delete(
`/admin/discounts/test-discount/conditions/${cond.id}/batch?expand=rule,rule.conditions,rule.conditions.products`,
{
...adminReqConfig,
data: {
resources: [{ id: prod2.id }, { id: prod3.id }, { id: prod4.id }],
},
}
)

const disc = response.data.discount

expect(response.status).toEqual(200)
expect(disc.rule.conditions).toHaveLength(1)
expect(disc.rule.conditions[0].products).toHaveLength(1)
expect(disc).toEqual(
expect.objectContaining({
id: "test-discount",
code: "TEST",
rule: expect.objectContaining({
conditions: expect.arrayContaining([
expect.objectContaining({
products: expect.arrayContaining([
expect.objectContaining({
id: prod1.id,
}),
]),
}),
]),
}),
})
)
})

it("should fail if condition does not belong to discount", async () => {
const api = useApi()

const err = await api
.delete(
"/admin/discounts/test-discount/conditions/test-condition-2/batch",
adminReqConfig
)
.catch((e) => e)

expect(err.response.data.message).toBe(
"Condition with id test-condition-2 does not belong to Discount with id test-discount"
)
})

it("should fail if discount does not exist", async () => {
const api = useApi()

const err = await api
.delete(
"/admin/discounts/not-exist/conditions/test-condition/batch",
adminReqConfig
)
.catch((e) => e)

expect(err.response.data.message).toBe(
"Discount with id not-exist was not found"
)
})
})
})
14 changes: 14 additions & 0 deletions packages/medusa-js/src/resources/admin/discounts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
AdminDeleteDiscountsDiscountConditionsConditionBatchReq,
AdminDiscountConditionsRes,
AdminDiscountsDeleteRes,
AdminDiscountsListRes,
Expand Down Expand Up @@ -230,6 +231,19 @@ class AdminDiscountsResource extends BaseResource {

return this.client.request("POST", path, payload, {}, customHeaders)
}

/**
* @description Delete a batch of items from a discount condition
*/
deleteConditionResourceBatch(
discountId: string,
conditionId: string,
payload: AdminDeleteDiscountsDiscountConditionsConditionBatchReq,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminDiscountsRes> {
const path = `/admin/discounts/${discountId}/conditions/${conditionId}/batch`
return this.client.request("DELETE", path, payload, {}, customHeaders)
}
}

export default AdminDiscountsResource
23 changes: 23 additions & 0 deletions packages/medusa-react/mocks/handlers/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,29 @@ export const adminHandlers = [
}
),

rest.delete(
"/admin/discounts/:id/conditions/:conditionId/batch",
(req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
discount: {
...fixtures.get("discount"),
rule: {
...fixtures.get("discount").rule,
conditions: [
{
...fixtures.get("discount").rule.conditions[0],
products: [],
},
],
},
},
})
)
}
),

rest.get("/admin/draft-orders/", (req, res, ctx) => {
return res(
ctx.status(200),
Expand Down
24 changes: 24 additions & 0 deletions packages/medusa-react/src/hooks/admin/discounts/mutations.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
AdminDeleteDiscountsDiscountConditionsConditionBatchReq,
AdminDiscountsDeleteRes,
AdminDiscountsRes,
AdminPostDiscountsDiscountConditions,
Expand Down Expand Up @@ -39,6 +40,29 @@ export const useAdminAddDiscountConditionResourceBatch = (
)
}

export const useAdminDeleteDiscountConditionResourceBatch = (
discountId: string,
conditionId: string,
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
Error,
AdminDeleteDiscountsDiscountConditionsConditionBatchReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()

return useMutation(
(payload: AdminDeleteDiscountsDiscountConditionsConditionBatchReq) =>
client.admin.discounts.deleteConditionResourceBatch(
discountId,
conditionId,
payload
),
buildOptions(queryClient, [adminDiscountKeys.detail(discountId)], options)
)
}

export const useAdminCreateDiscount = (
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
useAdminCreateDiscount,
useAdminCreateDynamicDiscountCode,
useAdminDeleteDiscount,
useAdminDeleteDiscountConditionResourceBatch,
useAdminDeleteDynamicDiscountCode,
useAdminDiscountAddRegion,
useAdminDiscountCreateCondition,
Expand All @@ -16,6 +17,48 @@ import {
} from "../../../../src/"
import { createWrapper } from "../../../utils"

describe("useAdminDeleteDiscountConditionResourceBatch hook", () => {
test("delete items from a discount condition and return the discount", async () => {
const resources = [
{
id: fixtures.get("product").id,
},
]
const discountId = fixtures.get("discount").id
const conditionId = fixtures.get("discount").rule.conditions[0].id

const { result, waitFor } = renderHook(
() =>
useAdminDeleteDiscountConditionResourceBatch(discountId, conditionId),
{
wrapper: createWrapper(),
}
)

result.current.mutate({
resources,
})

await waitFor(() => result.current.isSuccess)

expect(result.current.data.response.status).toEqual(200)
expect(result.current.data.discount).toEqual(
expect.objectContaining({
...fixtures.get("discount"),
rule: {
...fixtures.get("discount").rule,
conditions: [
{
...fixtures.get("discount").rule.conditions[0],
products: [],
},
],
},
})
)
})
})

describe("useAdminAddDiscountConditionResourceBatch hook", () => {
test("add items to a discount condition and return the discount", async () => {
const resources = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { Request, Response } from "express"
import { EntityManager } from "typeorm"
import { DiscountService } from "../../../../services"
import {
DiscountConditionInput,
DiscountConditionMapTypeToProperty,
UpsertDiscountConditionInput,
} from "../../../../types/discount"
import { IsArray } from "class-validator"
import { FindParams } from "../../../../types/common"
Expand All @@ -18,7 +18,7 @@ import { FindParams } from "../../../../types/common"
* parameters:
* - (path) discount_id=* {string} The ID of the Product.
* - (path) condition_id=* {string} The ID of the condition on which to add the item.
* - (query) expand {string} (Comma separated) Which fields should be expanded in each discount of the result.
* - (query) expand {string} (Comma separated) Which relations should be expanded in each discount of the result.
* - (query) fields {string} (Comma separated) Which fields should be included in each discount of the result.
* requestBody:
* content:
Expand All @@ -42,7 +42,6 @@ import { FindParams } from "../../../../types/common"
* label: JS Client
* source: |
* import Medusa from "@medusajs/medusa-js"
* import { DiscountConditionOperator } from "@medusajs/medusa"
* const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })
* // must be previously logged in or use api token
* medusa.admin.discounts.addConditionResourceBatch(discount_id, condition_id, {
Expand Down Expand Up @@ -101,7 +100,7 @@ export default async (req: Request, res: Response) => {
select: ["id", "type", "discount_rule_id"],
})

const updateObj: UpsertDiscountConditionInput = {
const updateObj: DiscountConditionInput = {
id: condition_id,
rule_id: condition.discount_rule_id,
[DiscountConditionMapTypeToProperty[condition.type]]:
Expand Down
Loading