mobile-customer-detail-lifecycle.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import assert from 'node:assert/strict'
  2. import test from 'node:test'
  3. import { readFileSync, existsSync } from 'node:fs'
  4. import { parse } from '@vue/compiler-sfc'
  5. import ts from 'typescript'
  6. import * as vue from 'vue'
  7. import { useClientColumnFilters } from '../src/composables/useClientColumnFilters'
  8. import * as customerFilterDefinitions from '../src/views/crm/customer/dialogColumnFilterDefs'
  9. function deferred() {
  10. let resolve!: (value?: any) => void
  11. let reject!: (error: any) => void
  12. const promise = new Promise<any>((a, b) => {
  13. resolve = a
  14. reject = b
  15. })
  16. return { promise, resolve, reject }
  17. }
  18. const flush = async () => {
  19. for (let i = 0; i < 20; i++) await Promise.resolve()
  20. }
  21. // Execute actual script-setup functions inside Vue's renderer; API responses alone are deferred.
  22. const helperPath = new URL('../src/utils/mp-customer-panel-identity.ts', import.meta.url)
  23. function evaluate(page: string, props: any, overrides: Record<string, any>, events: any[]) {
  24. const source = parse(
  25. readFileSync(new URL(`../src/views/m/crm/customer/${page}.vue`, import.meta.url), 'utf8')
  26. ).descriptor.scriptSetup!.content
  27. const ast = ts.createSourceFile('panel.ts', source, ts.ScriptTarget.Latest, true)
  28. const vueEntries = Object.entries(vue).filter(
  29. ([k]) => /^[a-zA-Z_$][\w$]*$/.test(k) && k !== 'default'
  30. )
  31. const bindings: Record<string, any> = Object.fromEntries(vueEntries)
  32. delete bindings.default
  33. for (const statement of ast.statements) {
  34. if (!ts.isImportDeclaration(statement)) continue
  35. const clause = statement.importClause
  36. if (clause?.name) bindings[clause.name.text] = () => undefined
  37. if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings))
  38. for (const item of clause.namedBindings.elements) bindings[item.name.text] = () => undefined
  39. }
  40. if (existsSync(helperPath)) {
  41. const helper = ts.transpile(
  42. readFileSync(helperPath, 'utf8').replace('export function', 'function'),
  43. { target: ts.ScriptTarget.ESNext }
  44. )
  45. bindings.useCustomerPanelIdentity = new Function(
  46. ...vueEntries.map(([k]) => k),
  47. `${helper};return useCustomerPanelIdentity`
  48. )(...vueEntries.map(([, v]) => v))
  49. }
  50. Object.assign(bindings, {
  51. useClientColumnFilters,
  52. ...customerFilterDefinitions,
  53. defineProps: () => props,
  54. defineEmits:
  55. () =>
  56. (...args: any[]) =>
  57. events.push(args),
  58. defineExpose() {},
  59. useDictStore: () => ({ getOptions: () => [], getLabel: () => '', getTagType: () => '' }),
  60. unwrapRows: (v: any) => (Array.isArray(v) ? v : v?.data?.rows || v?.data || v?.rows || []),
  61. unwrapData: (v: any) => v?.data || v,
  62. canDeleteByCreator: () => true,
  63. contactFields: [{ key: 'contactName', required: true }],
  64. requiredFieldsError: () => '',
  65. contactDetailsError: () => '',
  66. showCrmConfirmDialog: async () => {},
  67. fetchContactByCustomerId: async () => [],
  68. fetchContactDetail: async (v: any) => v,
  69. ...overrides
  70. })
  71. const statements = ast.statements.filter((s) => !ts.isImportDeclaration(s))
  72. const names = statements.flatMap((s) =>
  73. ts.isFunctionDeclaration(s)
  74. ? [s.name!.text]
  75. : ts.isVariableStatement(s)
  76. ? s.declarationList.declarations.map((d) => d.name.getText(ast))
  77. : []
  78. )
  79. const code = ts.transpile(statements.map((s) => s.getText(ast)).join('\n'), {
  80. target: ts.ScriptTarget.ESNext
  81. })
  82. return new Function(...Object.keys(bindings), `${code};return {${names.join(',')}}`)(
  83. ...Object.values(bindings)
  84. )
  85. }
  86. const detailRoute = (id = 'A', tab = 'basic') => ({
  87. name: 'MpCrmCustomerDetail',
  88. path: `/m/crm/customer/${id}`,
  89. params: { id },
  90. query: { tab }
  91. })
  92. function mount(initial = detailRoute(), withChild = false) {
  93. const current = vue.shallowRef(initial)
  94. const route = Object.fromEntries(['name', 'path', 'params', 'query'].map((key) => [key, null]))
  95. for (const key of Object.keys(route))
  96. Object.defineProperty(route, key, { get: () => current.value[key] })
  97. const reads: any[] = [],
  98. writes: any[] = [],
  99. messages: any[] = [],
  100. navigation: any[] = []
  101. const confirm = deferred()
  102. let api: any
  103. let child: any
  104. const childRead = deferred()
  105. const childWrites: any[] = []
  106. const renderer = vue.createRenderer<any, any>({
  107. patchProp() {},
  108. insert() {},
  109. remove() {},
  110. createElement: () => ({}),
  111. createText: () => ({}),
  112. createComment: () => ({}),
  113. setText() {},
  114. setElementText() {},
  115. parentNode: () => null,
  116. nextSibling: () => null
  117. })
  118. const Child = vue.defineComponent({
  119. props: ['customerId', 'getIdentity'],
  120. setup(props) {
  121. child = evaluate(
  122. 'ContactPanel',
  123. props,
  124. {
  125. fetchContactByCustomerId: () => childRead.promise,
  126. showCrmConfirmDialog: () => confirm.promise,
  127. fetchDeleteContact: async (value: any) => childWrites.push(value)
  128. },
  129. []
  130. )
  131. return () => vue.h('div')
  132. }
  133. })
  134. const app = renderer.createApp({
  135. setup() {
  136. api = evaluate(
  137. 'detail',
  138. {},
  139. {
  140. useRoute: () => route,
  141. useRouter: () => ({
  142. replace: (v: any) => navigation.push(v),
  143. push: (v: any) => navigation.push(v)
  144. }),
  145. fetchCustomerDetail: (params: any) => {
  146. const d = deferred()
  147. reads.push({ ...d, params })
  148. return d.promise
  149. },
  150. fetchDeleteCustomer: (params: any) => {
  151. const d = deferred()
  152. writes.push({ ...d, params })
  153. return d.promise
  154. },
  155. showCrmConfirmDialog: () => confirm.promise,
  156. customerForm: (v: any) => v,
  157. showFailToast: (v: any) => messages.push(v),
  158. showSuccessToast: (v: any) => messages.push(v)
  159. },
  160. []
  161. )
  162. return () =>
  163. withChild && api.customer.value && !api.loading.value
  164. ? vue.h(Child, { customerId: api.id.value, getIdentity: api.getPanelIdentity })
  165. : vue.h('div')
  166. }
  167. })
  168. app.mount({})
  169. return {
  170. api,
  171. reads,
  172. writes,
  173. messages,
  174. navigation,
  175. confirm,
  176. childRead,
  177. childWrites,
  178. get child() {
  179. return child
  180. },
  181. go: (value: any) => {
  182. current.value = value
  183. },
  184. unmount: () => app.unmount()
  185. }
  186. }
  187. const destinations = [
  188. { name: 'MpCrmCustomerList', path: '/m/crm/customer', params: {}, query: {} },
  189. { name: 'MpCrmProductDetail', path: '/m/crm/product/B', params: { id: 'B' }, query: {} },
  190. { name: 'MpCrmProductDetail', path: '/m/crm/product/A', params: { id: 'A' }, query: {} },
  191. { name: 'MpCrmCustomerEdit', path: '/m/crm/customer/A/edit', params: { id: 'A' }, query: {} },
  192. detailRoute('')
  193. ]
  194. for (const destination of destinations) {
  195. test(`leave to ${destination.name}/${destination.params.id || 'empty'} blocks all reads and invalidates synchronously`, async () => {
  196. const h = mount()
  197. h.api.onReady()
  198. const key = h.api.getPanelIdentity()
  199. h.go(destination)
  200. assert.notEqual(h.api.getPanelIdentity(), key)
  201. assert.equal(h.reads.length, 1, 'leaving must not request a customer')
  202. await h.api.load()
  203. await h.api.load('A')
  204. await h.api.refreshInfo()
  205. h.api.onReady()
  206. assert.equal(h.reads.length, 1)
  207. h.reads[0].resolve({ id: 'A', customerName: 'stale' })
  208. await flush()
  209. assert.equal(h.api.customer.value, undefined)
  210. assert.equal(h.api.error.value, '')
  211. assert.deepEqual(h.messages, [])
  212. h.unmount()
  213. })
  214. }
  215. test('ready gate, same-ID tab/query changes, retries and same-path reloads', async () => {
  216. const h = mount()
  217. await h.api.load()
  218. await h.api.refreshInfo()
  219. h.go(detailRoute('B'))
  220. assert.equal(h.reads.length, 0)
  221. h.api.onReady()
  222. h.api.onReady()
  223. assert.equal(h.reads.length, 1)
  224. assert.equal(h.reads[0].params.id, 'B')
  225. h.go(detailRoute('B', 'contact'))
  226. assert.equal(h.api.tab.value, 'contact')
  227. assert.equal(h.reads.length, 1)
  228. h.reads[0].reject(new Error('retryable'))
  229. await flush()
  230. assert.equal(h.api.error.value, 'retryable')
  231. const retry = h.api.load()
  232. h.reads[1].resolve({ id: 'B' })
  233. await retry
  234. const reload = h.api.load()
  235. h.reads[2].resolve({ id: 'B' })
  236. await reload
  237. const refresh = h.api.refreshInfo()
  238. h.reads[3].resolve({ id: 'B', customerName: 'fresh' })
  239. await refresh
  240. assert.equal(h.api.customer.value.customerName, 'fresh')
  241. h.unmount()
  242. })
  243. for (const aba of [false, true])
  244. for (const rejectOld of [false, true]) {
  245. test(`latest route wins: ABA=${aba} reject=${rejectOld}`, async () => {
  246. const h = mount()
  247. h.api.onReady()
  248. h.go(detailRoute('B'))
  249. if (aba) h.go(detailRoute('A'))
  250. const latest = h.reads.at(-1)
  251. for (const read of h.reads.slice(0, -1)) {
  252. if (rejectOld) read.reject(new Error('old failure'))
  253. else read.resolve({ id: read.params.id, customerName: 'stale' })
  254. }
  255. await flush()
  256. assert.equal(h.api.loading.value, true)
  257. assert.equal(h.api.error.value, '')
  258. assert.equal(h.api.customer.value, undefined)
  259. latest.resolve({ id: latest.params.id, customerName: 'latest' })
  260. await flush()
  261. assert.equal(h.api.customer.value.customerName, 'latest')
  262. h.unmount()
  263. })
  264. }
  265. test('customer detail has no deletion entry and leaving prevents stale edit navigation', async () => {
  266. const h = mount()
  267. h.api.onReady()
  268. h.reads[0].resolve({ id: 'A' })
  269. await flush()
  270. assert.equal(h.api.remove, undefined)
  271. h.go(destinations[2])
  272. h.api.goEdit()
  273. assert.deepEqual(h.writes, [])
  274. assert.deepEqual(h.navigation, [])
  275. h.unmount()
  276. })
  277. for (const destination of destinations)
  278. test(`late ready outside valid detail: ${destination.name}/${destination.params.id || 'empty'}`, async () => {
  279. const h = mount()
  280. h.go(destination)
  281. h.api.onReady()
  282. assert.equal(h.reads.length, 0)
  283. h.unmount()
  284. })
  285. test('refresh failure after same-ID leave is silent; reentry can load', async () => {
  286. const h = mount()
  287. h.api.onReady()
  288. h.reads[0].resolve({ id: 'A' })
  289. await flush()
  290. const refresh = h.api.refreshInfo()
  291. h.go(destinations[2])
  292. h.reads[1].reject(new Error('old refresh'))
  293. await refresh
  294. assert.deepEqual(h.messages, [])
  295. h.go(detailRoute())
  296. assert.equal(h.reads.length, 3)
  297. h.reads[2].resolve({ id: 'A', customerName: 'back' })
  298. await flush()
  299. assert.equal(h.api.customer.value.customerName, 'back')
  300. h.unmount()
  301. })
  302. test('same-ID leave invalidates real child panel reads and confirmations before unmount', async () => {
  303. const h = mount(detailRoute(), true)
  304. h.api.onReady()
  305. h.reads[0].resolve({ id: 'A' })
  306. await flush()
  307. const child = h.child
  308. const pending = child.remove({ id: 'contact-A' })
  309. h.confirm.resolve()
  310. h.childRead.resolve([{ id: 'stale' }])
  311. h.go(destinations[2])
  312. assert.deepEqual(child.rows.value, [])
  313. assert.equal(child.acting.value, false)
  314. await pending
  315. await flush()
  316. assert.deepEqual(h.childWrites, [])
  317. assert.deepEqual(child.rows.value, [])
  318. h.unmount()
  319. })
  320. test('unmount makes pending reads and all entry points inert', async () => {
  321. const h = mount()
  322. h.api.onReady()
  323. h.unmount()
  324. h.reads[0].reject(new Error('late'))
  325. await flush()
  326. await h.api.load()
  327. await h.api.refreshInfo()
  328. h.api.onReady()
  329. assert.equal(h.reads.length, 1)
  330. assert.equal(h.api.error.value, '')
  331. assert.deepEqual(h.messages, [])
  332. })