feat(medusa): Update OrderEdit (#2220)

This commit is contained in:
Frane Polić
2022-09-19 13:29:12 +02:00
committed by GitHub
parent 5a2ac76762
commit e1fe5ed094
11 changed files with 337 additions and 12 deletions
@@ -1,4 +1,5 @@
import { Router } from "express"
import middlewares, {
transformBody,
transformQuery,
@@ -11,6 +12,7 @@ import {
defaultOrderEditRelations,
} from "../../../../types/order-edit"
import { OrderEdit } from "../../../../models"
import { AdminPostOrderEditsOrderEditReq } from "./update-order-edit"
import { AdminPostOrderEditsReq } from "./create-order-edit"
const route = Router()
@@ -38,6 +40,12 @@ export default (app) => {
middlewares.wrap(require("./get-order-edit").default)
)
route.post(
"/:id",
transformBody(AdminPostOrderEditsOrderEditReq),
middlewares.wrap(require("./update-order-edit").default)
)
route.delete("/:id", middlewares.wrap(require("./delete-order-edit").default))
return app
@@ -48,4 +56,6 @@ export type AdminOrderEditsRes = {
}
export type AdminOrderEditDeleteRes = DeleteResponse
export * from "./update-order-edit"
export * from "./create-order-edit"
@@ -0,0 +1,102 @@
import { IsOptional, IsString } from "class-validator"
import { Request, Response } from "express"
import { EntityManager } from "typeorm"
import { OrderEditService } from "../../../../services"
/**
* @oas [post] /order-edits/{id}
* operationId: "PostOrderEditsOrderEdit"
* summary: "Updates an OrderEdit"
* description: "Updates a OrderEdit."
* x-authenticated: true
* parameters:
* - (path) id=* {string} The ID of the OrderEdit.
* 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
* const params = {internal_note: "internal reason XY"}
* medusa.admin.orderEdit.update(orderEditId, params)
* .then(({ order_edit }) => {
* console.log(order_edit.id);
* });
* - lang: Shell
* label: cURL
* source: |
* curl --location --request POST 'https://medusa-url.com/admin/order-edits/{id}' \
* --header 'Authorization: Bearer {api_token}'
* --header 'Content-Type: application/json' \
* --data-raw '{
* "internal_note": "internal reason XY"
* }'
* 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 } = req.params
const { validatedBody } = req as {
validatedBody: AdminPostOrderEditsOrderEditReq
}
const orderEditService: OrderEditService =
req.scope.resolve("orderEditService")
const manager: EntityManager = req.scope.resolve("manager")
const orderEdit = await manager.transaction(async (transactionManager) => {
const orderEditServiceTx =
orderEditService.withTransaction(transactionManager)
const _orderEdit = await orderEditServiceTx.update(id, validatedBody)
const { items } = await orderEditServiceTx.computeLineItems(_orderEdit.id)
_orderEdit.items = items
const totals = await orderEditServiceTx.getTotals(_orderEdit.id)
_orderEdit.discount_total = totals.discount_total
_orderEdit.gift_card_total = totals.gift_card_total
_orderEdit.gift_card_tax_total = totals.gift_card_tax_total
_orderEdit.shipping_total = totals.shipping_total
_orderEdit.subtotal = totals.subtotal
_orderEdit.tax_total = totals.tax_total
_orderEdit.total = totals.total
return _orderEdit
})
res.status(200).json({ order_edit: orderEdit })
}
export class AdminPostOrderEditsOrderEditReq {
@IsOptional()
@IsString()
internal_note?: string
}
@@ -34,11 +34,6 @@ export default (app) => {
"/",
middlewares.wrap(require("./get-sales-channel").default)
)
salesChannelRouter.post(
"/",
transformBody(AdminPostSalesChannelsSalesChannelReq),
middlewares.wrap(require("./update-sales-channel").default)
)
salesChannelRouter.delete(
"/",
middlewares.wrap(require("./delete-sales-channel").default)
@@ -12,6 +12,10 @@ import { EventBusServiceMock } from "../__mocks__/event-bus"
import { LineItemServiceMock } from "../__mocks__/line-item"
import { TotalsServiceMock } from "../__mocks__/totals"
const orderEditToUpdate = {
id: IdMap.getId("order-edit-to-update"),
}
const orderEditWithChanges = {
id: IdMap.getId("order-edit-with-changes"),
order: {
@@ -77,6 +81,10 @@ const lineItemServiceMock = {
}
describe("OrderEditService", () => {
afterEach(() => {
jest.clearAllMocks()
})
const orderEditRepository = MockRepository({
findOneWithRelations: (relations, query) => {
if (query?.where?.id === IdMap.getId("order-edit-with-changes")) {
@@ -113,6 +121,16 @@ describe("OrderEditService", () => {
)
})
it("should update an order edit with the right arguments", async () => {
await orderEditService.update(IdMap.getId("order-edit-to-update"), {
internal_note: "test note",
})
expect(orderEditRepository.save).toHaveBeenCalledTimes(1)
expect(orderEditRepository.save).toHaveBeenCalledWith({
internal_note: "test note",
})
})
it("should compute the items from the changes and attach them to the orderEdit", async () => {
const { items, removedItems } = await orderEditService.computeLineItems(
IdMap.getId("order-edit-with-changes")
+32 -1
View File
@@ -1,6 +1,6 @@
import { EntityManager } from "typeorm"
import { FindConfig } from "../types/common"
import { buildQuery } from "../utils"
import { buildQuery, isDefined } from "../utils"
import { MedusaError } from "medusa-core-utils"
import { OrderEditRepository } from "../repositories/order-edit"
import {
@@ -18,6 +18,7 @@ import {
TotalsService,
} from "./index"
import { CreateOrderEditInput } from "../types/order-edit"
import { UpdateOrderEditInput } from "../types/order-edit"
type InjectedDependencies = {
manager: EntityManager
@@ -31,6 +32,7 @@ type InjectedDependencies = {
export default class OrderEditService extends TransactionBaseService {
static readonly Events = {
CREATED: "order-edit.created",
UPDATED: "order-edit.updated",
}
protected transactionManager_: EntityManager | undefined
@@ -259,6 +261,35 @@ export default class OrderEditService extends TransactionBaseService {
})
}
async update(
orderEditId: string,
data: UpdateOrderEditInput
): Promise<OrderEdit> {
return await this.atomicPhase_(async (manager) => {
const orderEditRepo = manager.getCustomRepository(
this.orderEditRepository_
)
const orderEdit = await this.retrieve(orderEditId)
for (const key of Object.keys(data)) {
if (isDefined(data[key])) {
orderEdit[key] = data[key]
}
}
const result = await orderEditRepo.save(orderEdit)
await this.eventBusService_
.withTransaction(manager)
.emit(OrderEditService.Events.UPDATED, {
id: result.id,
})
return result
})
}
async delete(orderEditId: string): Promise<void> {
return await this.atomicPhase_(async (manager) => {
const orderEditRepo = manager.getCustomRepository(
+4
View File
@@ -1,5 +1,9 @@
import { OrderEdit } from "../models"
export type UpdateOrderEditInput = {
internal_note?: string
}
export const defaultOrderEditRelations: string[] = [
"changes",
"changes.line_item",