/** * AORD-01..38 — `admin.order` (catalogue §7.5). * * Live HTTP/tRPC suite against the running backend. Every `it()` maps to one * catalogue row; rows that pin current (not intended) behaviour are prefixed * `(current)` with a comment recording the observed contract. * * Notable observed contracts (do not "fix" here): * - The router uses `protectedProcedure`, not `staffProcedure`, so a user token * passes the guard and then dereferences `ctx.staffUser!.regionId`. * - `getAll` wraps everything in try/catch and resolves `undefined` on any * error, including the `packagedFilter`/`deliveredFilter`/`cancellationFilter` * paths (they reference `order_status` in a relational `where` and throw) and * `limit: 0` (the nextCursor line dereferences an empty page). * - `getOrderDetails` / `updateNotes` / `removeDeliveryCharge` throw a raw * `Error` -> 500, not 404, for unknown ids. * - `updatePackaged` / `updateDelivered` / `updateOrderItemPackaging` / * `updateAddressCoords` / `cancelOrder` surface their own 404/400 ApiErrors. * - `orderId` for `updatePackaged`/`updateDelivered`/`getSlotOrders` is a string. */ import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api' import { anonClient, staffClient, superadminClient, userClient } from '../helpers/sessions' import { PASSWORD, createAddress, createCatalogOrderFixture, createFutureSlot, createProduct, createStore, placeOrder, registerThrowawayUser, } from '../helpers/fixtures' import { TEST_OTHER_REGION_ID, TEST_REGION_ID } from '../helpers/env' jest.setTimeout(180_000) const REGION_1 = TEST_REGION_ID type CatalogFx = Awaited> /** A staff client scoped to another region (region isolation). */ async function createRegionStaff(regionId: number): Promise { const superadmin = await superadminClient() const roles: any = await superadmin.superadmin.staff.roles.query() const roleId = Number(roles.roles.find((r: any) => r.name === 'admin')?.id ?? roles.roles[0].id) const name = `e2e_order_staff_${uniqueSuffix()}` await superadmin.superadmin.staff.create.mutate({ name, password: PASSWORD, roleId, regionId }) const login: any = await apiClient().admin.staffUser.login.mutate({ name, password: PASSWORD }) return apiClient(login.token) } let region2Promise: Promise | null = null function region2Staff(): Promise { region2Promise ??= createRegionStaff(TEST_OTHER_REGION_ID) return region2Promise } /** Place a COD order from a fixture and return its id. */ async function placeOne(fx: CatalogFx): Promise { const placed = await placeOrder(fx.user.token, { addressId: fx.address.id, skuId: fx.product.skuId, slotId: fx.slot.slotId, }) return Number(placed[0].id) } /** Place a flash order and return its id. */ async function placeFlash(userToken: string, addressId: number, skuId: number): Promise { const res: any = await apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId: null }], addressId, regionId: REGION_1, isFlashDelivery: true, }) return Number(res.data[0].id) } /** The user-facing order read. */ function detail(token: string, orderId: number): Promise { return apiClient(token).user.order.getOrderById.query({ orderId: String(orderId) }) as Promise } /* -------------------------------------------------------------------------- */ /* 1. Reads + pagination (AORD-01..06) */ /* -------------------------------------------------------------------------- */ describe('admin.order.getAll (AORD-01..06)', () => { it('AORD-01: getAll default returns 20 orders with a nextCursor', async () => { const admin = await staffClient() const res: any = await admin.admin.order.getAll.query({}) expect(res.orders).toHaveLength(20) expect(typeof res.nextCursor).toBe('number') const row = res.orders[0] expect(typeof row.id).toBe('number') expect(typeof row.orderId).toBe('string') expect(typeof row.status).toBe('string') expect(Array.isArray(row.items)).toBe(true) // List rows carry the same per-line numbers as the detail view. for (const item of row.items) { expect(typeof item.id).toBe('number') expect(typeof item.quantity).toBe('number') expect(typeof item.price).toBe('number') expect(item.amount).toBe(item.quantity * item.price) } }) it('AORD-02: cursor pagination returns a new page with no overlap', async () => { const admin = await staffClient() const page1: any = await admin.admin.order.getAll.query({ limit: 5 }) expect(page1.orders).toHaveLength(5) expect(typeof page1.nextCursor).toBe('number') const page2: any = await admin.admin.order.getAll.query({ limit: 5, cursor: page1.nextCursor }) expect(page2.orders).toHaveLength(5) const ids1 = page1.orders.map((o: any) => o.id) const ids2 = page2.orders.map((o: any) => o.id) expect(ids1.some((id: number) => ids2.includes(id))).toBe(false) // keyset pagination walks ids descending. expect(Math.max(...ids2)).toBeLessThan(Math.min(...ids1)) }) it('AORD-03 (current): only flashDeliveryFilter is applied; the status filters resolve undefined', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 120 }) const regularId = await placeOne(fx) const store = await createStore() const flashProduct = await createProduct({ storeId: store.storeId, price: 199, isFlashAvailable: true, flashPrice: 149, }) const flashUser = await registerThrowawayUser() const flashAddress = await createAddress(flashUser.token) const flashId = await placeFlash(flashUser.token, flashAddress.id, flashProduct.skuId) const flash: any = await admin.admin.order.getAll.query({ limit: 50, flashDeliveryFilter: 'flash' }) const regular: any = await admin.admin.order.getAll.query({ limit: 50, flashDeliveryFilter: 'regular' }) expect(flash.orders.some((o: any) => o.id === flashId)).toBe(true) expect(flash.orders.some((o: any) => o.id === regularId)).toBe(false) expect(regular.orders.some((o: any) => o.id === regularId)).toBe(true) expect(regular.orders.some((o: any) => o.id === flashId)).toBe(false) // packaged/delivered/cancellation filters join order_status in a relational // where they cannot resolve, so the query throws and getAll swallows it. for (const filter of [ { packagedFilter: 'packaged' }, { deliveredFilter: 'delivered' }, { cancellationFilter: 'cancelled' }, ] as const) { expect(await admin.admin.order.getAll.query({ limit: 5, ...filter })).toBeUndefined() } }) it('AORD-04: the slotId filter returns only that slot’s orders', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const other = await createCatalogOrderFixture({ price: 100 }) const inSlot = await placeOne(fx) const otherSlot = await placeOne(other) const res: any = await admin.admin.order.getAll.query({ limit: 50, slotId: fx.slot.slotId }) const ids = res.orders.map((o: any) => o.id) expect(ids).toContain(inSlot) expect(ids).not.toContain(otherSlot) }) it('AORD-05 (current): limit has a default but no MAX; limit 0 swallows to undefined', async () => { const admin = await staffClient() const emptySlot = await createFutureSlot([]) // No upper bound: a very large limit is accepted (the slot filter keeps the // materialised page empty). const big: any = await admin.admin.order.getAll.query({ limit: 1000, slotId: emptySlot.slotId }) expect(big.orders).toEqual([]) // limit 0 -> hasMore true but the returned page is empty, so the nextCursor // line dereferences [].id and the catch resolves undefined. expect(await admin.admin.order.getAll.query({ limit: 0 })).toBeUndefined() await expectTrpcError( () => admin.admin.order.getAll.query({ limit: 'x' } as any), 'BAD_REQUEST' ) }) it('AORD-06: a slot with no orders returns an empty page', async () => { const admin = await staffClient() const emptySlot = await createFutureSlot([]) const res: any = await admin.admin.order.getAll.query({ limit: 10, slotId: emptySlot.slotId }) expect(res.orders).toEqual([]) expect(res.nextCursor).toBeUndefined() }) }) /* -------------------------------------------------------------------------- */ /* 2. getOrderDetails (AORD-07..09) */ /* -------------------------------------------------------------------------- */ describe('admin.order.getOrderDetails (AORD-07..09)', () => { it('AORD-07: getOrderDetails returns customer, address, slot, items and status', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 250 }) const orderId = await placeOne(fx) const d: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(d).toEqual( expect.objectContaining({ id: orderId, readableId: orderId, userId: fx.user.userId, status: 'pending', isPackaged: false, isDelivered: false, }) ) expect(d.customerMobile).toBe(fx.user.mobile) expect(d.address).toEqual( expect.objectContaining({ name: 'E2E Home', city: 'Mahabubnagar', state: 'Telangana' }) ) expect(d.slotInfo.time).toEqual(expect.any(String)) expect(d.items).toHaveLength(1) const item = d.items[0] expect(item).toEqual( expect.objectContaining({ id: expect.any(Number), name: expect.any(String), skuName: '1pc', // order_items.quantity / .price are TEXT columns, so the admin payload // keeps them as strings; `amount` is computed as a number. quantity: '1', price: '250', amount: 250, }) ) expect(Number(item.amount)).toBe(Number(item.quantity) * Number(item.price)) expect(d.orderStatus).toEqual( expect.objectContaining({ isCancelled: false, isDelivered: false, isPackaged: false }) ) }) it('AORD-08 (current): an unknown order id is an INTERNAL_SERVER_ERROR', async () => { // A plain `Error('Order not found')`, not an ApiError -> tRPC flattens to 500. const admin = await staffClient() await expectTrpcError( () => admin.admin.order.getOrderDetails.query({ orderId: 999_999_999 }), 'INTERNAL_SERVER_ERROR', 'Order not found' ) }) it('AORD-09 (current): another region sees the order as not found', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const region2 = await region2Staff() const list: any = await region2.admin.order.getAll.query({ limit: 50 }) expect(list.orders.some((o: any) => o.id === orderId)).toBe(false) await expectTrpcError( () => region2.admin.order.getOrderDetails.query({ orderId }), 'INTERNAL_SERVER_ERROR', 'Order not found' ) // region 1 still sees it const own: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(own.id).toBe(orderId) }) }) /* -------------------------------------------------------------------------- */ /* 3. updateNotes (AORD-10..12) */ /* -------------------------------------------------------------------------- */ describe('admin.order.updateNotes (AORD-10..12)', () => { it('AORD-10: updateNotes stores adminNotes and returns the order row', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const note = `Handle with care ${uniqueSuffix()}` const res: any = await admin.admin.order.updateNotes.mutate({ orderId, adminNotes: note }) expect(res.id).toBe(orderId) expect(res.adminNotes).toBe(note) const d: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(d.adminNotes).toBe(note) }) it('AORD-11 (current): updateNotes on an unknown order is an INTERNAL_SERVER_ERROR', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.updateNotes.mutate({ orderId: 999_999_999, adminNotes: 'x' }), 'INTERNAL_SERVER_ERROR', 'Order not found' ) }) it('AORD-12: an empty adminNotes is stored as null', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) await admin.admin.order.updateNotes.mutate({ orderId, adminNotes: 'first note' }) const res: any = await admin.admin.order.updateNotes.mutate({ orderId, adminNotes: '' }) expect(res.adminNotes).toBeNull() const d: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(d.adminNotes).toBeNull() }) }) /* -------------------------------------------------------------------------- */ /* 4. updatePackaged / updateDelivered (AORD-13..17) */ /* -------------------------------------------------------------------------- */ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => { it('AORD-13: updatePackaged flips packaging and the user read follows', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const before: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(before.items[0].packagedAt).toBeNull() const packed: any = await admin.admin.order.updatePackaged.mutate({ orderId: String(orderId), isPackaged: true, }) expect(packed).toEqual({ success: true, userId: fx.user.userId }) const afterPacked: any = await detail(fx.user.token, orderId) expect(afterPacked.deliveryStatus).toBe('packaged') expect(afterPacked.orderStatus).toBe('success') // Every item is stamped with the packaging moment. const packedDetail: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(typeof packedDetail.items[0].packagedAt).toBe('string') expect(Number.isNaN(new Date(packedDetail.items[0].packagedAt).getTime())).toBe(false) await admin.admin.order.updatePackaged.mutate({ orderId: String(orderId), isPackaged: false }) const afterUnpacked: any = await detail(fx.user.token, orderId) expect(afterUnpacked.deliveryStatus).toBe('pending') const unpackedDetail: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(unpackedDetail.items[0].packagedAt).toBeNull() }) it('AORD-14: updatePackaged on an unknown order is NOT_FOUND 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.updatePackaged.mutate({ orderId: '999999999', isPackaged: true }), 'NOT_FOUND', 'Order not found' ) }) it('AORD-15: orderId must be a string — a numeric id is BAD_REQUEST', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.updatePackaged.mutate({ orderId: 1 as any, isPackaged: true }), 'BAD_REQUEST' ) }) it('AORD-16: updateDelivered flips delivery and the user read follows', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const before: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(before.deliveredAt).toBeNull() const res: any = await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: true, }) expect(res).toEqual({ success: true, userId: fx.user.userId }) const delivered: any = await detail(fx.user.token, orderId) expect(delivered.orderStatus).toBe('success') expect(delivered.deliveryStatus).toBe('success') // The delivery moment is recorded and survives a repeat "delivered" call. const deliveredDetail: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(typeof deliveredDetail.deliveredAt).toBe('string') expect(Number.isNaN(new Date(deliveredDetail.deliveredAt).getTime())).toBe(false) await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: true }) const repeat: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(repeat.deliveredAt).toBe(deliveredDetail.deliveredAt) await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: false }) const pending: any = await detail(fx.user.token, orderId) expect(pending.orderStatus).toBe('success') expect(pending.deliveryStatus).toBe('pending') const pendingDetail: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(pendingDetail.deliveredAt).toBeNull() }) it('AORD-17: updateDelivered on an unknown order is NOT_FOUND 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.updateDelivered.mutate({ orderId: '999999999', isDelivered: true }), 'NOT_FOUND', 'Order not found' ) }) }) /* -------------------------------------------------------------------------- */ /* 5. updateOrderItemPackaging (AORD-18..20) */ /* -------------------------------------------------------------------------- */ describe('admin.order.updateOrderItemPackaging (AORD-18..20)', () => { it('AORD-18: updateOrderItemPackaging stores both flags', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const d: any = await admin.admin.order.getOrderDetails.query({ orderId }) const itemId = d.items[0].id const res: any = await admin.admin.order.updateOrderItemPackaging.mutate({ orderItemId: itemId, isPackaged: true, isPackageVerified: true, }) expect(res).toEqual({ success: true, updated: true }) const after: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(after.items[0].isPackaged).toBe(true) expect(after.items[0].isPackageVerified).toBe(true) expect(typeof after.items[0].packagedAt).toBe('string') await admin.admin.order.updateOrderItemPackaging.mutate({ orderItemId: itemId, isPackaged: false, }) const unpacked: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(unpacked.items[0].isPackaged).toBe(false) expect(unpacked.items[0].packagedAt).toBeNull() }) it('AORD-19: an unknown order item is NOT_FOUND 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.updateOrderItemPackaging.mutate({ orderItemId: 999_999_999, isPackaged: true, }), 'NOT_FOUND', 'Order item not found' ) }) it('AORD-20: supplying only one flag preserves the other', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const initial: any = await admin.admin.order.getOrderDetails.query({ orderId }) const itemId = initial.items[0].id await admin.admin.order.updateOrderItemPackaging.mutate({ orderItemId: itemId, isPackaged: true }) const afterPack: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(afterPack.items[0].isPackaged).toBe(true) expect(afterPack.items[0].isPackageVerified).toBe(false) await admin.admin.order.updateOrderItemPackaging.mutate({ orderItemId: itemId, isPackageVerified: true }) const afterVerify: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(afterVerify.items[0].isPackaged).toBe(true) // preserved expect(afterVerify.items[0].isPackageVerified).toBe(true) }) }) /* -------------------------------------------------------------------------- */ /* 6. removeDeliveryCharge (AORD-21..22) */ /* -------------------------------------------------------------------------- */ describe('admin.order.removeDeliveryCharge (AORD-21..22)', () => { it('AORD-21: removeDeliveryCharge zeroes the charge and lowers the user total', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) // below free-delivery threshold -> 20 const orderId = await placeOne(fx) const before: any = await detail(fx.user.token, orderId) expect(before.deliveryCharge).toBe(20) const res: any = await admin.admin.order.removeDeliveryCharge.mutate({ orderId }) expect(res).toEqual({ success: true, message: 'Delivery charge removed' }) const after: any = await detail(fx.user.token, orderId) expect(after.deliveryCharge).toBe(0) expect(after.totalAmount).toBe(before.totalAmount - 20) }) it('AORD-22 (current): removeDeliveryCharge on an unknown order is an INTERNAL_SERVER_ERROR', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.removeDeliveryCharge.mutate({ orderId: 999_999_999 }), 'INTERNAL_SERVER_ERROR', 'Order not found' ) }) }) /* -------------------------------------------------------------------------- */ /* 7. getSlotOrders (AORD-23..25) */ /* -------------------------------------------------------------------------- */ describe('admin.order.getSlotOrders (AORD-23..25)', () => { it('AORD-23: getSlotOrders returns the slot’s orders with isFirstOrder flagged', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const res: any = await admin.admin.order.getSlotOrders.query({ slotId: String(fx.slot.slotId) }) expect(res.success).toBe(true) const row = res.data.find((o: any) => o.id === orderId) expect(row).toBeTruthy() expect(row.userId).toBe(fx.user.userId) expect(row.isFirstOrder).toBe(true) // the user's very first order expect(Array.isArray(row.items)).toBe(true) expect(row.status).toBe('pending') }) it('AORD-24: a slot with no orders returns an empty list', async () => { const admin = await staffClient() const emptySlot = await createFutureSlot([]) const res: any = await admin.admin.order.getSlotOrders.query({ slotId: String(emptySlot.slotId) }) expect(res).toEqual({ success: true, data: [] }) }) it('AORD-25 (current): an invalid slot string parses to NaN and returns an empty list', async () => { // parseInt('not-a-slot') -> NaN; the slot lookup misses and the resolver // returns an empty result rather than a validation error. const admin = await staffClient() const res: any = await admin.admin.order.getSlotOrders.query({ slotId: 'not-a-slot' }) expect(res).toEqual({ success: true, data: [] }) }) }) /* -------------------------------------------------------------------------- */ /* 8. updateAddressCoords (AORD-26..28) */ /* -------------------------------------------------------------------------- */ describe('admin.order.updateAddressCoords (AORD-26..28)', () => { it('AORD-26: updateAddressCoords stores admin coordinates', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const res: any = await admin.admin.order.updateAddressCoords.mutate({ addressId: fx.address.id, latitude: 16.75, longitude: 78.02, }) expect(res).toEqual({ success: true }) const slotOrders: any = await admin.admin.order.getSlotOrders.query({ slotId: String(fx.slot.slotId), }) const row = slotOrders.data.find((o: any) => o.id === orderId) expect(row.latitude).toBe(16.75) expect(row.longitude).toBe(78.02) // Attaching real coordinates clears the migration-seeded flag so a later // order read exposes the admin coordinates instead of omitting them. const addresses: any = await apiClient(fx.user.token).user.address.getUserAddresses.query() const addressRow = addresses.data.find((a: any) => a.id === fx.address.id) expect(addressRow.vagueBackfilledCoords).toBe(false) }) it('AORD-27: an unknown address is NOT_FOUND 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.updateAddressCoords.mutate({ addressId: 999_999_999, latitude: 1, longitude: 1, }), 'NOT_FOUND', 'Address not found' ) }) it('AORD-28 (current): admin coordinates are not exposed by the user order read', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) await admin.admin.order.updateAddressCoords.mutate({ addressId: fx.address.id, latitude: 16.75, longitude: 78.02, }) // The user detail has no coordinate fields at all. const userDetail: any = await detail(fx.user.token, orderId) expect('latitude' in userDetail).toBe(false) expect(userDetail.latitude).toBeUndefined() // Only the admin reads surface the admin coordinates. const all: any = await admin.admin.order.getAll.query({ limit: 20, slotId: fx.slot.slotId }) const row = all.orders.find((o: any) => o.id === orderId) expect(row.latitude).toBe(16.75) expect(row.longitude).toBe(78.02) }) }) /* -------------------------------------------------------------------------- */ /* 9. rebalanceSlots (AORD-29..30) */ /* -------------------------------------------------------------------------- */ describe('admin.order.rebalanceSlots (AORD-29..30)', () => { it('AORD-29: rebalanceSlots returns the repriced order ids', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const res: any = await admin.admin.order.rebalanceSlots.mutate({ slotIds: [fx.slot.slotId] }) expect(res.success).toBe(true) expect(res.updatedOrders).toContain(orderId) expect(res.message).toMatch(/Rebalanced \d+ orders?\./) }) it('AORD-30: zero or more than 50 slot ids is BAD_REQUEST', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.rebalanceSlots.mutate({ slotIds: [] }), 'BAD_REQUEST' ) await expectTrpcError( () => admin.admin.order.rebalanceSlots.mutate({ slotIds: Array.from({ length: 51 }, (_, i) => i + 1), }), 'BAD_REQUEST' ) }) }) /* -------------------------------------------------------------------------- */ /* 10. cancelOrder (AORD-31..38) */ /* -------------------------------------------------------------------------- */ describe('admin.order.cancelOrder (AORD-31..38)', () => { it('AORD-31: cancelling a fresh order succeeds and the user sees it cancelled', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) const res: any = await admin.admin.order.cancelOrder.mutate({ orderId, reason: 'customer requested', }) expect(res).toEqual({ success: true, message: 'Order cancelled successfully' }) const userDetail: any = await detail(fx.user.token, orderId) expect(userDetail.deliveryStatus).toBe('cancelled') expect(userDetail.cancelReason).toBe('customer requested') const adminDetail: any = await admin.admin.order.getOrderDetails.query({ orderId }) expect(adminDetail.status).toBe('cancelled') }) it('AORD-32: a blank reason is BAD_REQUEST', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) await expectTrpcError( () => admin.admin.order.cancelOrder.mutate({ orderId, reason: '' }), 'BAD_REQUEST' ) }) it('AORD-33: an unknown order is NOT_FOUND 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.order.cancelOrder.mutate({ orderId: 999_999_999, reason: 'x' }), 'NOT_FOUND', 'Order not found' ) }) it('AORD-34: an already-cancelled order is BAD_REQUEST 400', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) await admin.admin.order.cancelOrder.mutate({ orderId, reason: 'first' }) await expectTrpcError( () => admin.admin.order.cancelOrder.mutate({ orderId, reason: 'again' }), 'BAD_REQUEST', 'already cancelled' ) }) it('AORD-35: a delivered order cannot be cancelled', async () => { const admin = await staffClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: true }) await expectTrpcError( () => admin.admin.order.cancelOrder.mutate({ orderId, reason: 'too late' }), 'BAD_REQUEST', 'Cannot cancel delivered order' ) }) it('AORD-36: cancelling the first order clears the first-order tracker', async () => { const admin = await staffClient() const store = await createStore() const product = await createProduct({ storeId: store.storeId, price: 100 }) const slot1 = await createFutureSlot([product.skuId]) const slot2 = await createFutureSlot([product.skuId]) const user = await registerThrowawayUser() const address = await createAddress(user.token) const first = Number( (await placeOrder(user.token, { addressId: address.id, skuId: product.skuId, slotId: slot1.slotId }))[0].id ) const second = Number( (await placeOrder(user.token, { addressId: address.id, skuId: product.skuId, slotId: slot2.slotId }))[0].id ) const before1: any = await admin.admin.order.getSlotOrders.query({ slotId: String(slot1.slotId) }) expect(before1.data.find((o: any) => o.id === first).isFirstOrder).toBe(true) const before2: any = await admin.admin.order.getSlotOrders.query({ slotId: String(slot2.slotId) }) expect(before2.data.find((o: any) => o.id === second).isFirstOrder).toBe(false) await admin.admin.order.cancelOrder.mutate({ orderId: first, reason: 'clear tracker' }) const after1: any = await admin.admin.order.getSlotOrders.query({ slotId: String(slot1.slotId) }) const after2: any = await admin.admin.order.getSlotOrders.query({ slotId: String(slot2.slotId) }) expect(after1.data.find((o: any) => o.id === first).isFirstOrder).toBe(false) expect(after2.data.find((o: any) => o.id === second).isFirstOrder).toBe(false) }) it('AORD-38 (current): a user token passes protectedProcedure then 500s on staffUser', async () => { const user = await userClient() const fx = await createCatalogOrderFixture({ price: 100 }) const orderId = await placeOne(fx) // getAll swallows the null-deref and resolves undefined. expect(await user.admin.order.getAll.query({ limit: 1 })).toBeUndefined() await expectTrpcError( () => user.admin.order.cancelOrder.mutate({ orderId, reason: 'nope' }), 'INTERNAL_SERVER_ERROR' ) await expectTrpcError( () => user.admin.order.updateNotes.mutate({ orderId, adminNotes: 'nope' }), 'INTERNAL_SERVER_ERROR' ) await expectTrpcError( () => anonClient().admin.order.getAll.query({ limit: 1 }), 'UNAUTHORIZED' ) }) })