mobile-quote-selectors.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import assert from 'node:assert/strict'
  2. import { readFileSync } from 'node:fs'
  3. import test from 'node:test'
  4. import { compile, computed, createSSRApp, effectScope, proxyRefs, ref, watch } from 'vue'
  5. import { renderToString } from 'vue/server-renderer'
  6. import { parse } from '@vue/compiler-sfc'
  7. import ts from 'typescript'
  8. const file = new URL('../src/views/crm/quote/components/QuoteFormPanel.vue', import.meta.url)
  9. const { descriptor } = parse(readFileSync(file, 'utf8'))
  10. const ast = ts.createSourceFile(
  11. 'QuoteFormPanel.ts',
  12. descriptor.scriptSetup!.content,
  13. ts.ScriptTarget.Latest,
  14. true
  15. )
  16. function deferred() {
  17. let resolve!: (value: any) => void
  18. let reject!: (error: Error) => void
  19. const promise = new Promise<any>((yes, no) => {
  20. resolve = yes
  21. reject = no
  22. })
  23. return { promise, resolve, reject }
  24. }
  25. // Run the component's actual mobile declarations with Vue reactivity and transport stubs.
  26. // No component mount, browser, HTTP request, or database is involved.
  27. function harness(page = true) {
  28. const names: string[] = []
  29. const selected = ast.statements.filter((node) => {
  30. if (ts.isVariableStatement(node)) {
  31. const name = node.declarationList.declarations[0].name.getText(ast)
  32. if (
  33. /^(mobile|filteredMobile|scheduleMobile)/.test(name) ||
  34. ['approverPickerOpen', 'extractCustomerList', 'handleAddProduct'].includes(name)
  35. ) {
  36. names.push(name)
  37. return true
  38. }
  39. }
  40. if (ts.isFunctionDeclaration(node)) {
  41. const name = node.name?.text || ''
  42. if (/Mobile|^createMobile|^toggleApprover$/.test(name)) {
  43. names.push(name)
  44. return true
  45. }
  46. }
  47. return (
  48. ts.isExpressionStatement(node) &&
  49. /^(watch\(|onBeforeUnmount\(|useIntersectionObserver\()/.test(node.getText(ast)) &&
  50. /[mM]obile/.test(node.getText(ast))
  51. )
  52. })
  53. const timers = new Map<number, { fn: () => void; at: number }>()
  54. let now = 0
  55. let timerId = 0
  56. const setTimer = (fn: () => void, delay = 0) => {
  57. timers.set(++timerId, { fn, at: now + delay })
  58. return timerId
  59. }
  60. const clearTimer = (id: number) => timers.delete(id)
  61. const advance = async (ms: number) => {
  62. now += ms
  63. for (const [id, timer] of [...timers]) {
  64. if (timer.at > now) continue
  65. timers.delete(id)
  66. timer.fn()
  67. }
  68. for (let i = 0; i < 8; i++) await Promise.resolve()
  69. }
  70. const calls: Array<{ kind: string; query: any; request: ReturnType<typeof deferred> }> = []
  71. const transport = (kind: string) => (query: any) => {
  72. const request = deferred()
  73. calls.push({ kind, query, request })
  74. return request.promise
  75. }
  76. const cleanups: Array<() => void> = []
  77. const observers: Array<() => void> = []
  78. const confirmed: any[][] = []
  79. const bindings = {
  80. ref,
  81. computed,
  82. watch,
  83. setTimeout: setTimer,
  84. clearTimeout: clearTimer,
  85. onBeforeUnmount: (fn: () => void) => cleanups.push(fn),
  86. useIntersectionObserver: (_target: any, fn: any) =>
  87. observers.push(() => fn([{ isIntersecting: true }])),
  88. useDebounceFn: (fn: () => void, delay: number) => {
  89. let id: number
  90. return () => {
  91. clearTimer(id)
  92. id = setTimer(fn, delay)
  93. }
  94. },
  95. isPageVariant: ref(page),
  96. form: ref({ supplierId: 's1', customerId: 'c1', products: [] }),
  97. productSelectorVisible: ref(false),
  98. customerSelectorVisible: ref(false),
  99. opportunitySelectorVisible: ref(false),
  100. contactSelectorVisible: ref(false),
  101. contactOptions: ref([
  102. { id: 'c1', contactName: '张三', mobile: '13812345678' },
  103. { id: 'c2', contactName: '李四', mobile: '13987654321' }
  104. ]),
  105. submitForm: ref({ approverIds: ['u2', 'u1'] }),
  106. userList: ref([
  107. { userId: 'u1', nickName: '张三' },
  108. { userId: 'u2', nickName: '李四' }
  109. ]),
  110. formatApproverOptionLabel: (user: any) => user.nickName,
  111. fetchProductList: transport('product'),
  112. fetchCustomerList: transport('customer'),
  113. listOpportunity: transport('opportunity'),
  114. handleProductConfirm: (items: any[]) => confirmed.push(items),
  115. showFailToast: () => {},
  116. $modal: { msgWarning: () => {} },
  117. loadContactOptions: async () => {},
  118. handleContactConfirm: () => {},
  119. handleOpportunityConfirm: () => {},
  120. hasCustomerShortName: () => true,
  121. handleCustomerConfirm: async () => {}
  122. }
  123. const code = ts.transpile(selected.map((node) => node.getText(ast)).join('\n'), {
  124. target: ts.ScriptTarget.ESNext
  125. })
  126. const scope = effectScope()
  127. const api = scope.run(() =>
  128. new Function(...Object.keys(bindings), `${code}\nreturn { ${names.join(', ')} }`)(
  129. ...Object.values(bindings)
  130. )
  131. )
  132. return {
  133. ...bindings,
  134. ...api,
  135. calls,
  136. confirmed,
  137. observers,
  138. advance,
  139. async flush() {
  140. for (let i = 0; i < 8; i++) await Promise.resolve()
  141. },
  142. async debounce() {
  143. await advance(250)
  144. },
  145. dispose() {
  146. cleanups.forEach((fn) => fn())
  147. scope.stop()
  148. }
  149. }
  150. }
  151. const row = (id: string) => ({ id, productName: id, customerName: id, opportunityName: id })
  152. const response = (ids: string[], total: number | string = ids.length) => ({
  153. data: { list: ids.map(row), total }
  154. })
  155. async function statusMarkup(kind: string, h: any) {
  156. let body: any
  157. const visit = (node: any) => {
  158. if (
  159. node.tag === 'div' &&
  160. node.children?.some(
  161. (child: any) =>
  162. child.tag === 'van-search' && child.loc.source.includes(`mobile${kind}Keyword`)
  163. )
  164. )
  165. body = node
  166. node.children?.forEach(visit)
  167. }
  168. visit(descriptor.template!.ast)
  169. assert.ok(body)
  170. const fragment = body.children
  171. .filter(
  172. (node: any) =>
  173. node.type === 1 && !['van-search', 'van-cell', 'van-checkbox-group'].includes(node.tag)
  174. )
  175. .map((node: any) => node.loc.source)
  176. .join('\n')
  177. const compiled = compile(fragment, { isCustomElement: () => true })
  178. const bindings = proxyRefs(h)
  179. return renderToString(createSSRApp({ render: () => compiled.call(bindings, bindings, []) }))
  180. }
  181. test('product page two failure retries page two without skipping it', async () => {
  182. const h = harness()
  183. const open = h.handleAddProduct()
  184. h.calls[0].request.resolve(response(['p1'], 50))
  185. await open
  186. const more = h.loadMoreMobileProducts()
  187. h.calls[1].request.reject(new Error('offline'))
  188. await more
  189. const retry = h.loadMoreMobileProducts()
  190. assert.equal(h.calls[2].query.page, 2)
  191. h.calls[2].request.resolve(response(['p2'], 50))
  192. await retry
  193. assert.deepEqual(
  194. h.mobileProductList.value.map((item: any) => item.id),
  195. ['p1', 'p2']
  196. )
  197. h.dispose()
  198. })
  199. test('typing invalidates the in-flight product request before the debounce fires', async () => {
  200. const h = harness()
  201. const open = h.handleAddProduct()
  202. h.mobileProductKeyword.value = '乙'
  203. h.onMobileProductKeywordInput?.()
  204. h.calls[0].request.resolve(response(['stale']))
  205. await open
  206. assert.deepEqual(h.mobileProductList.value, [])
  207. await h.debounce()
  208. assert.equal(h.calls.at(-1).query.keyword, '乙')
  209. h.calls.at(-1).request.resolve(response(['new']))
  210. await h.flush()
  211. assert.equal(h.mobileProductList.value[0].id, 'new')
  212. h.dispose()
  213. })
  214. test('old product finally cannot clear loading after closing and reopening', async () => {
  215. const h = harness()
  216. const first = h.handleAddProduct()
  217. h.productSelectorVisible.value = false
  218. const second = h.handleAddProduct()
  219. h.calls[0].request.resolve(response(['stale']))
  220. await first
  221. assert.equal(h.mobileProductLoading.value, true)
  222. assert.deepEqual(h.mobileProductList.value, [])
  223. h.calls[1].request.resolve(response(['fresh']))
  224. await second
  225. h.productSelectorVisible.value = false
  226. const third = h.handleAddProduct()
  227. h.productSelectorVisible.value = false
  228. h.calls[2].request.resolve(response(['closed']))
  229. await third
  230. assert.deepEqual(h.mobileProductList.value, [])
  231. h.dispose()
  232. })
  233. test('cross-search product selection confirms cached objects in selection order', async () => {
  234. const h = harness()
  235. const open = h.handleAddProduct()
  236. h.calls[0].request.resolve(response(['A']))
  237. await open
  238. h.toggleMobileProduct('A')
  239. h.mobileProductKeyword.value = 'B'
  240. const search = h.loadMobileProducts()
  241. h.calls.at(-1).request.resolve(response(['B']))
  242. await search
  243. h.toggleMobileProduct('B')
  244. h.confirmMobileProductPick()
  245. assert.deepEqual(
  246. h.confirmed[0].map((item: any) => item.id),
  247. ['A', 'B']
  248. )
  249. h.dispose()
  250. })
  251. test('supplier or customer changes prevent confirming products from the previous context', async () => {
  252. for (const key of ['supplierId', 'customerId']) {
  253. const h = harness()
  254. const open = h.handleAddProduct()
  255. h.calls[0].request.resolve(response(['A']))
  256. await open
  257. h.toggleMobileProduct('A')
  258. h.form.value[key] = 'changed'
  259. h.confirmMobileProductPick()
  260. assert.equal(h.confirmed.length, 0)
  261. assert.equal(h.productSelectorVisible.value, false)
  262. h.dispose()
  263. }
  264. })
  265. test('customer input and clear search automatically; old responses cannot overwrite newer results', async () => {
  266. const h = harness()
  267. const open = h.openMobileCustomer()
  268. h.calls[0].request.resolve(response(['initial']))
  269. await open
  270. h.mobileCustomerKeyword.value = '池州'
  271. await h.debounce()
  272. assert.equal(h.calls.length, 2)
  273. h.mobileCustomerKeyword.value = '国臣'
  274. await h.debounce()
  275. h.calls[2].request.resolve(response(['current']))
  276. await h.flush()
  277. h.calls[1].request.resolve(response(['old']))
  278. await h.flush()
  279. assert.deepEqual(
  280. h.mobileCustomerList.value.map((item: any) => item.id),
  281. ['current']
  282. )
  283. h.mobileCustomerKeyword.value = ''
  284. await h.debounce()
  285. assert.equal(h.calls[3].query.keyword, undefined)
  286. h.calls[3].request.resolve(response(['cleared']))
  287. await h.flush()
  288. h.dispose()
  289. })
  290. test('customer and opportunity matches beyond thirty remain reachable', async () => {
  291. for (const kind of ['Customer', 'Opportunity']) {
  292. const h = harness()
  293. const open = h[`openMobile${kind}`]()
  294. const rows = Array.from({ length: 30 }, (_, i) => row(String(i)))
  295. h.calls[0].request.resolve(
  296. kind === 'Customer' ? { data: { list: rows, total: '31' } } : { rows, total: '31' }
  297. )
  298. await open
  299. assert.equal(
  300. typeof h[`loadMoreMobile${kind === 'Customer' ? 'Customers' : 'Opportunities'}`],
  301. 'function'
  302. )
  303. const more = h[`loadMoreMobile${kind === 'Customer' ? 'Customers' : 'Opportunities'}`]()
  304. assert.equal(h.calls[1].query.page ?? h.calls[1].query.pageNum, 2)
  305. h.calls[1].request.resolve(
  306. kind === 'Customer' ? response(['30'], 31) : { rows: [row('30')], total: 31 }
  307. )
  308. await more
  309. assert.equal(h[`mobile${kind}List`].value.length, 31)
  310. h.dispose()
  311. }
  312. })
  313. test('opportunity customer change discards the old response and queries the new customer', async () => {
  314. const h = harness()
  315. const open = h.openMobileOpportunity()
  316. h.form.value.customerId = 'c2'
  317. h.calls[0].request.resolve({ rows: [row('old')], total: 1 })
  318. await open
  319. assert.deepEqual(h.mobileOpportunityList.value, [])
  320. await h.debounce()
  321. assert.equal(h.calls[1].query.customerId, 'c2')
  322. h.calls[1].request.resolve({ rows: [row('new')], total: 1 })
  323. await h.flush()
  324. assert.equal(h.mobileOpportunityList.value[0].id, 'new')
  325. h.dispose()
  326. })
  327. test('unmount invalidates unresolved requests and scheduled searches', async () => {
  328. const h = harness()
  329. const open = h.handleAddProduct()
  330. h.mobileProductKeyword.value = 'later'
  331. h.onMobileProductKeywordInput?.()
  332. h.dispose()
  333. h.calls[0].request.resolve(response(['unmounted']))
  334. await open
  335. await h.debounce()
  336. assert.deepEqual(h.mobileProductList.value, [])
  337. assert.equal(h.calls.length, 1)
  338. })
  339. test('mobile contact and approver filters search locally without changing selected order', () => {
  340. const h = harness()
  341. assert.ok(h.mobileContactKeyword)
  342. h.mobileContactKeyword.value = '8765'
  343. assert.deepEqual(
  344. h.filteredMobileContacts.value.map((item: any) => item.id),
  345. ['c2']
  346. )
  347. h.mobileContactKeyword.value = '张'
  348. assert.deepEqual(
  349. h.filteredMobileContacts.value.map((item: any) => item.id),
  350. ['c1']
  351. )
  352. h.mobileApproverKeyword.value = '张'
  353. assert.deepEqual(
  354. h.filteredMobileApprovers.value.map((item: any) => item.userId),
  355. ['u1']
  356. )
  357. assert.deepEqual(h.submitForm.value.approverIds, ['u2', 'u1'])
  358. h.dispose()
  359. })
  360. test('first-page errors expose retry and never masquerade as an empty result', async () => {
  361. for (const kind of ['Product', 'Customer', 'Opportunity']) {
  362. const h = harness()
  363. const open = kind === 'Product' ? h.handleAddProduct() : h[`openMobile${kind}`]()
  364. assert.doesNotMatch(await statusMarkup(kind, h), /暂无/)
  365. h.calls[0].request.reject(new Error('offline'))
  366. await open
  367. const markup = await statusMarkup(kind, h)
  368. assert.match(markup, /加载失败/)
  369. assert.match(markup, /重试/)
  370. assert.doesNotMatch(markup, /暂无/)
  371. h.dispose()
  372. }
  373. })
  374. test('load-more errors retain rows, expose a retry button, and stop automatic retries', async () => {
  375. const h = harness()
  376. const open = h.handleAddProduct()
  377. h.calls[0].request.resolve(response(['A'], 40))
  378. await open
  379. const more = h.loadMoreMobileProducts()
  380. h.calls[1].request.reject(new Error('offline'))
  381. await more
  382. assert.deepEqual(
  383. h.mobileProductList.value.map((item: any) => item.id),
  384. ['A']
  385. )
  386. const markup = await statusMarkup('Product', h)
  387. assert.match(markup, /加载失败/)
  388. assert.match(markup, /重试加载更多/)
  389. h.observers[0]()
  390. assert.equal(h.calls.length, 2)
  391. h.dispose()
  392. })
  393. test('the explicit search action cancels a pending debounce request', async () => {
  394. const h = harness()
  395. const open = h.openMobileCustomer()
  396. h.calls[0].request.resolve(response(['A']))
  397. await open
  398. h.mobileCustomerKeyword.value = 'B'
  399. const search = h.loadMobileCustomers()
  400. h.calls[1].request.resolve(response(['B']))
  401. await search
  402. await h.debounce()
  403. assert.equal(h.calls.length, 2)
  404. h.dispose()
  405. })
  406. test('closing clears pending product choices without writing the form; reopening starts fresh', async () => {
  407. const h = harness()
  408. const open = h.handleAddProduct()
  409. h.calls[0].request.resolve(response(['A']))
  410. await open
  411. h.onMobileProductSelectionChange(['A'])
  412. h.productSelectorVisible.value = false
  413. assert.deepEqual(h.form.value.products, [])
  414. assert.equal(h.confirmed.length, 0)
  415. const reopen = h.handleAddProduct()
  416. h.calls[1].request.resolve(response(['A']))
  417. await reopen
  418. assert.deepEqual(h.mobileProductSelectedIds.value, [])
  419. h.dispose()
  420. })
  421. test('desktop supplier changes and selector visibility never trigger mobile transport or cleanup', async () => {
  422. const h = harness(false)
  423. await h.handleAddProduct()
  424. assert.equal(h.productSelectorVisible.value, true)
  425. h.form.value.supplierId = 's2'
  426. h.form.value.customerId = 'c2'
  427. h.customerSelectorVisible.value = true
  428. h.opportunitySelectorVisible.value = true
  429. h.mobileCustomerKeyword.value = 'A'
  430. await h.debounce()
  431. assert.equal(h.productSelectorVisible.value, true)
  432. assert.equal(h.calls.length, 0)
  433. h.dispose()
  434. })
  435. test('all remote pickers debounce typing for 250 ms and keep their original filters', async () => {
  436. for (const kind of ['Product', 'Customer', 'Opportunity']) {
  437. const h = harness()
  438. const open = kind === 'Product' ? h.handleAddProduct() : h[`openMobile${kind}`]()
  439. h.calls[0].request.resolve(response(['A']))
  440. await open
  441. h[`mobile${kind}Keyword`].value = ' 查询 '
  442. await h.advance(249)
  443. assert.equal(h.calls.length, 1)
  444. await h.advance(1)
  445. assert.equal(h.calls.length, 2)
  446. assert.equal(h.calls[1].query.keyword, '查询')
  447. if (kind === 'Product') {
  448. assert.deepEqual(h.calls[1].query, {
  449. page: 1,
  450. pageSize: 20,
  451. status: 'on',
  452. keyword: '查询',
  453. matchProductNo: false,
  454. matchModel: true,
  455. supplierId: 's1'
  456. })
  457. } else if (kind === 'Opportunity') {
  458. assert.equal(h.calls[1].query.customerId, 'c1')
  459. }
  460. h.calls[1].request.resolve(response(['B']))
  461. await h.flush()
  462. h.dispose()
  463. }
  464. })
  465. test('customer and opportunity closing/reopening discard old success and error responses', async () => {
  466. for (const kind of ['Customer', 'Opportunity']) {
  467. const h = harness()
  468. const visible = h[`${kind.toLowerCase()}SelectorVisible`]
  469. const first = h[`openMobile${kind}`]()
  470. visible.value = false
  471. const second = h[`openMobile${kind}`]()
  472. h.calls[0].request.reject(new Error('stale failure'))
  473. await first
  474. assert.equal(h[`mobile${kind}Loading`].value, true)
  475. assert.equal(h[`mobile${kind}Error`].value, '')
  476. h.calls[1].request.resolve(response(['fresh']))
  477. await second
  478. visible.value = false
  479. const third = h[`openMobile${kind}`]()
  480. visible.value = false
  481. h.calls[2].request.resolve(response(['closed']))
  482. await third
  483. assert.deepEqual(h[`mobile${kind}List`].value, [])
  484. h.dispose()
  485. }
  486. })
  487. test('product checkbox changes preserve cached selection across pages and deselection order', async () => {
  488. const h = harness()
  489. const open = h.handleAddProduct()
  490. h.calls[0].request.resolve(response(['A'], 40))
  491. await open
  492. h.onMobileProductSelectionChange(['A'])
  493. const more = h.loadMoreMobileProducts()
  494. h.calls[1].request.resolve(response(['B'], 40))
  495. await more
  496. h.onMobileProductSelectionChange(['A', 'B'])
  497. h.onMobileProductSelectionChange(['B'])
  498. h.onMobileProductSelectionChange(['B', 'A'])
  499. h.confirmMobileProductPick()
  500. assert.deepEqual(
  501. h.confirmed[0].map((item: any) => item.id),
  502. ['B', 'A']
  503. )
  504. h.dispose()
  505. })