2
0

user-orders-routes.integration.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import { describe, it, expect, beforeEach } from 'vitest';
  2. import { testClient } from 'hono/testing';
  3. import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
  4. import { JWTUtil } from '@d8d/shared-utils';
  5. import { UserEntityMt, RoleMt } from '@d8d/user-module-mt';
  6. import { DeliveryAddressMt } from '@d8d/delivery-address-module-mt';
  7. import { AreaEntityMt } from '@d8d/geo-areas-mt';
  8. import { MerchantMt } from '@d8d/merchant-module-mt';
  9. import { SupplierMt } from '@d8d/supplier-module-mt';
  10. import { FileMt } from '@d8d/file-module-mt';
  11. import { GoodsMt, GoodsCategoryMt } from '@d8d/goods-module-mt';
  12. import userOrderRoutes from '../../src/routes/user/orders.mt';
  13. import { OrderMt, OrderGoodsMt } from '../../src/entities';
  14. import { OrdersTestFactory } from '../factories/orders-test-factory';
  15. // 设置集成测试钩子
  16. setupIntegrationDatabaseHooksWithEntities([
  17. UserEntityMt, RoleMt, OrderMt, OrderGoodsMt, DeliveryAddressMt, MerchantMt, SupplierMt, FileMt, AreaEntityMt, GoodsMt, GoodsCategoryMt
  18. ])
  19. describe('多租户用户订单管理API集成测试', () => {
  20. let client: ReturnType<typeof testClient<typeof userOrderRoutes>>;
  21. let testFactory: OrdersTestFactory;
  22. let userToken: string;
  23. let otherUserToken: string;
  24. let otherTenantUserToken: string;
  25. let testUser: UserEntityMt;
  26. let otherUser: UserEntityMt;
  27. let otherTenantUser: UserEntityMt;
  28. beforeEach(async () => {
  29. // 创建测试客户端
  30. client = testClient(userOrderRoutes);
  31. // 获取数据源并创建测试工厂
  32. const dataSource = await IntegrationTestDatabase.getDataSource();
  33. testFactory = new OrdersTestFactory(dataSource);
  34. // 创建测试用户
  35. testUser = await testFactory.createTestUser(1);
  36. otherUser = await testFactory.createTestUser(1);
  37. otherTenantUser = await testFactory.createTestUser(2);
  38. // 生成JWT令牌
  39. userToken = JWTUtil.generateToken({ id: testUser.id, username: testUser.username, tenantId: 1 });
  40. otherUserToken = JWTUtil.generateToken({ id: otherUser.id, username: otherUser.username, tenantId: 1 });
  41. otherTenantUserToken = JWTUtil.generateToken({ id: otherTenantUser.id, username: otherTenantUser.username, tenantId: 2 });
  42. });
  43. describe('租户数据隔离验证', () => {
  44. it('应该只能访问自己租户的订单', async () => {
  45. // 创建租户1的订单
  46. const tenant1Order = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });
  47. // 创建租户2的订单
  48. const tenant2Order = await testFactory.createTestOrder(otherTenantUser.id, { tenantId: 2 });
  49. // 使用租户1的用户查询订单列表
  50. const response = await client.index.$get({
  51. query: {}
  52. }, {
  53. headers: {
  54. 'Authorization': `Bearer ${userToken}`
  55. }
  56. });
  57. expect(response.status).toBe(200);
  58. if(response.status === 200){
  59. const data = await response.json();
  60. // 应该只返回租户1的订单
  61. expect(data.data).toHaveLength(1);
  62. expect(data.data[0].tenantId).toBe(1);
  63. expect(data.data[0].id).toBe(tenant1Order.id);
  64. }
  65. });
  66. it('不应该访问其他租户的订单详情', async () => {
  67. // 创建租户2的订单
  68. const otherTenantOrder = await testFactory.createTestOrder(otherTenantUser.id, { tenantId: 2 });
  69. // 使用租户1的用户尝试访问租户2的订单
  70. const response = await client[':id'].$get({
  71. param: { id: otherTenantOrder.id }
  72. }, {
  73. headers: {
  74. 'Authorization': `Bearer ${userToken}`
  75. }
  76. });
  77. // 应该返回404,因为订单不在当前租户
  78. expect(response.status).toBe(404);
  79. });
  80. it('应该正确过滤跨租户订单访问', async () => {
  81. // 创建租户1的订单
  82. const tenant1Order = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });
  83. // 使用租户2的用户尝试访问租户1的订单
  84. const response = await client[':id'].$get({
  85. param: { id: tenant1Order.id }
  86. }, {
  87. headers: {
  88. 'Authorization': `Bearer ${otherTenantUserToken}`
  89. }
  90. });
  91. // 应该返回404,因为订单不在当前租户
  92. expect(response.status).toBe(404);
  93. });
  94. });
  95. describe('用户数据权限验证', () => {
  96. it('应该只能访问自己的订单', async () => {
  97. // 创建当前用户的订单
  98. const myOrder = await testFactory.createTestOrder(testUser.id, { tenantId: 1 });
  99. // 创建其他用户的订单(同一租户)
  100. const otherUserOrder = await testFactory.createTestOrder(otherUser.id, { tenantId: 1 });
  101. // 使用当前用户查询订单列表
  102. const response = await client.index.$get({
  103. query: {}
  104. }, {
  105. headers: {
  106. 'Authorization': `Bearer ${userToken}`
  107. }
  108. });
  109. expect(response.status).toBe(200);
  110. if (response.status === 200) {
  111. const data = await response.json();
  112. // 应该只返回当前用户的订单
  113. expect(data.data).toHaveLength(1);
  114. expect(data.data[0].userId).toBe(testUser.id);
  115. expect(data.data[0].id).toBe(myOrder.id);
  116. }
  117. });
  118. it('不应该访问其他用户的订单详情', async () => {
  119. // 创建其他用户的订单
  120. const otherUserOrder = await testFactory.createTestOrder(otherUser.id, { tenantId: 1 });
  121. console.debug('创建的订单:', { id: otherUserOrder.id, userId: otherUserOrder.userId, tenantId: otherUserOrder.tenantId });
  122. // 使用当前用户尝试访问其他用户的订单
  123. const response = await client[':id'].$get({
  124. param: { id: otherUserOrder.id }
  125. }, {
  126. headers: {
  127. 'Authorization': `Bearer ${userToken}`
  128. }
  129. });
  130. // 应该返回403,因为无权访问其他用户的订单
  131. console.debug('响应状态码:', response.status);
  132. expect(response.status).toBe(403);
  133. });
  134. });
  135. describe('订单创建验证', () => {
  136. it('应该自动设置租户ID', async () => {
  137. // 创建必要的关联实体
  138. const testSupplier = await testFactory.createTestSupplier(testUser.id, { tenantId: 1 });
  139. const testMerchant = await testFactory.createTestMerchant(testUser.id, { tenantId: 1 });
  140. const testDeliveryAddress = await testFactory.createTestDeliveryAddress(testUser.id, { tenantId: 1 });
  141. const testGoods = await testFactory.createTestGoods(testUser.id, {
  142. tenantId: 1,
  143. merchantId: testMerchant.id,
  144. supplierId: testSupplier.id
  145. });
  146. const orderData = {
  147. addressId: testDeliveryAddress.id,
  148. productOwn: '自营',
  149. consumeFrom: '积分兑换',
  150. products: [
  151. { id: testGoods.id, num: 2 }
  152. ]
  153. };
  154. const response = await client['create-order'].$post({
  155. json: orderData
  156. }, {
  157. headers: {
  158. 'Authorization': `Bearer ${userToken}`
  159. }
  160. });
  161. console.debug('订单创建响应状态码:', response.status);
  162. if (response.status !== 201) {
  163. const errorResult = await response.json();
  164. console.debug('订单创建错误响应:', errorResult);
  165. }
  166. expect(response.status).toBe(201);
  167. if (response.status === 201) {
  168. const createdOrder = await response.json();
  169. // 验证订单创建成功
  170. expect(createdOrder.success).toBe(true);
  171. expect(createdOrder.orderId).toBeGreaterThan(0);
  172. expect(createdOrder.orderNo).toBeDefined();
  173. expect(createdOrder.amount).toBeGreaterThan(0);
  174. expect(createdOrder.payAmount).toBeGreaterThan(0);
  175. }
  176. });
  177. });
  178. describe('取消订单功能验证', () => {
  179. it('应该成功取消未支付订单', async () => {
  180. // 创建未支付订单
  181. const order = await testFactory.createTestOrder(testUser.id, {
  182. tenantId: 1,
  183. payState: 0, // 未支付
  184. state: 0
  185. });
  186. const cancelData = {
  187. orderId: order.id,
  188. reason: '用户主动取消'
  189. };
  190. const response = await client['cancel-order'].$post({
  191. json: cancelData
  192. }, {
  193. headers: {
  194. 'Authorization': `Bearer ${userToken}`
  195. }
  196. });
  197. expect(response.status).toBe(200);
  198. if (response.status === 200) {
  199. const result = await response.json();
  200. expect(result.success).toBe(true);
  201. expect(result.message).toBe('订单取消成功');
  202. }
  203. // 验证订单状态已更新
  204. const dataSource = await IntegrationTestDatabase.getDataSource();
  205. const updatedOrder = await dataSource.getRepository(OrderMt).findOne({
  206. where: { id: order.id, tenantId: 1 }
  207. });
  208. expect(updatedOrder?.payState).toBe(5); // 订单关闭
  209. expect(updatedOrder?.cancelReason).toBe('用户主动取消');
  210. expect(updatedOrder?.cancelTime).toBeInstanceOf(Date);
  211. });
  212. it('应该成功取消已支付订单', async () => {
  213. // 创建已支付订单
  214. const order = await testFactory.createTestOrder(testUser.id, {
  215. tenantId: 1,
  216. payState: 2, // 支付成功
  217. state: 0
  218. });
  219. const cancelData = {
  220. orderId: order.id,
  221. reason: '用户主动取消(已支付)'
  222. };
  223. const response = await client['cancel-order'].$post({
  224. json: cancelData
  225. }, {
  226. headers: {
  227. 'Authorization': `Bearer ${userToken}`
  228. }
  229. });
  230. expect(response.status).toBe(200);
  231. if (response.status === 200) {
  232. const result = await response.json();
  233. expect(result.success).toBe(true);
  234. expect(result.message).toBe('订单取消成功');
  235. }
  236. // 验证订单状态已更新
  237. const dataSource = await IntegrationTestDatabase.getDataSource();
  238. const updatedOrder = await dataSource.getRepository(OrderMt).findOne({
  239. where: { id: order.id, tenantId: 1 }
  240. });
  241. expect(updatedOrder?.payState).toBe(5); // 订单关闭
  242. expect(updatedOrder?.cancelReason).toBe('用户主动取消(已支付)');
  243. expect(updatedOrder?.cancelTime).toBeInstanceOf(Date);
  244. });
  245. it('应该拒绝取消不允许的订单状态', async () => {
  246. // 创建已发货订单(支付状态=2,订单状态=1)
  247. const order = await testFactory.createTestOrder(testUser.id, {
  248. tenantId: 1,
  249. payState: 2, // 支付成功
  250. state: 1 // 已发货
  251. });
  252. const cancelData = {
  253. orderId: order.id,
  254. reason: '尝试取消已发货订单'
  255. };
  256. const response = await client['cancel-order'].$post({
  257. json: cancelData
  258. }, {
  259. headers: {
  260. 'Authorization': `Bearer ${userToken}`
  261. }
  262. });
  263. // 应该返回403,因为已发货订单不允许取消
  264. expect(response.status).toBe(403);
  265. if (response.status === 403) {
  266. const result = await response.json();
  267. expect(result.message).toBe('当前订单状态不允许取消');
  268. }
  269. });
  270. it('应该拒绝取消不存在的订单', async () => {
  271. const cancelData = {
  272. orderId: 99999, // 不存在的订单ID
  273. reason: '取消不存在的订单'
  274. };
  275. const response = await client['cancel-order'].$post({
  276. json: cancelData
  277. }, {
  278. headers: {
  279. 'Authorization': `Bearer ${userToken}`
  280. }
  281. });
  282. // 应该返回404
  283. expect(response.status).toBe(404);
  284. if (response.status === 404) {
  285. const result = await response.json();
  286. expect(result.message).toBe('订单不存在');
  287. }
  288. });
  289. it('应该拒绝跨租户取消订单', async () => {
  290. // 创建租户2的订单
  291. const otherTenantOrder = await testFactory.createTestOrder(otherTenantUser.id, {
  292. tenantId: 2,
  293. payState: 0
  294. });
  295. const cancelData = {
  296. orderId: otherTenantOrder.id,
  297. reason: '跨租户取消尝试'
  298. };
  299. const response = await client['cancel-order'].$post({
  300. json: cancelData
  301. }, {
  302. headers: {
  303. 'Authorization': `Bearer ${userToken}`
  304. }
  305. });
  306. // 应该返回404,因为订单不在当前租户
  307. expect(response.status).toBe(404);
  308. if (response.status === 404) {
  309. const result = await response.json();
  310. expect(result.message).toBe('订单不存在');
  311. }
  312. });
  313. it('应该拒绝跨用户取消订单', async () => {
  314. // 创建其他用户的订单(同一租户)
  315. const otherUserOrder = await testFactory.createTestOrder(otherUser.id, {
  316. tenantId: 1,
  317. payState: 0
  318. });
  319. const cancelData = {
  320. orderId: otherUserOrder.id,
  321. reason: '跨用户取消尝试'
  322. };
  323. const response = await client['cancel-order'].$post({
  324. json: cancelData
  325. }, {
  326. headers: {
  327. 'Authorization': `Bearer ${userToken}`
  328. }
  329. });
  330. // 应该返回404,因为无权访问其他用户的订单
  331. expect(response.status).toBe(404);
  332. const result = await response.json();
  333. expect(result.message).toBe('订单不存在');
  334. });
  335. });
  336. });