Skip to content

Commit

Permalink
feat(medusa): cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
adrien2p committed Sep 15, 2022
1 parent 95615a0 commit 7674a1f
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 38 deletions.
4 changes: 2 additions & 2 deletions packages/medusa-js/src/resources/admin/order-edits.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { AdminOrdersEditsRes } from "@medusajs/medusa"
import { AdminOrderEditsRes } from "@medusajs/medusa"
import { ResponsePromise } from "../../typings"
import BaseResource from "../base"

class AdminOrderEditsResource extends BaseResource {
retrieve(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersEditsRes> {
): ResponsePromise<AdminOrderEditsRes> {
const path = `/admin/order-edits/${id}`
return this.client.request("GET", path, undefined, {}, customHeaders)
}
Expand Down
8 changes: 3 additions & 5 deletions packages/medusa-react/src/hooks/admin/order-edits/queries.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AdminOrdersEditsRes } from "@medusajs/medusa"
import { AdminOrderEditsRes } from "@medusajs/medusa"
import { queryKeysFactory } from "../../utils"
import { UseQueryOptionsWrapper } from "../../../types"
import { Response } from "@medusajs/medusa-js"
Expand All @@ -12,11 +12,9 @@ type OrderEditQueryKeys = typeof adminOrderEditsKeys

export const useAdminOrderEdit = (
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminOrdersEditsRes>,
options?: UseQueryOptionsWrapper<Response<AdminOrderEditsRes>,
Error,
ReturnType<OrderEditQueryKeys["detail"]>
>
ReturnType<OrderEditQueryKeys["detail"]>>
) => {
const { client } = useMedusa()
const { data, ...rest } = useQuery(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { IdMap } from "medusa-test-utils"
import { request } from "../../../../../helpers/test-request"
import { ProductServiceMock } from "../../../../../services/__mocks__/product"
import { ProductVariantServiceMock } from "../../../../../services/__mocks__/product-variant"
import { ShippingProfileServiceMock } from "../../../../../services/__mocks__/shipping-profile"
import { OrderEditService } from "../../../../../services/order-edit"
import { orderEditServiceMock } from "../../../../../services/__mocks__/order-edit";
import OrderEditingFeatureFlag from "../../../../../loaders/feature-flags/order-editing";

describe("POST /admin/order-edits", () => {
describe("successfully create an order edit", () => {
Expand All @@ -22,6 +20,7 @@ describe("POST /admin/order-edits", () => {
userId: IdMap.getId("admin_user"),
},
},
flags: [OrderEditingFeatureFlag],
})
})

Expand All @@ -34,8 +33,8 @@ describe("POST /admin/order-edits", () => {
})

it("calls order edit service create", () => {
expect(OrderEditService.create).toHaveBeenCalledTimes(1)
expect(OrderEditService.create).toHaveBeenCalledWith(
expect(orderEditServiceMock.create).toHaveBeenCalledTimes(1)
expect(orderEditServiceMock.create).toHaveBeenCalledWith(
{
order_id: orderId,
internal_note: internalNote,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,6 @@
import { Request, Response } from "express"
import { OrderEditService } from "../../../../services/order-edit"
import {
IsArray,
IsBoolean,
IsEnum,
IsNumber,
IsObject,
IsOptional,
IsString,
ValidateNested,
} from "class-validator"
import { ProductStatus } from "../../../../models"
import { Type } from "class-transformer"
import {
ProductSalesChannelReq,
ProductTagReq,
ProductTypeReq,
} from "../../../../types/product"
import { FeatureFlagDecorators } from "../../../../utils/feature-flag-decorators"
import SalesChannelFeatureFlag from "../../../../loaders/feature-flags/sales-channels"
import { OrderEditService } from "../../../../services"
import { IsOptional, IsString } from "class-validator"

/**
* @oas [post] /order-edits
Expand Down
14 changes: 12 additions & 2 deletions packages/medusa/src/api/routes/admin/order-edits/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Router } from "express"
import middlewares, { transformQuery } from "../../../middlewares"
import middlewares, {
transformBody,
transformQuery,
} from "../../../middlewares"
import { EmptyQueryParams } from "../../../../types/common"
import { isFeatureFlagEnabled } from "../../../middlewares/feature-flag-enabled"
import OrderEditingFeatureFlag from "../../../../loaders/feature-flags/order-editing"
Expand All @@ -8,6 +11,7 @@ import {
defaultOrderEditRelations,
} from "../../../../types/order-edit"
import { OrderEdit } from "../../../../models"
import { AdminPostProductsReq } from "./create-order-edit"

const route = Router()

Expand All @@ -18,6 +22,12 @@ export default (app) => {
route
)

route.post(
"/",
transformBody(AdminPostProductsReq),
middlewares.wrap(require("./create-order-edit").default)
)

route.get(
"/:id",
transformQuery(EmptyQueryParams, {
Expand All @@ -31,6 +41,6 @@ export default (app) => {
return app
}

export type AdminOrdersEditsRes = {
export type AdminOrderEditsRes = {
order_edit: OrderEdit
}
7 changes: 7 additions & 0 deletions packages/medusa/src/services/__mocks__/order-edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ export const orderEditServiceMock = {
computeLineItems: jest.fn().mockImplementation((orderEdit) => {
return Promise.resolve(orderEdit)
}),
create: jest.fn().mockImplementation((data, context) => {
return Promise.resolve({
order_id: data.order_id,
internal_note: data.internal_note,
created_by: context.loggedInUserId,
})
}),
}

const mock = jest.fn().mockImplementation(() => {
Expand Down
20 changes: 19 additions & 1 deletion packages/medusa/src/services/__tests__/order-edit.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { IdMap, MockManager, MockRepository } from "medusa-test-utils"
import { OrderEditService, OrderService } from "../index"
import { EventBusService, OrderEditService, OrderService } from "../index"
import { OrderEditItemChangeType } from "../../models"
import { OrderServiceMock } from "../__mocks__/order"
import { EventBusServiceMock } from "../__mocks__/event-bus";

const orderEditWithChanges = {
id: IdMap.getId("order-edit-with-changes"),
Expand Down Expand Up @@ -63,6 +64,7 @@ describe("OrderEditService", () => {
manager: MockManager,
orderEditRepository,
orderService: OrderServiceMock as unknown as OrderService,
eventBusService: EventBusServiceMock as unknown as EventBusService,
})

it("should retrieve an order edit and call the repository with the right arguments", async () => {
Expand Down Expand Up @@ -104,4 +106,20 @@ describe("OrderEditService", () => {
])
)
})

it("should create an order edit and call the repository with the right arguments as well as the event bus service", async () => {
const data = {
order_id: IdMap.getId("order-edit-order-id"),
internal_note: "internal note"
}
await orderEditService.create(data, { loggedInUserId: IdMap.getId("admin_user") })
expect(orderEditRepository.create).toHaveBeenCalledTimes(1)
expect(orderEditRepository.create).toHaveBeenCalledWith(
{
order_id: data.order_id,
internal_note: data.internal_note,
created_by: IdMap.getId("admin_user"),
},
)
})
})
63 changes: 61 additions & 2 deletions packages/medusa/src/services/order-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,48 @@ import {
OrderItemChange,
} from "../models"
import { TransactionBaseService } from "../interfaces"
import { OrderService } from "./index"
import { EventBusService, OrderService } from "./index"
import { CreateOrderEditInput } from "../types/order-edit"

type InjectedDependencies = {
manager: EntityManager
orderEditRepository: typeof OrderEditRepository
orderService: OrderService
eventBusService: EventBusService
}

export default class OrderEditService extends TransactionBaseService {
static readonly Events = {
CREATED: "order-edit.created",
}

protected transactionManager_: EntityManager | undefined
protected readonly manager_: EntityManager
protected readonly orderEditRepository_: typeof OrderEditRepository
protected readonly orderService_: OrderService
protected readonly eventBusService_: EventBusService

constructor({
manager,
orderEditRepository,
orderService,
eventBusService,
}: InjectedDependencies) {
// eslint-disable-next-line prefer-rest-params
super(arguments[0])

this.manager_ = manager
this.orderEditRepository_ = orderEditRepository
this.orderService_ = orderService
this.eventBusService_ = eventBusService
}

async retrieve(
orderEditId: string,
config: FindConfig<OrderEdit> = {}
): Promise<OrderEdit | never> {
const orderEditRepository = this.manager_.getCustomRepository(
const manager = this.transactionManager_ ?? this.manager_
const orderEditRepository = manager.getCustomRepository(
this.orderEditRepository_
)
const { relations, ...query } = buildQuery({ id: orderEditId }, config)
Expand All @@ -61,6 +71,23 @@ export default class OrderEditService extends TransactionBaseService {
return orderEdit
}

protected async retrieveActiveOrderEdit(
orderId: string
): Promise<OrderEdit | undefined> {
const manager = this.transactionManager_ ?? this.manager_
const orderEditRepository = manager.getCustomRepository(
this.orderEditRepository_
)
return await orderEditRepository.findOne({
where: {
order_id: orderId,
confirmed_at: null,
declined_at: null,
canceled_at: null,
},
})
}

async computeLineItems(
orderEditId: string
): Promise<{ items: LineItem[]; removedItems: LineItem[] }> {
Expand Down Expand Up @@ -114,4 +141,36 @@ export default class OrderEditService extends TransactionBaseService {

return { items, removedItems }
}

async create(
data: CreateOrderEditInput,
context: { loggedInUserId: string }
): Promise<OrderEdit> {
return await this.atomicPhase_(async (transactionManager) => {
const activeOrderEdit = await this.retrieveActiveOrderEdit(data.order_id)
if (activeOrderEdit) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`An active order edit already exists for the order ${data.order_id}`
)
}

const orderEditRepository = transactionManager.getCustomRepository(
this.orderEditRepository_
)

const orderEditToCreate = orderEditRepository.create({
order_id: data.order_id,
internal_note: data.internal_note,
created_by: context.loggedInUserId,
})
const orderEdit = await orderEditRepository.save(orderEditToCreate)

await this.eventBusService_
.withTransaction(transactionManager)
.emit(OrderEditService.Events.CREATED, { id: orderEdit.id })

return orderEdit
})
}
}
5 changes: 5 additions & 0 deletions packages/medusa/src/types/order-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ export const defaultOrderEditFields: (keyof OrderEdit)[] = [
"canceled_at",
"internal_note",
]

export type CreateOrderEditInput = {
order_id: string
internal_note?: string
}

0 comments on commit 7674a1f

Please sign in to comment.