import { describe, expect, it } from 'vitest'; import { buildLegacyCategoryBranchExpr, buildProductCatalogMixedBranchExpr, } from '../src/services/branchCategoryScope'; import { compileTrustedExpr, isTrustedExprTemplate, normalizeTrustedExpr, } from '../src/services/trustedExprFilters'; describe('trustedExprFilters', () => { it('accepts tenantScope purchase branch template with parameterized $val', () => { const raw = '(t0.branch_code = $val OR (t0.branch_code IS NULL AND EXISTS (SELECT 1 FROM orders o WHERE o.order_code = t0.order_code AND o.branch_code = $val)))'; expect(isTrustedExprTemplate(raw)).toBe(true); const compiled = compileTrustedExpr(raw, 'BR001', 1); expect(compiled).not.toBeNull(); expect(compiled!.sql).toContain('$1'); expect(compiled!.sql).toContain('$2'); expect(compiled!.sql).not.toContain('$val'); expect(compiled!.params).toEqual(['BR001', 'BR001']); expect(compiled!.nextIndex).toBe(3); }); it('accepts product catalog / category templates from branchCategoryScope', () => { const raw = buildProductCatalogMixedBranchExpr('$val'); const compiled = compileTrustedExpr(raw, 'BR002', 4); expect(compiled).toEqual({ sql: '(branch_code = $4)', params: ['BR002'], nextIndex: 5, }); expect(compileTrustedExpr(buildLegacyCategoryBranchExpr('$val'), 'BR003', 1)?.sql).toBe( '(branch_code = $1)' ); }); it('normalizes whitespace before matching', () => { const messy = `t0.sku_code IN (SELECT sku_code FROM skus WHERE branch_code = $val) AND t0.supplier_code IN (SELECT supplier_code FROM suppliers WHERE branch_code = $val)`; expect(isTrustedExprTemplate(messy)).toBe(true); expect(normalizeTrustedExpr(messy)).toBe( 't0.sku_code IN (SELECT sku_code FROM skus WHERE branch_code = $val) AND t0.supplier_code IN (SELECT supplier_code FROM suppliers WHERE branch_code = $val)' ); }); it('accepts purchaser owner-scope template', () => { const raw = "(CASE WHEN t0.purchase_status IN (10, 32) THEN (NULLIF(TRIM(t0.purchaser_code), '') IS NULL OR t0.purchaser_code = $val) ELSE t0.purchaser_code = $val END)"; expect(isTrustedExprTemplate(raw)).toBe(true); const compiled = compileTrustedExpr(raw, 'P001', 1); expect(compiled!.params).toEqual(['P001', 'P001']); expect(compiled!.sql).not.toContain('$val'); }); it('rejects unknown templates', () => { expect(isTrustedExprTemplate('1 = 1')).toBe(false); expect(compileTrustedExpr('SELECT * FROM orders', 'x', 1)).toBeNull(); expect(compileTrustedExpr("branch_code = 'BR001'", null, 1)).toBeNull(); }); it('rejects object values', () => { expect(() => compileTrustedExpr('(branch_code = $val)', { a: 1 }, 1)).toThrow( /scalar/i ); }); });