Feat(medusa): remove item from order (#2273)
* wait for update to order edit model * delete line item tests * create remove method for lineitem with tax lines * add remove item tests * split delete allocation tests into two: more and less than total * remove unused import * cleanup * add medusa-js and react endpoints * pr feedback fixes * linting * remove unused relation from query * remove removed-event and unused imports * add await
This commit is contained in:
@@ -95,6 +95,15 @@ class AdminOrderEditsResource extends BaseResource {
|
||||
const path = `/admin/order-edits/${orderEditId}/items/${itemId}`
|
||||
return this.client.request("POST", path, payload, {}, customHeaders)
|
||||
}
|
||||
|
||||
removeLineItem(
|
||||
orderEditId: string,
|
||||
itemId: string,
|
||||
customHeaders: Record<string, any> = {}
|
||||
): ResponsePromise<AdminOrderEditsRes> {
|
||||
const path = `/admin/order-edits/${orderEditId}/items/${itemId}`
|
||||
return this.client.request("DELETE", path, undefined, {}, customHeaders)
|
||||
}
|
||||
}
|
||||
|
||||
export default AdminOrderEditsResource
|
||||
|
||||
@@ -1783,6 +1783,22 @@ export const adminHandlers = [
|
||||
})
|
||||
)
|
||||
}),
|
||||
|
||||
rest.delete("/admin/order-edits/:id/items/:item_id", (req, res, ctx) => {
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
order_edit: {
|
||||
...fixtures.get("order_edit"),
|
||||
changes: [
|
||||
{
|
||||
type: 'item_remove'
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
}),
|
||||
|
||||
rest.get("/admin/auth", (req, res, ctx) => {
|
||||
return res(
|
||||
|
||||
@@ -93,6 +93,27 @@ export const useAdminOrderEditUpdateLineItem = (
|
||||
)
|
||||
}
|
||||
|
||||
export const useAdminOrderEditDeleteLineItem = (
|
||||
orderEditId: string,
|
||||
itemId: string,
|
||||
options?: UseMutationOptions<
|
||||
Response<AdminOrderEditsRes>,
|
||||
Error
|
||||
>
|
||||
) => {
|
||||
const { client } = useMedusa()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation(
|
||||
(() => client.admin.orderEdits.removeLineItem(orderEditId, itemId)),
|
||||
buildOptions(
|
||||
queryClient,
|
||||
[adminOrderEditsKeys.detail(orderEditId), adminOrderEditsKeys.lists()],
|
||||
options
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export const useAdminUpdateOrderEdit = (
|
||||
id: string,
|
||||
options?: UseMutationOptions<
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
useAdminOrderEditLineItem,
|
||||
useAdminCancelOrderEdit,
|
||||
useAdminUpdateOrderEdit,
|
||||
useAdminOrderEditDeleteLineItem,
|
||||
} from "../../../../src/"
|
||||
import { fixtures } from "../../../../mocks/data"
|
||||
import { createWrapper } from "../../../utils"
|
||||
@@ -247,3 +248,32 @@ describe("useAdminConfirmOrderEdit hook", () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("useAdminOrderEditDeleteLineItem hook", () => {
|
||||
test("Remove line item of an order edit and create an item change", async () => {
|
||||
const id = "oe_1"
|
||||
const itemId = "item_1"
|
||||
const { result, waitFor } = renderHook(
|
||||
() => useAdminOrderEditDeleteLineItem(id, itemId),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
}
|
||||
)
|
||||
|
||||
result.current.mutate()
|
||||
await waitFor(() => result.current.isSuccess)
|
||||
|
||||
expect(result.current.data.response.status).toEqual(200)
|
||||
expect(result.current.data.order_edit).toEqual(
|
||||
expect.objectContaining({
|
||||
...fixtures.get("order_edit"),
|
||||
changes: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: 'item_remove'
|
||||
}),
|
||||
]),
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { IdMap } from "medusa-test-utils"
|
||||
import { request } from "../../../../../helpers/test-request"
|
||||
import OrderEditingFeatureFlag from "../../../../../loaders/feature-flags/order-editing"
|
||||
import { orderEditServiceMock } from "../../../../../services/__mocks__/order-edit"
|
||||
|
||||
describe("DELETE /admin/order-edits/:id/items/:item_id", () => {
|
||||
describe("deletes a line item", () => {
|
||||
const lineItemId = IdMap.getId("testLineItem")
|
||||
const orderEditId = IdMap.getId("testCreatedOrder")
|
||||
let subject
|
||||
|
||||
beforeAll(async () => {
|
||||
subject = await request("DELETE", `/admin/order-edits/${orderEditId}/items/${lineItemId}`, {
|
||||
adminSession: {
|
||||
jwt: {
|
||||
userId: IdMap.getId("admin_user"),
|
||||
},
|
||||
},
|
||||
flags: [OrderEditingFeatureFlag],
|
||||
})
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it("calls orderService removeLineItem", () => {
|
||||
expect(orderEditServiceMock.removeLineItem).toHaveBeenCalledTimes(1)
|
||||
expect(orderEditServiceMock.removeLineItem).toHaveBeenCalledWith(orderEditId, lineItemId)
|
||||
})
|
||||
|
||||
it("returns 200", () => {
|
||||
expect(subject.status).toEqual(200)
|
||||
})
|
||||
|
||||
it("returns retrieve result", () => {
|
||||
expect(subject.body.order_edit).toEqual(expect.objectContaining({
|
||||
id: orderEditId,
|
||||
}))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { EntityManager } from "typeorm"
|
||||
import { OrderEditService } from "../../../../services"
|
||||
import { Request, Response } from "express"
|
||||
import { IsNumber } from "class-validator"
|
||||
import {
|
||||
defaultOrderEditFields,
|
||||
defaultOrderEditRelations,
|
||||
} from "../../../../types/order-edit"
|
||||
|
||||
/**
|
||||
* @oas [delete] /order-edits/{id}/items/{item_id}
|
||||
* operationId: "DeleteOrderEditsOrderEditLineItemsLineItem"
|
||||
* summary: "Delete line items from an order edit and create change item"
|
||||
* description: "Delete line items from an order edit and create change item"
|
||||
* x-authenticated: true
|
||||
* parameters:
|
||||
* - (path) id=* {string} The ID of the Order Edit to delete from.
|
||||
* - (path) item_id=* {string} The ID of the order edit item to delete from order.
|
||||
* x-codeSamples:
|
||||
* - lang: JavaScript
|
||||
* label: JS Client
|
||||
* source: |
|
||||
* import Medusa from "@medusajs/medusa-js"
|
||||
* const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })
|
||||
* // must be previously logged in or use api token
|
||||
* medusa.admin.orderEdits.removeLineItem(order_edit_id, line_item_id)
|
||||
* .then(({ order_edit }) => {
|
||||
* console.log(order_edit.id)
|
||||
* })
|
||||
* - lang: Shell
|
||||
* label: cURL
|
||||
* source: |
|
||||
* curl --location --request DELETE 'https://medusa-url.com/admin/order-edits/{id}/items/{item_id}' \
|
||||
* --header 'Authorization: Bearer {api_token}'
|
||||
* security:
|
||||
* - api_token: []
|
||||
* - cookie_auth: []
|
||||
* tags:
|
||||
* - OrderEdit
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* properties:
|
||||
* order_edit:
|
||||
* $ref: "#/components/schemas/order_edit"
|
||||
* "400":
|
||||
* $ref: "#/components/responses/400_error"
|
||||
* "401":
|
||||
* $ref: "#/components/responses/unauthorized"
|
||||
* "404":
|
||||
* $ref: "#/components/responses/not_found_error"
|
||||
* "409":
|
||||
* $ref: "#/components/responses/invalid_state_error"
|
||||
* "422":
|
||||
* $ref: "#/components/responses/invalid_request_error"
|
||||
* "500":
|
||||
* $ref: "#/components/responses/500_error"
|
||||
*/
|
||||
export default async (req: Request, res: Response) => {
|
||||
const { id, item_id } = req.params
|
||||
|
||||
const orderEditService: OrderEditService =
|
||||
req.scope.resolve("orderEditService")
|
||||
|
||||
const manager: EntityManager = req.scope.resolve("manager")
|
||||
|
||||
await manager.transaction(async (transactionManager) => {
|
||||
await orderEditService
|
||||
.withTransaction(transactionManager)
|
||||
.removeLineItem(id, item_id)
|
||||
})
|
||||
|
||||
let orderEdit = await orderEditService.retrieve(id, {
|
||||
select: defaultOrderEditFields,
|
||||
relations: defaultOrderEditRelations,
|
||||
})
|
||||
orderEdit = await orderEditService.decorateTotals(orderEdit)
|
||||
|
||||
res.status(200).send({
|
||||
order_edit: orderEdit,
|
||||
})
|
||||
}
|
||||
@@ -82,6 +82,11 @@ export default (app) => {
|
||||
middlewares.wrap(require("./update-order-edit-line-item").default)
|
||||
)
|
||||
|
||||
route.delete(
|
||||
"/:id/items/:item_id",
|
||||
middlewares.wrap(require("./delete-line-item").default)
|
||||
)
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
* description: "Create or update the order edit change holding the line item changes"
|
||||
* x-authenticated: true
|
||||
* parameters:
|
||||
* - (path) id=* {string} The ID of the Order Edit to delete.
|
||||
* - (path) id=* {string} The ID of the Order Edit to update.
|
||||
* - (path) item_id=* {string} The ID of the order edit item to update.
|
||||
* x-codeSamples:
|
||||
* - lang: JavaScript
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
* - lang: Shell
|
||||
* label: cURL
|
||||
* source: |
|
||||
* curl --location --request DELETE 'https://medusa-url.com/admin/order-edits/{id}/items/{item_id}' \
|
||||
* curl --location --request POST 'https://medusa-url.com/admin/order-edits/{id}/items/{item_id}' \
|
||||
* --header 'Authorization: Bearer {api_token}'
|
||||
* -d '{ "quantity": 5 }'
|
||||
* security:
|
||||
|
||||
@@ -22,10 +22,6 @@ export default (app, featureFlagRouter: FlagRouter) => {
|
||||
relations.push("sales_channel")
|
||||
}
|
||||
|
||||
if (featureFlagRouter.isFeatureEnabled(OrderEditingFeatureFlag.key)) {
|
||||
relations.push("edits")
|
||||
}
|
||||
|
||||
/**
|
||||
* List orders
|
||||
*/
|
||||
|
||||
@@ -146,6 +146,9 @@ export const orderEditServiceMock = {
|
||||
updateLineItem: jest.fn().mockImplementation((_) => {
|
||||
return Promise.resolve()
|
||||
}),
|
||||
removeLineItem: jest.fn().mockImplementation((_) => {
|
||||
return Promise.resolve()
|
||||
}),
|
||||
}
|
||||
|
||||
const mock = jest.fn().mockImplementation(() => {
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
ProductService,
|
||||
ProductVariantService,
|
||||
RegionService,
|
||||
TaxProviderService,
|
||||
} from "./index"
|
||||
import { buildQuery, setMetadata } from "../utils"
|
||||
import { TransactionBaseService } from "../interfaces"
|
||||
@@ -30,6 +31,7 @@ type InjectedDependencies = {
|
||||
pricingService: PricingService
|
||||
regionService: RegionService
|
||||
lineItemAdjustmentService: LineItemAdjustmentService
|
||||
taxProviderService: TaxProviderService
|
||||
featureFlagRouter: FlagRouter
|
||||
}
|
||||
|
||||
@@ -46,6 +48,7 @@ class LineItemService extends TransactionBaseService {
|
||||
protected readonly regionService_: RegionService
|
||||
protected readonly featureFlagRouter_: FlagRouter
|
||||
protected readonly lineItemAdjustmentService_: LineItemAdjustmentService
|
||||
protected readonly taxProviderService_: TaxProviderService
|
||||
|
||||
constructor({
|
||||
manager,
|
||||
@@ -57,6 +60,7 @@ class LineItemService extends TransactionBaseService {
|
||||
regionService,
|
||||
cartRepository,
|
||||
lineItemAdjustmentService,
|
||||
taxProviderService,
|
||||
featureFlagRouter,
|
||||
}: InjectedDependencies) {
|
||||
super(arguments[0])
|
||||
@@ -70,6 +74,7 @@ class LineItemService extends TransactionBaseService {
|
||||
this.regionService_ = regionService
|
||||
this.cartRepository_ = cartRepository
|
||||
this.lineItemAdjustmentService_ = lineItemAdjustmentService
|
||||
this.taxProviderService_ = taxProviderService
|
||||
this.featureFlagRouter_ = featureFlagRouter
|
||||
}
|
||||
|
||||
@@ -352,6 +357,27 @@ class LineItemService extends TransactionBaseService {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a line item with the tax lines.
|
||||
* @param id - the id of the line item to delete
|
||||
* @return the result of the delete operation
|
||||
*/
|
||||
async deleteWithTaxLines(id: string): Promise<LineItem | undefined> {
|
||||
return await this.atomicPhase_(
|
||||
async (transactionManager: EntityManager) => {
|
||||
const lineItemRepository = transactionManager.getCustomRepository(
|
||||
this.lineItemRepository_
|
||||
)
|
||||
|
||||
await this.taxProviderService_
|
||||
.withTransaction(transactionManager)
|
||||
.clearLineItemsTaxLines([id])
|
||||
|
||||
return await this.delete(id)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a line item tax line.
|
||||
* @param args - tax line partial passed to the repo create method
|
||||
|
||||
@@ -38,7 +38,7 @@ export default class OrderEditItemChangeService extends TransactionBaseService {
|
||||
lineItemService,
|
||||
taxProviderService,
|
||||
}: InjectedDependencies) {
|
||||
// @ts-ignore
|
||||
// eslint-disable-next-line prefer-rest-params
|
||||
super(arguments[0])
|
||||
|
||||
this.manager_ = manager
|
||||
@@ -125,7 +125,9 @@ export default class OrderEditItemChangeService extends TransactionBaseService {
|
||||
|
||||
const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
|
||||
await Promise.all([
|
||||
...lineItemIdsToRemove.map((id) => lineItemServiceTx.delete(id)),
|
||||
...lineItemIdsToRemove.map(
|
||||
async (id) => await lineItemServiceTx.delete(id)
|
||||
),
|
||||
this.taxProviderService_
|
||||
.withTransaction(manager)
|
||||
.clearLineItemsTaxLines(lineItemIdsToRemove),
|
||||
|
||||
@@ -389,6 +389,63 @@ export default class OrderEditService extends TransactionBaseService {
|
||||
})
|
||||
}
|
||||
|
||||
async removeLineItem(orderEditId: string, lineItemId: string): Promise<void> {
|
||||
return await this.atomicPhase_(async (manager) => {
|
||||
const orderEdit = await this.retrieve(orderEditId, {
|
||||
select: [
|
||||
"id",
|
||||
"created_at",
|
||||
"requested_at",
|
||||
"confirmed_at",
|
||||
"declined_at",
|
||||
"canceled_at",
|
||||
],
|
||||
})
|
||||
|
||||
const isOrderEditActive = OrderEditService.isOrderEditActive(orderEdit)
|
||||
|
||||
if (!isOrderEditActive) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.NOT_ALLOWED,
|
||||
`Can not update an item on the order edit ${orderEditId} with the status ${orderEdit.status}`
|
||||
)
|
||||
}
|
||||
|
||||
const lineItem = await this.lineItemService_
|
||||
.withTransaction(manager)
|
||||
.retrieve(lineItemId, {
|
||||
select: ["id", "order_edit_id", "original_item_id"],
|
||||
})
|
||||
.catch(() => void 0)
|
||||
|
||||
if (!lineItem) {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
lineItem.order_edit_id !== orderEditId ||
|
||||
!lineItem.original_item_id
|
||||
) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
`Invalid line item id ${lineItemId} it does not belong to the same order edit ${orderEdit.order_id}.`
|
||||
)
|
||||
}
|
||||
|
||||
await this.lineItemService_
|
||||
.withTransaction(manager)
|
||||
.deleteWithTaxLines(lineItem.id)
|
||||
|
||||
await this.refreshAdjustments(orderEditId)
|
||||
|
||||
await this.orderEditItemChangeService_.withTransaction(manager).create({
|
||||
original_line_item_id: lineItem.original_item_id,
|
||||
type: OrderEditItemChangeType.ITEM_REMOVE,
|
||||
order_edit_id: orderEdit.id,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async refreshAdjustments(orderEditId: string) {
|
||||
const manager = this.transactionManager_ ?? this.manager_
|
||||
|
||||
|
||||
@@ -966,4 +966,3 @@ const SalesChannelsSchema: ProductImportCsvSchema = {
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user