mobile-product-list.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import assert from 'node:assert/strict'
  2. import test from 'node:test'
  3. import { existsSync, readFileSync } from 'node:fs'
  4. async function model() {
  5. assert.ok(
  6. existsSync(new URL('../src/views/m/crm/product/listState.ts', import.meta.url)),
  7. 'mobile product list state must exist'
  8. )
  9. return import('../src/views/m/crm/product/listState')
  10. }
  11. test('enum selections and all numeric operators serialize to Web queries; invalid ranges are rejected', async () => {
  12. const m = await model()
  13. const draft = m.createProductFilterDraft({ productNoIn: 'P1,P2', priceOp: 'gte', price: 0 })
  14. assert.deepEqual(m.productFilterQuery(draft), {
  15. productNoIn: 'P1,P2',
  16. priceOp: 'gte',
  17. price: '0'
  18. })
  19. for (const op of ['eq', 'gt', 'gte', 'lt', 'lte'] as const) {
  20. draft.cost = { op, value: '12.5', min: '', max: '' }
  21. assert.equal(m.productFilterQuery(draft).costOp, op)
  22. assert.equal(m.productFilterQuery(draft).cost, '12.5')
  23. }
  24. draft.cost = { op: 'between', value: '', min: '20', max: '10' }
  25. assert.throws(() => m.productFilterQuery(draft), /最低值不能大于最高值/)
  26. })
  27. test('hidden columns drop related filters, reset keeps keyword, and facets exclude self and pagination', async () => {
  28. const m = await model()
  29. const query = {
  30. keyword: '酸',
  31. categoryId: 'C',
  32. categoryNameIn: '化工',
  33. model: '快速',
  34. modelIn: '精确',
  35. priceOp: 'gte',
  36. price: 0,
  37. productNameIn: '产品',
  38. statusIn: 'off'
  39. }
  40. assert.deepEqual(m.cleanProductQuery(query, []), {
  41. keyword: '酸',
  42. productNameIn: '产品',
  43. statusIn: 'off'
  44. })
  45. assert.deepEqual(m.cleanProductQuery(query, [], true), { keyword: '酸', statusIn: 'off' })
  46. assert.deepEqual(
  47. m.buildMobileProductQuery({
  48. query,
  49. keyword: '酸',
  50. categoryId: 'C',
  51. model: '快速',
  52. visible: m.productColumnDefs.map((d) => d.prop),
  53. page: 3,
  54. pageSize: 20
  55. }),
  56. {
  57. keyword: '酸',
  58. categoryNameIn: '化工',
  59. modelIn: '精确',
  60. productNameIn: '产品',
  61. statusIn: 'on',
  62. page: 3,
  63. pageSize: 20
  64. }
  65. )
  66. const facet = m.productFacetQuery({ ...query, page: 2, pageSize: 20 }, 'categoryName')
  67. assert.equal(facet.categoryId, undefined)
  68. assert.equal(facet.categoryNameIn, undefined)
  69. assert.equal(facet.page, undefined)
  70. assert.equal(facet.keyword, '酸')
  71. assert.equal(facet.limit, 500)
  72. })
  73. import { parse } from '@vue/compiler-sfc'
  74. import * as Vue from 'vue'
  75. import ts from 'typescript'
  76. import { buildProductCard } from '../src/utils/mp-crm-product-card'
  77. async function harness(page: string, props: any = {}, overrides: Record<string, any> = {}) {
  78. const path = new URL(`../src/views/m/crm/product/${page}.vue`, import.meta.url)
  79. assert.ok(existsSync(path), `${page} must exist`)
  80. const source = readFileSync(path, 'utf8')
  81. const ast = ts.createSourceFile(
  82. 'page.ts',
  83. parse(source).descriptor.scriptSetup!.content,
  84. ts.ScriptTarget.Latest,
  85. true
  86. )
  87. const statements = ast.statements.filter((s) => !ts.isImportDeclaration(s))
  88. const names = statements.flatMap((s) =>
  89. ts.isFunctionDeclaration(s) && s.name
  90. ? [s.name.text]
  91. : ts.isVariableStatement(s)
  92. ? s.declarationList.declarations.flatMap((d) =>
  93. ts.isIdentifier(d.name)
  94. ? [d.name.text]
  95. : ts.isObjectBindingPattern(d.name)
  96. ? d.name.elements.map((e) => e.name.getText(ast))
  97. : []
  98. )
  99. : []
  100. )
  101. const bindings: Record<string, any> = { ...Vue }
  102. for (const s of ast.statements)
  103. if (ts.isImportDeclaration(s)) {
  104. if (s.importClause?.name) bindings[s.importClause.name.text] = () => {}
  105. const n = s.importClause?.namedBindings
  106. if (n && ts.isNamedImports(n)) for (const e of n.elements) bindings[e.name.text] = () => {}
  107. }
  108. const requests: any[] = [],
  109. statuses: any[] = [],
  110. deletes: any[] = [],
  111. events: any[] = [],
  112. facets: any[] = []
  113. const user = Vue.reactive({ accessToken: 'token1', getUserInfo: { id: 'u1' } })
  114. let facetFail = false
  115. Object.assign(bindings, await model(), {
  116. buildProductCard,
  117. defineProps: () => props,
  118. defineEmits:
  119. () =>
  120. (...args: any[]) =>
  121. events.push(args),
  122. useRouter: () => ({ push: () => {} }),
  123. useUserStore: () => user,
  124. useListReturnState: () => ({ restoring: Vue.ref(false), restore: async () => {} }),
  125. useIntersectionObserver: () => {},
  126. useDebounceFn: (fn: any) => fn,
  127. canDeleteByCreator: (row: any) => row.createBy === user.getUserInfo.id,
  128. fetchCategoryTree: async () => [],
  129. buildPathLabelMapFromTreeRoots: () => new Map(),
  130. fetchProductList: async (q: any) => {
  131. requests.push(q)
  132. return { list: [], total: 0 }
  133. },
  134. fetchProductColumnFacetValues: async (q: any) => {
  135. facets.push(q)
  136. if (facetFail) throw new Error('离线')
  137. return {
  138. list: [
  139. { value: 'A', label: '甲' },
  140. { value: 'B', label: '乙' }
  141. ]
  142. }
  143. },
  144. showProductConfirmDialog: async () => {},
  145. fetchUpdateProductStatus: async (q: any) => statuses.push(q),
  146. fetchDeleteProduct: async (q: any) => deletes.push(q),
  147. HttpError: class extends Error {},
  148. ApiStatus: { forbidden: 403 },
  149. onMounted: () => {},
  150. onBeforeUnmount: () => {}
  151. })
  152. Object.assign(bindings, overrides)
  153. for (const k of Object.keys(bindings))
  154. if (!/^[a-zA-Z_$][\w$]*$/.test(k) || k === 'default') delete bindings[k]
  155. const code = ts.transpile(statements.map((s) => s.getText(ast)).join('\n'), {
  156. target: ts.ScriptTarget.ESNext
  157. })
  158. const scope = Vue.effectScope()
  159. const api = scope.run(() =>
  160. new Function(...Object.keys(bindings), `${code}; return {${names.join(',')}}`)(
  161. ...Object.values(bindings)
  162. )
  163. )
  164. return {
  165. api,
  166. requests,
  167. statuses,
  168. deletes,
  169. events,
  170. facets,
  171. user,
  172. failFacet: (v: boolean) => {
  173. facetFail = v
  174. },
  175. stop: () => scope.stop()
  176. }
  177. }
  178. test('fixed product columns retain ordinary filters and discard hidden legacy conditions', async () => {
  179. const h = await harness('index')
  180. try {
  181. h.api.products.value = [{ id: '1', productName: '产品', createBy: 'u1', cost: 10 }]
  182. assert.equal(h.api.cards.value[0].previewFields.length, 6)
  183. assert.equal(h.api.cards.value[0].extraFields.length, 0)
  184. h.api.query.value = { productNameIn: 'P', costOp: 'gt', cost: 1 }
  185. h.api.keyword.value = '酸'
  186. await h.api.fetchPage(true)
  187. assert.equal(h.requests.at(-1).productNameIn, 'P')
  188. assert.equal(h.requests.at(-1).keyword, '酸')
  189. assert.equal(h.requests.at(-1).cost, undefined)
  190. h.user.accessToken = 'token2'
  191. assert.deepEqual(h.api.products.value, [])
  192. } finally {
  193. h.stop()
  194. }
  195. })
  196. test('single product status change guards duplicate submission without a delete entry', async () => {
  197. const h = await harness('index')
  198. try {
  199. assert.equal(h.api.deleteCard, undefined)
  200. assert.equal(h.deletes.length, 0)
  201. const card = { id: '1', createBy: 'u1', status: 'on' }
  202. await Promise.all([h.api.toggleStatus(card), h.api.toggleStatus(card)])
  203. assert.deepEqual(h.statuses, [{ ids: ['1'], status: 'off' }])
  204. assert.deepEqual(h.deletes, [])
  205. } finally {
  206. h.stop()
  207. }
  208. })
  209. test('facet uses applied context, preserves selections, searches locally and retries failure', async () => {
  210. const props = Vue.reactive({
  211. modelValue: true,
  212. query: { brandsIn: 'A' },
  213. context: { keyword: '酸', brandsIn: 'A', modelIn: 'M', page: 2 },
  214. visibleColumns: ['brands']
  215. })
  216. const h = await harness('ProductFilters', props)
  217. try {
  218. h.failFacet(true)
  219. await h.api.loadFacet('brands')
  220. assert.match(h.api.facetErrors.brands, /离线/)
  221. h.failFacet(false)
  222. await h.api.loadFacet('brands')
  223. assert.equal(h.api.facetErrors.brands, '')
  224. assert.deepEqual(h.facets.at(-1), { keyword: '酸', modelIn: 'M', field: 'brands', limit: 500 })
  225. h.api.searches.brands = '甲'
  226. assert.deepEqual(
  227. h.api.optionsFor('brands').map((x: any) => x.value),
  228. ['A']
  229. )
  230. assert.deepEqual(h.api.draft.value.brands, ['A'])
  231. props.visibleColumns = []
  232. await Vue.nextTick()
  233. assert.deepEqual(h.api.draft.value.brands, [])
  234. h.api.draft.value.price = { op: 'between', min: '20', max: '10', value: '' }
  235. props.visibleColumns = ['price']
  236. await Vue.nextTick()
  237. h.api.apply()
  238. assert.equal(h.events.length, 0, 'invalid range must not emit query')
  239. } finally {
  240. h.stop()
  241. }
  242. })
  243. test('selected filter options remain visible during search and can be removed before applying', async () => {
  244. const props = Vue.reactive({
  245. modelValue: true,
  246. query: { brandsIn: 'A,B' },
  247. context: {},
  248. visibleColumns: ['brands', 'price']
  249. })
  250. const h = await harness('ProductFilters', props)
  251. try {
  252. await h.api.loadFacet('brands')
  253. h.api.searches.brands = '甲'
  254. assert.deepEqual(h.api.optionsFor('brands'), [{ value: 'A', label: '甲' }])
  255. assert.deepEqual(h.api.selectedOptionsFor('brands'), [
  256. { value: 'A', label: '甲' },
  257. { value: 'B', label: '乙' }
  258. ])
  259. h.api.openEnum('brands')
  260. h.api.toggleEnum('B')
  261. assert.deepEqual(h.api.draft.value.brands, ['A', 'B'], 'picker changes remain a draft')
  262. h.api.enumOpen.value = false
  263. h.api.openEnum('brands')
  264. assert.deepEqual(h.api.enumDraft.value, ['A', 'B'], 'cancel preserves the original selection')
  265. h.api.toggleEnum('B')
  266. h.api.confirmEnum()
  267. assert.deepEqual(h.api.draft.value.brands, ['A'])
  268. assert.equal(props.query.brandsIn, 'A,B')
  269. assert.deepEqual(h.events, [])
  270. assert.ok(h.api.numberDefs.value.every((d: any) => d.prop !== 'price'))
  271. h.api.apply()
  272. assert.deepEqual(h.events[0], ['apply', { brandsIn: 'A' }])
  273. } finally {
  274. h.stop()
  275. }
  276. })
  277. test('active number filters preserve Web string values and explicit between operator', async () => {
  278. const m = await model()
  279. const draft = m.createProductFilterDraft()
  280. draft.price = { op: 'between', value: '', min: '0', max: '10.5' }
  281. draft.cost = { op: 'eq', value: '12.50', min: '', max: '' }
  282. assert.deepEqual(m.productFilterQuery(draft), {
  283. priceOp: 'between',
  284. priceMin: '0',
  285. priceMax: '10.5',
  286. costOp: 'eq',
  287. cost: '12.50'
  288. })
  289. })
  290. test('product list ignores obsolete saved fields and keeps seven fixed default columns', async () => {
  291. const reads: string[] = []
  292. Object.assign(globalThis, {
  293. localStorage: {
  294. getItem: (key: string) => {
  295. reads.push(key)
  296. return '[]'
  297. },
  298. setItem: () => {}
  299. }
  300. })
  301. const h = await harness('index')
  302. try {
  303. assert.equal(h.api.visibleColumns.value.length, 7)
  304. assert.equal(h.api.visibleColumns.value.includes('cost'), false)
  305. assert.deepEqual(reads, [])
  306. for (const name of ['selectedIds', 'selecting', 'columnsOpen', 'selectLoaded', 'batchStatus'])
  307. assert.equal(h.api[name], undefined, `${name} must not remain in mobile list`)
  308. } finally {
  309. h.stop()
  310. delete (globalThis as any).localStorage
  311. }
  312. })
  313. test('actual product list renders fixed default data and excludes desktop management controls', async () => {
  314. const { compileTemplate, compileScript } = await import('@vue/compiler-sfc')
  315. const { renderToString } = await import('vue/server-renderer')
  316. const h = await harness('index')
  317. try {
  318. h.api.products.value = [
  319. {
  320. id: '1',
  321. productName: '固定产品名称',
  322. productNo: '编号值',
  323. status: 'on',
  324. price: 19,
  325. cost: 15
  326. }
  327. ]
  328. h.api.loading.value = false
  329. const source = readFileSync(
  330. new URL('../src/views/m/crm/product/index.vue', import.meta.url),
  331. 'utf8'
  332. )
  333. const descriptor = parse(source).descriptor
  334. compileScript(descriptor, { id: 'list' })
  335. const template = compileTemplate({
  336. id: 'list',
  337. filename: 'index.vue',
  338. source: descriptor.template!.content
  339. })
  340. assert.deepEqual(template.errors, [])
  341. const exports: any = {}
  342. const stub = {
  343. setup:
  344. (_: any, { slots }: any) =>
  345. () =>
  346. Vue.h(
  347. 'div',
  348. Object.values(slots).flatMap((slot: any) => slot())
  349. )
  350. }
  351. new Function(
  352. 'require',
  353. 'exports',
  354. ts.transpile(template.code, {
  355. module: ts.ModuleKind.CommonJS,
  356. target: ts.ScriptTarget.ESNext
  357. })
  358. )(() => ({ ...Vue, resolveComponent: () => stub }), exports)
  359. const render = () =>
  360. renderToString(
  361. Vue.createSSRApp({ setup: () => () => exports.render(Vue.proxyRefs(h.api), []) })
  362. )
  363. const rendered = await render()
  364. for (const value of ['固定产品名称', '编号值', '¥19'])
  365. assert.ok(rendered.includes(value), value)
  366. for (const value of [
  367. '¥15',
  368. '更多字段',
  369. '字段设置',
  370. '刷新',
  371. '清空筛选',
  372. '多选',
  373. '列统计',
  374. '批量'
  375. ])
  376. assert.ok(!rendered.includes(value), value)
  377. const filters = parse(
  378. readFileSync(
  379. new URL('../src/views/m/crm/product/ProductFilters.vue', import.meta.url),
  380. 'utf8'
  381. )
  382. ).descriptor
  383. const script = compileScript(filters, { id: 'filters' })
  384. assert.deepEqual(
  385. compileTemplate({
  386. id: 'filters',
  387. filename: 'ProductFilters.vue',
  388. source: filters.template!.content,
  389. compilerOptions: { bindingMetadata: script.bindings }
  390. }).errors,
  391. []
  392. )
  393. } finally {
  394. h.stop()
  395. }
  396. })
  397. test('cancelled confirmation and changed identity never submit pending single-record actions', async () => {
  398. let resolve!: () => void
  399. let cancel = true
  400. const h = await harness(
  401. 'index',
  402. {},
  403. {
  404. showProductConfirmDialog: () =>
  405. cancel
  406. ? Promise.reject(new Error('cancel'))
  407. : new Promise<void>((r) => {
  408. resolve = r
  409. })
  410. }
  411. )
  412. try {
  413. const card = { id: '1', createBy: 'u1', status: 'on' }
  414. await h.api.toggleStatus(card)
  415. assert.deepEqual(h.deletes, [])
  416. assert.equal(h.api.actingId.value, '')
  417. cancel = false
  418. const pending = h.api.toggleStatus(card)
  419. h.user.accessToken = 'other'
  420. resolve()
  421. await pending
  422. assert.deepEqual(h.statuses, [])
  423. assert.equal(h.api.actingId.value, '')
  424. } finally {
  425. h.stop()
  426. }
  427. })
  428. test('closing pending facets resets loading and reopening can fetch without stale completion overwriting options', async () => {
  429. const props = Vue.reactive({
  430. modelValue: true,
  431. query: {},
  432. context: { statusIn: 'on' },
  433. visibleColumns: ['brands']
  434. })
  435. let resolveOld!: (value: any) => void
  436. let calls = 0
  437. const h = await harness('ProductFilters', props, {
  438. fetchProductColumnFacetValues: () => {
  439. calls++
  440. return calls === 1
  441. ? new Promise((resolve) => {
  442. resolveOld = resolve
  443. })
  444. : Promise.resolve({ list: [{ value: 'new', label: '新候选' }] })
  445. }
  446. })
  447. try {
  448. const pending = h.api.loadFacet('brands')
  449. assert.equal(h.api.facetLoading.brands, true)
  450. props.modelValue = false
  451. await Vue.nextTick()
  452. assert.equal(h.api.facetLoading.brands, false)
  453. props.modelValue = true
  454. await Vue.nextTick()
  455. h.api.openEnum('brands')
  456. await Vue.nextTick()
  457. assert.equal(calls, 2)
  458. resolveOld({ list: [{ value: 'old', label: '旧候选' }] })
  459. await pending
  460. assert.equal(h.api.facetLoading.brands, false)
  461. assert.deepEqual(
  462. h.api.optionsFor('brands').map((o: any) => o.value),
  463. ['new']
  464. )
  465. } finally {
  466. h.stop()
  467. }
  468. })