/** * AUSER-01..26 — `admin.user` (catalogue §7.10). * * All procedures are `protectedProcedure`, so a user token passes the guard and * then crashes on `ctx.staffUser!.regionId` → 500 (the §13 gap, AUSER-25). * Users only appear in a region's list/detail when they have an order in that * region (`EXISTS (orders WHERE region_id = staff region)`), so every targeted * fixture places an order first. * * AUSER-09 pins the unchunked `IN (...)` order-history query: at suite scale it * never reaches the SQLite bind limit, so the observable contract is "a normal * history is returned". */ import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api' import { anonClient, staffClient, userClient } from '../helpers/sessions' import { PASSWORD, createCatalogOrderFixture, placeOrder, type CatalogOrderFixture, type CreatedUser, } from '../helpers/fixtures' import { TEST_OTHER_REGION_ID } from '../helpers/env' jest.setTimeout(300_000) /* -------------------------------------------------------------------------- */ /* Helpers */ /* -------------------------------------------------------------------------- */ interface UserWithOrder extends CatalogOrderFixture { order: any } async function userWithOrder(price = 149): Promise { const fixture = await createCatalogOrderFixture({ price }) const orders = await placeOrder(fixture.user.token, { addressId: fixture.address.id, skuId: fixture.product.skuId, slotId: fixture.slot.slotId, }) return { ...fixture, order: orders[0] } } async function findUser(admin: ApiClient, mobile: string): Promise { const res: any = await admin.admin.user.getAllUsers.query({ limit: 10, search: mobile }) return res.users.find((user: any) => user.mobile === mobile) } async function savePushToken(user: CreatedUser, token: string): Promise { const client = apiClient(user.token) await client.user.user.savePushToken.mutate({ token }) } async function createRegionStaff(regionId: number): Promise { const { superadminClient } = await import('../helpers/sessions') 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_auser_${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 otherRegionPromise: Promise | null = null function otherRegion(): Promise { otherRegionPromise ??= createRegionStaff(TEST_OTHER_REGION_ID) return otherRegionPromise } /* -------------------------------------------------------------------------- */ /* Essentials + list */ /* -------------------------------------------------------------------------- */ describe('admin.user.getEssentials / getAllUsers (AUSER-01..05)', () => { it('AUSER-01: getEssentials reports the unresolved-complaints count', async () => { const admin = await staffClient() const res: any = await admin.admin.user.getEssentials.query() expect(res.unresolvedComplaints).toEqual(expect.any(Number)) expect(res.unresolvedComplaints).toBeGreaterThanOrEqual(0) }) it('AUSER-02: getAllUsers paginates and attaches order stats + suspension', async () => { const admin = await staffClient() // 99 is the largest limit the unchunked `IN (...)` can serve under D1's // 100-bind cap (see AUSER-09); the schema still allows 100. const res: any = await admin.admin.user.getAllUsers.query({ limit: 99 }) expect(Array.isArray(res.users)).toBe(true) expect(res.users.length).toBe(99) expect(res.hasMore).toBe(true) expect(res.nextCursor).toBe(res.users[res.users.length - 1].id) for (const user of res.users) { expect(user).toEqual( expect.objectContaining({ id: expect.any(Number), mobile: expect.any(String), totalOrders: expect.any(Number), isSuspended: expect.any(Boolean), }) ) // The list only contains users with an order in the staff region. expect(user.totalOrders).toBeGreaterThan(0) expect(user.lastOrderDate).not.toBeNull() } }) it('AUSER-03 (current): getAllUsers search matches mobile only, not name', async () => { // `getAllUsersWithFilters` pushes `users.mobile LIKE %search%` only; the // name match lives in getUsersForNotification (AUSER-14). const admin = await staffClient() const fixture = await userWithOrder() const byMobile: any = await admin.admin.user.getAllUsers.query({ limit: 10, search: fixture.user.mobile, }) const match = byMobile.users.find((user: any) => user.id === fixture.user.userId) expect(match).toBeTruthy() expect(match.totalOrders).toBeGreaterThanOrEqual(1) const nameFragment = fixture.user.name.split(' ').pop()! const byName: any = await admin.admin.user.getAllUsers.query({ limit: 100, search: nameFragment, }) expect(byName.users.some((user: any) => user.id === fixture.user.userId)).toBe(false) }) it('AUSER-04: cursor pagination does not overlap', async () => { const admin = await staffClient() const page1: any = await admin.admin.user.getAllUsers.query({ limit: 3 }) expect(page1.users).toHaveLength(3) expect(page1.hasMore).toBe(true) const page2: any = await admin.admin.user.getAllUsers.query({ limit: 3, cursor: page1.nextCursor, }) const ids1 = page1.users.map((user: any) => user.id) const ids2 = page2.users.map((user: any) => user.id) expect(ids2.some((id: number) => ids1.includes(id))).toBe(false) expect(Math.min(...ids2)).toBeGreaterThan(Math.max(...ids1)) }) it('AUSER-05: limit above 100 or below 1 is BAD_REQUEST', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.user.getAllUsers.query({ limit: 101 }), 'BAD_REQUEST' ) await expectTrpcError( () => admin.admin.user.getAllUsers.query({ limit: 0 }), 'BAD_REQUEST' ) }) }) /* -------------------------------------------------------------------------- */ /* getUserDetails */ /* -------------------------------------------------------------------------- */ describe('admin.user.getUserDetails (AUSER-06..09)', () => { it('AUSER-06: getUserDetails returns the user and their orders with status/item counts', async () => { const admin = await staffClient() const fixture = await userWithOrder() const res: any = await admin.admin.user.getUserDetails.query({ userId: fixture.user.userId, }) expect(res.user).toEqual( expect.objectContaining({ id: fixture.user.userId, mobile: fixture.user.mobile, isSuspended: false, }) ) expect(res.orders.length).toBeGreaterThanOrEqual(1) const order = res.orders.find((o: any) => Number(o.id) === Number(fixture.order.id)) expect(order).toBeTruthy() expect(['pending', 'delivered', 'cancelled']).toContain(order.status) expect(order.itemCount).toBeGreaterThanOrEqual(1) expect(order.totalAmount).toEqual(expect.anything()) expect(order.readableId).toEqual(expect.anything()) }) it('AUSER-07: an unknown user is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.user.getUserDetails.query({ userId: 999_999_999 }), 'NOT_FOUND', 'User not found' ) }) it('AUSER-08: a user with only another region’s orders is 404', async () => { const admin = await staffClient() const fixture = await userWithOrder() const region2 = await otherRegion() await expectTrpcError( () => region2.admin.user.getUserDetails.query({ userId: fixture.user.userId }), 'NOT_FOUND', 'User not found' ) }) it('AUSER-09 (current): reads work while under D1’s 100-bind cap', async () => { // `getUserOrders` fetches every order id and `getOrderStatusesByOrderIds` // builds one flat `IN (...)` over them (no chunking), so a user with more // than ~99 orders fails the whole detail read with a 500, and the same cap // applies to `getAllUsers` at limit 100. After the local test-data cleanup // no seeded user has that many orders, so the reachable contract is the // normal read; the cap is documented rather than induced here. const admin = await staffClient() const detail: any = await admin.admin.user.getUserDetails.query({ userId: 388 }) expect(detail.user.id).toBe(388) expect(Array.isArray(detail.orders)).toBe(true) const capped: any = await admin.admin.user.getAllUsers.query({ limit: 99 }) expect(capped.users).toHaveLength(99) }) }) /* -------------------------------------------------------------------------- */ /* suspension */ /* -------------------------------------------------------------------------- */ describe('admin.user.updateUserSuspension (AUSER-10..12)', () => { it('AUSER-10: suspending a user is reflected in detail and list', async () => { const admin = await staffClient() const fixture = await userWithOrder() const res: any = await admin.admin.user.updateUserSuspension.mutate({ userId: fixture.user.userId, isSuspended: true, }) expect(res.success).toBe(true) expect(res.message).toMatch(/suspended/i) const detail: any = await admin.admin.user.getUserDetails.query({ userId: fixture.user.userId, }) expect(detail.user.isSuspended).toBe(true) const listed = await findUser(admin, fixture.user.mobile) expect(listed?.isSuspended).toBe(true) }) it('AUSER-11: unsuspending a user is reflected', async () => { const admin = await staffClient() const fixture = await userWithOrder() await admin.admin.user.updateUserSuspension.mutate({ userId: fixture.user.userId, isSuspended: true, }) const res: any = await admin.admin.user.updateUserSuspension.mutate({ userId: fixture.user.userId, isSuspended: false, }) expect(res.message).toMatch(/unsuspended/i) const detail: any = await admin.admin.user.getUserDetails.query({ userId: fixture.user.userId, }) expect(detail.user.isSuspended).toBe(false) }) it('AUSER-12 (current): an unknown user id is upserted as suspended, not rejected', async () => { // `upsertUserSuspension` inserts a `user_details` row with no existence // check and no FK enforcement, so an unknown id succeeds silently; the user // still has no order, so the detail read stays 404. const admin = await staffClient() const ghostId = 999_999_000 + Math.floor(Math.random() * 1000) const res: any = await admin.admin.user.updateUserSuspension.mutate({ userId: ghostId, isSuspended: true, }) expect(res.success).toBe(true) await expectTrpcError( () => admin.admin.user.getUserDetails.query({ userId: ghostId }), 'NOT_FOUND' ) }) }) /* -------------------------------------------------------------------------- */ /* notifications */ /* -------------------------------------------------------------------------- */ describe('admin.user notifications (AUSER-13..19)', () => { }) /* -------------------------------------------------------------------------- */ /* incidents */ /* -------------------------------------------------------------------------- */ describe('admin.user incidents (AUSER-20..23)', () => { it('AUSER-20: getUserIncidents returns incidents with the related order status', async () => { const admin = await staffClient() const fixture = await userWithOrder() await admin.admin.user.addUserIncident.mutate({ userId: fixture.user.userId, orderId: Number(fixture.order.id), adminComment: 'E2E incident', negativityScore: 3, }) const res: any = await admin.admin.user.getUserIncidents.query({ userId: fixture.user.userId, }) const incident = res.incidents.find((i: any) => Number(i.orderId) === Number(fixture.order.id)) expect(incident).toBeTruthy() expect(incident).toEqual( expect.objectContaining({ userId: fixture.user.userId, adminComment: 'E2E incident', negativityScore: 3, orderStatus: 'active', addedBy: expect.any(String), }) ) }) it('AUSER-21: an unknown user has no incidents', async () => { const admin = await staffClient() const res: any = await admin.admin.user.getUserIncidents.query({ userId: 999_999_999 }) expect(res.incidents).toEqual([]) }) it('AUSER-22: addUserIncident creates the incident', async () => { const admin = await staffClient() const fixture = await userWithOrder() const res: any = await admin.admin.user.addUserIncident.mutate({ userId: fixture.user.userId, orderId: Number(fixture.order.id), adminComment: 'Created by AUSER-22', negativityScore: 7, }) expect(res.success).toBe(true) expect(res.data).toEqual( expect.objectContaining({ id: expect.any(Number), userId: fixture.user.userId, orderId: Number(fixture.order.id), negativityScore: 7, }) ) const read: any = await admin.admin.user.getUserIncidents.query({ userId: fixture.user.userId, }) expect(read.incidents.some((i: any) => i.id === res.data.id)).toBe(true) }) it('AUSER-23: optional order/comment/score accept nulls', async () => { const admin = await staffClient() const fixture = await userWithOrder() const res: any = await admin.admin.user.addUserIncident.mutate({ userId: fixture.user.userId, }) expect(res.success).toBe(true) expect(res.data).toEqual( expect.objectContaining({ userId: fixture.user.userId, orderId: null, adminComment: null, negativityScore: null, }) ) }) }) /* -------------------------------------------------------------------------- */ /* auth + isolation */ /* -------------------------------------------------------------------------- */ describe('admin.user auth + isolation (AUSER-24..26)', () => { it('AUSER-24: an anonymous caller is 401', async () => { const anon = anonClient() await expectTrpcError(() => anon.admin.user.getEssentials.query(), 'UNAUTHORIZED') await expectTrpcError( () => anon.admin.user.getAllUsers.query({ limit: 5 }), 'UNAUTHORIZED' ) }) it('AUSER-25 (current): a user token crashes on ctx.staffUser → 500', async () => { // `protectedProcedure` admits the user token, then `ctx.staffUser!.regionId` // dereferences null (the §13 protectedProcedure gap). const user = await userClient() await expectTrpcError(() => user.admin.user.getEssentials.query(), 'INTERNAL_SERVER_ERROR') }) it('AUSER-26: another region cannot see the user', async () => { const fixture = await userWithOrder() const region2 = await otherRegion() await expectTrpcError( () => region2.admin.user.getUserDetails.query({ userId: fixture.user.userId }), 'NOT_FOUND' ) const incidents: any = await region2.admin.user.getUserIncidents.query({ userId: fixture.user.userId, }) expect(incidents.incidents).toEqual([]) const search: any = await region2.admin.user.getAllUsers.query({ limit: 10, search: fixture.user.mobile, }) expect(search.users.some((user: any) => user.id === fixture.user.userId)).toBe(false) }) })