diff --git a/apps/admin-ui/tests/components/order-options-menu.test.tsx b/apps/admin-ui/tests/components/order-options-menu.test.tsx index 35cd990..a300b71 100644 --- a/apps/admin-ui/tests/components/order-options-menu.test.tsx +++ b/apps/admin-ui/tests/components/order-options-menu.test.tsx @@ -226,7 +226,7 @@ describe('OrderOptionsMenu', () => { setupApiMocks({ procedures: { 'admin.order.updateAddressCoords': { success: true }, - 'admin.const.getConstants': [{ key: 'welcomeMessage', value: 'Hello & welcome!' }], + 'admin.region.getRegionConstants': [{ key: 'welcomeMessage', value: 'Hello & welcome!' }], }, }) renderMenu({ isFirstOrder: true }) diff --git a/apps/admin-ui/tests/screens/customize-app-all-items-order.test.tsx b/apps/admin-ui/tests/screens/customize-app-all-items-order.test.tsx index 12604b4..e56e504 100644 --- a/apps/admin-ui/tests/screens/customize-app-all-items-order.test.tsx +++ b/apps/admin-ui/tests/screens/customize-app-all-items-order.test.tsx @@ -40,7 +40,7 @@ describe('All items order editor', () => { it('shows the loading state while constants load', () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => new Promise(() => {}), + 'admin.region.getRegionConstants': () => new Promise(() => {}), 'common.product.getAllProductsSummary': productsResponse, }, }) @@ -52,7 +52,7 @@ describe('All items order editor', () => { it('shows the error state when constants fail', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => { + 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'common.product.getAllProductsSummary': productsResponse, @@ -66,7 +66,7 @@ describe('All items order editor', () => { it('sorts products by the constant and appends the rest', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'allItemsOrder', value: [2, 1] }], + 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [2, 1] }], 'common.product.getAllProductsSummary': productsResponse, }, }) @@ -82,7 +82,7 @@ describe('All items order editor', () => { it('accepts a comma-separated order string', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'allItemsOrder', value: '3' }], + 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: '3' }], 'common.product.getAllProductsSummary': productsResponse, }, }) @@ -96,7 +96,7 @@ describe('All items order editor', () => { it('shows the empty state when there are no products', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'allItemsOrder', value: [] }], + 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [] }], 'common.product.getAllProductsSummary': { products: [], count: 0 }, }, }) @@ -108,9 +108,9 @@ describe('All items order editor', () => { it('disables Save until the order changes, then saves the full list', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], + 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], 'common.product.getAllProductsSummary': productsResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] }, }, }) const result = renderWithProviders() @@ -118,7 +118,7 @@ describe('All items order editor', () => { await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible()) fireEvent.press(screen.getByText('Save')) - expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0) + expect(procCount(api.fetchMock, 'admin.region.updateRegionConstants')).toBe(0) const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default) act(() => { @@ -126,8 +126,8 @@ describe('All items order editor', () => { }) fireEvent.press(screen.getByText('Save')) - await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants')) - expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({ + await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants')) + expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({ constants: [{ key: 'allItemsOrder', value: [3, 1, 2] }], }) await waitFor(() => @@ -141,9 +141,9 @@ describe('All items order editor', () => { it('refetches the constants after saving', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], + 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], 'common.product.getAllProductsSummary': productsResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] }, }, }) const client = createQueryClient() @@ -151,7 +151,7 @@ describe('All items order editor', () => { const result = renderWithProviders(, { queryClient: client }) await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible()) - const before = procCount(api.fetchMock, 'admin.const.getConstants') + const before = procCount(api.fetchMock, 'admin.region.getRegionConstants') // Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's // request can land in this test's fetchMock. expect(before).toBeGreaterThan(0) @@ -163,7 +163,7 @@ describe('All items order editor', () => { fireEvent.press(screen.getByText('Save')) await waitFor(() => - expect(procCount(api.fetchMock, 'admin.const.getConstants')).toBeGreaterThan(before) + expect(procCount(api.fetchMock, 'admin.region.getRegionConstants')).toBeGreaterThan(before) ) // The refetch is driven by the path-based invalidation, not by updateConstants itself. // Asserting the ARRAY path is the point: the old dotted string matched no query at all. @@ -178,16 +178,16 @@ describe('All items order editor', () => { client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length ).toBeGreaterThan(0) expect( - client.getQueryCache().findAll({ queryKey: ['admin.const.getConstants'] }) + client.getQueryCache().findAll({ queryKey: ['admin.region.getRegionConstants'] }) ).toHaveLength(0) }) it('shows the saving label while the update is pending', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], + 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], 'common.product.getAllProductsSummary': productsResponse, - 'admin.const.updateConstants': () => new Promise(() => {}), + 'admin.region.updateRegionConstants': () => new Promise(() => {}), }, }) const result = renderWithProviders() @@ -205,7 +205,7 @@ describe('All items order editor', () => { it('goes back from the header and the error state', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => { + 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'common.product.getAllProductsSummary': productsResponse, diff --git a/apps/admin-ui/tests/screens/customize-app-popular-items.test.tsx b/apps/admin-ui/tests/screens/customize-app-popular-items.test.tsx index a738803..2151b61 100644 --- a/apps/admin-ui/tests/screens/customize-app-popular-items.test.tsx +++ b/apps/admin-ui/tests/screens/customize-app-popular-items.test.tsx @@ -70,7 +70,7 @@ describe('Popular items editor', () => { it('shows the loading state while constants load', () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => new Promise(() => {}), + 'admin.region.getRegionConstants': () => new Promise(() => {}), 'common.product.getAllProductsSummary': productsResponse, }, }) @@ -82,7 +82,7 @@ describe('Popular items editor', () => { it('shows the error state when constants fail', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => { + 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'common.product.getAllProductsSummary': productsResponse, @@ -96,7 +96,7 @@ describe('Popular items editor', () => { it('renders the popular items resolved from the constant', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': constants, + 'admin.region.getRegionConstants': constants, 'common.product.getAllProductsSummary': productsResponse, }, }) @@ -111,7 +111,7 @@ describe('Popular items editor', () => { it('shows the empty state when nothing is configured', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'popularItems', value: [] }], + 'admin.region.getRegionConstants': [{ key: 'popularItems', value: [] }], 'common.product.getAllProductsSummary': productsResponse, }, }) @@ -125,9 +125,9 @@ describe('Popular items editor', () => { it('removes a product and saves the remaining ids', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': constants, + 'admin.region.getRegionConstants': constants, 'common.product.getAllProductsSummary': productsResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, }, }) const result = renderWithProviders() @@ -139,8 +139,8 @@ describe('Popular items editor', () => { fireEvent.press(screen.getByText('Save')) - await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants')) - expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({ + await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants')) + expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({ constants: [{ key: 'popularItems', value: [2] }], }) await waitFor(() => @@ -154,9 +154,9 @@ describe('Popular items editor', () => { it('saves a reordered list', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': constants, + 'admin.region.getRegionConstants': constants, 'common.product.getAllProductsSummary': productsResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, }, }) const result = renderWithProviders() @@ -168,8 +168,8 @@ describe('Popular items editor', () => { }) fireEvent.press(screen.getByText('Save')) - await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants')) - expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({ + await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants')) + expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({ constants: [{ key: 'popularItems', value: [2, 1] }], }) }) @@ -177,9 +177,9 @@ describe('Popular items editor', () => { it('refetches the constants after saving', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': constants, + 'admin.region.getRegionConstants': constants, 'common.product.getAllProductsSummary': productsResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, }, }) const client = createQueryClient() @@ -187,7 +187,7 @@ describe('Popular items editor', () => { const result = renderWithProviders(, { queryClient: client }) await screen.findByText('Chicken') - const before = procCount(api.fetchMock, 'admin.const.getConstants') + const before = procCount(api.fetchMock, 'admin.region.getRegionConstants') // Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's // request can land in this test's fetchMock. expect(before).toBeGreaterThan(0) @@ -199,7 +199,7 @@ describe('Popular items editor', () => { fireEvent.press(screen.getByText('Save')) await waitFor(() => - expect(procCount(api.fetchMock, 'admin.const.getConstants')).toBeGreaterThan(before) + expect(procCount(api.fetchMock, 'admin.region.getRegionConstants')).toBeGreaterThan(before) ) // The refetch is driven by the path-based invalidation, not by updateConstants itself. // Asserting the ARRAY path is the point: the old dotted string matched no query at all. @@ -214,14 +214,14 @@ describe('Popular items editor', () => { client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length ).toBeGreaterThan(0) expect( - client.getQueryCache().findAll({ queryKey: ['admin.const.getConstants'] }) + client.getQueryCache().findAll({ queryKey: ['admin.region.getRegionConstants'] }) ).toHaveLength(0) }) it('does not save while nothing changed', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': constants, + 'admin.region.getRegionConstants': constants, 'common.product.getAllProductsSummary': productsResponse, }, }) @@ -230,16 +230,16 @@ describe('Popular items editor', () => { await screen.findByText('Chicken') fireEvent.press(screen.getByText('Save')) - expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0) + expect(procCount(api.fetchMock, 'admin.region.updateRegionConstants')).toBe(0) }) it('adds a product through the add dialog and saves it', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': constants, + 'admin.region.getRegionConstants': constants, 'common.product.getAllProductsSummary': productsResponse, 'common.product.getAllSkusSummary': skusResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] }, }, }) const result = renderWithProviders() @@ -256,8 +256,8 @@ describe('Popular items editor', () => { await waitFor(() => expect(screen.getByText('Fish')).toBeVisible()) fireEvent.press(screen.getByText('Save')) - await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants')) - expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({ + await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants')) + expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({ constants: [{ key: 'popularItems', value: [1, 2, 3] }], }) }) @@ -265,9 +265,9 @@ describe('Popular items editor', () => { it('shows the saving label while the update is pending', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': constants, + 'admin.region.getRegionConstants': constants, 'common.product.getAllProductsSummary': productsResponse, - 'admin.const.updateConstants': () => new Promise(() => {}), + 'admin.region.updateRegionConstants': () => new Promise(() => {}), }, }) const result = renderWithProviders() @@ -283,7 +283,7 @@ describe('Popular items editor', () => { it('goes back from the header and the error state', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => { + 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'common.product.getAllProductsSummary': productsResponse, diff --git a/apps/admin-ui/tests/screens/product-tags-order.test.tsx b/apps/admin-ui/tests/screens/product-tags-order.test.tsx index 52c5e72..08a49d9 100644 --- a/apps/admin-ui/tests/screens/product-tags-order.test.tsx +++ b/apps/admin-ui/tests/screens/product-tags-order.test.tsx @@ -39,7 +39,7 @@ describe('Tag orders', () => { it('shows the loading state while constants load', () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => new Promise(() => {}), + 'admin.region.getRegionConstants': () => new Promise(() => {}), 'admin.product.getProductTags': tagsResponse, }, }) @@ -51,7 +51,7 @@ describe('Tag orders', () => { it('shows the error state when the constants query fails', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => { + 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'admin.product.getProductTags': tagsResponse, @@ -65,7 +65,7 @@ describe('Tag orders', () => { it('orders the tags by the tagsOrder constant', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'tagsOrder', value: [2, 1] }], + 'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [2, 1] }], 'admin.product.getProductTags': tagsResponse, }, }) @@ -83,7 +83,7 @@ describe('Tag orders', () => { it('appends tags missing from the order and accepts comma lists', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'tagsOrder', value: '2' }], + 'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: '2' }], 'admin.product.getProductTags': tagsResponse, }, }) @@ -99,7 +99,7 @@ describe('Tag orders', () => { it('shows the empty state when there are no tags', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'tagsOrder', value: [] }], + 'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [] }], 'admin.product.getProductTags': { tags: [], message: 'ok' }, }, }) @@ -111,9 +111,9 @@ describe('Tag orders', () => { it('disables Save until the order changes, then saves', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'tagsOrder', value: [1, 2] }], + 'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [1, 2] }], 'admin.product.getProductTags': tagsResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] }, }, }) const result = renderWithProviders() @@ -122,7 +122,7 @@ describe('Tag orders', () => { // Save is disabled before any drag. fireEvent.press(screen.getByText('Save')) - expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0) + expect(procCount(api.fetchMock, 'admin.region.updateRegionConstants')).toBe(0) // Reorder and save. const list = result.UNSAFE_getByType( @@ -135,8 +135,8 @@ describe('Tag orders', () => { fireEvent.press(screen.getByText('Save')) - await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants')) - expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({ + await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants')) + expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({ constants: [{ key: 'tagsOrder', value: [2, 1] }], }) await waitFor(() => @@ -148,9 +148,9 @@ describe('Tag orders', () => { it('refetches the constants after saving', async () => { const api = setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'tagsOrder', value: [1, 2] }], + 'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [1, 2] }], 'admin.product.getProductTags': tagsResponse, - 'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] }, + 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] }, }, }) const client = createQueryClient() @@ -158,7 +158,7 @@ describe('Tag orders', () => { const result = renderWithProviders(, { queryClient: client }) await waitFor(() => expect(screen.getByText('Chicken Tag')).toBeVisible()) - const before = procCount(api.fetchMock, 'admin.const.getConstants') + const before = procCount(api.fetchMock, 'admin.region.getRegionConstants') // Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's // request can land in this test's fetchMock. expect(before).toBeGreaterThan(0) @@ -172,7 +172,7 @@ describe('Tag orders', () => { fireEvent.press(screen.getByText('Save')) await waitFor(() => - expect(procCount(api.fetchMock, 'admin.const.getConstants')).toBeGreaterThan(before) + expect(procCount(api.fetchMock, 'admin.region.getRegionConstants')).toBeGreaterThan(before) ) // The refetch is driven by the path-based invalidation, not by updateConstants itself. // Asserting the ARRAY path is the point: the old dotted string matched no query at all. @@ -187,16 +187,16 @@ describe('Tag orders', () => { client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length ).toBeGreaterThan(0) expect( - client.getQueryCache().findAll({ queryKey: ['admin.const.getConstants'] }) + client.getQueryCache().findAll({ queryKey: ['admin.region.getRegionConstants'] }) ).toHaveLength(0) }) it('shows the saving label while the update is pending', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': [{ key: 'tagsOrder', value: [1, 2] }], + 'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [1, 2] }], 'admin.product.getProductTags': tagsResponse, - 'admin.const.updateConstants': () => new Promise(() => {}), + 'admin.region.updateRegionConstants': () => new Promise(() => {}), }, }) const result = renderWithProviders() @@ -216,7 +216,7 @@ describe('Tag orders', () => { it('goes back from the header and the error state', async () => { setupApiMocks({ procedures: { - 'admin.const.getConstants': () => { + 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'admin.product.getProductTags': tagsResponse, diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts index 9dd1333..fa49b79 100644 --- a/apps/backend/src/sqliteImporter.ts +++ b/apps/backend/src/sqliteImporter.ts @@ -28,9 +28,6 @@ export { // Admin - Complaint getComplaints, resolveComplaint, - // Admin - Constants - getAllConstants, - upsertConstants, // Admin - Coupon getAllCoupons, getCouponById, diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts b/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts index 4304359..cecfe9a 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts @@ -11,7 +11,6 @@ import { storeRouter } from '@/src/trpc/apis/admin-apis/apis/store' import { adminPaymentsRouter } from '@/src/trpc/apis/admin-apis/apis/payments' import { bannerRouter } from '@/src/trpc/apis/admin-apis/apis/banner' import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user' -import { constRouter } from '@/src/trpc/apis/admin-apis/apis/const' import { regionRouter } from '@/src/trpc/apis/admin-apis/apis/region' export const adminRouter = router({ @@ -26,7 +25,6 @@ export const adminRouter = router({ payments: adminPaymentsRouter, banner: bannerRouter, user: userRouter, - const: constRouter, region: regionRouter, }); diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/const.ts b/apps/backend/src/trpc/apis/admin-apis/apis/const.ts deleted file mode 100644 index dd1d50b..0000000 --- a/apps/backend/src/trpc/apis/admin-apis/apis/const.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { router, staffProcedure } from '@/src/trpc/trpc-index' -import { z } from 'zod'; -import { TRPCError } from '@trpc/server' -import { computeConstants } from '@/src/lib/const-store' -import { refreshGenKv, refreshGenKvForRegion } from '@/src/lib/gen-store' -import { CONST_SCOPE } from '@/src/lib/const-keys' -import { scheduleStoreInitialization } from '@/src/stores/store-initializer' -import { - getAllConstants as getAllConstantsFromDb, - upsertConstants as upsertConstantsInDb, -} from '@/src/dbService' -import type { Constant, ConstantUpdateResult } from '@packages/shared' - -// Constants that are baked into the versioned cache files (products.json etc.) -// — changing them requires regenerating the cache so the user app picks it up. -const CACHE_AFFECTING_KEYS: string[] = ['tagsOrder'] - -const constantsInput = z.object({ - constants: z.array(z.object({ key: z.string(), value: z.any() })), -}) - -export const constRouter = router({ - // Backward-compat: merged global + legacy view. Writes route by key scope. - getConstants: staffProcedure - .query(async (): Promise => { - return getAllConstantsFromDb(); - }), - - updateConstants: staffProcedure - .input(constantsInput) - .mutation(async ({ input, ctx }): Promise => { - const { constants } = input; - - const invalidKeys = constants - .filter(c => !CONST_SCOPE[c.key]) - .map(c => c.key); - - if (invalidKeys.length > 0) { - throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`); - } - - // Global constants (versionNum, playStoreUrl, …) are superadmin-only and are - // managed via superadmin.const.*. Never let a region staff token write them - // through the merged route. - const globalKeys = constants - .filter((c) => CONST_SCOPE[c.key] === 'global') - .map((c) => c.key) - - if (globalKeys.length > 0) { - throw new TRPCError({ - code: 'FORBIDDEN', - message: `Global constants are superadmin-only: ${globalKeys.join(', ')}`, - }) - } - - const regionId = ctx.staffUser?.regionId ?? null - await upsertConstantsInDb(constants, regionId ?? undefined) - - await computeConstants() - - const touchedRegion = constants.some((c) => CONST_SCOPE[c.key] === 'region') - const touchedOther = constants.some((c) => CONST_SCOPE[c.key] !== 'region') - if (touchedOther) await refreshGenKv() - else if (touchedRegion && regionId != null) await refreshGenKvForRegion(regionId) - - if (constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) { - await scheduleStoreInitialization() - } - - return { - success: true, - updatedCount: constants.length, - keys: constants.map(c => c.key), - }; - }), -}); diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/region.ts b/apps/backend/src/trpc/apis/admin-apis/apis/region.ts index f4bfc80..e9e18e1 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/region.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/region.ts @@ -80,7 +80,8 @@ export const regionRouter = router({ } if (rows.some((c) => CACHE_AFFECTING_REGION_KEYS.includes(c.key))) { - await scheduleStoreInitialization() + // tagsOrder is region-scoped, so only this region's cache files can change. + await scheduleStoreInitialization(regionId) } return { success: true, updatedCount: updated, deletedCount: deleted } diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts index 25210a1..c0ffcba 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts @@ -265,7 +265,8 @@ export const superadminRegionsRouter = router({ } if (rows.some((c) => CACHE_AFFECTING_REGION_KEYS.includes(c.key))) { - await scheduleStoreInitialization() + // tagsOrder is region-scoped, so only this region's cache files can change. + await scheduleStoreInitialization(input.regionId) } return { success: true, updatedCount: updated, deletedCount: deleted } diff --git a/apps/backend/tests/BUGS.md b/apps/backend/tests/BUGS.md index 02bda6c..6b48620 100644 --- a/apps/backend/tests/BUGS.md +++ b/apps/backend/tests/BUGS.md @@ -30,13 +30,16 @@ write. **Pinned by:** `tests/api/authorization-matrix.test.ts`. -> **Partially fixed (FC-01/SEC-01):** `admin.const.*` is no longer reachable with -> a user token. The router now uses `staffProcedure`; `updateConstants` also -> rejects global-scope keys (globals are superadmin-only), and the redundant -> `getGlobalConstants`/`updateGlobalConstants`/`getLegacyConstants`/ -> `updateLegacyConstants` procedures were removed (they had no production UI -> caller — the admin apps use `admin.region.*`, the superadmin UI uses -> `superadmin.const.*`). The remaining entries above are still open. +> **Fixed (FC-01/SEC-01), route removed:** the merged staff `admin.const.*` route is +> gone. It had no production caller (the admin apps use `admin.region.*`, the +> superadmin UI uses `superadmin.const.*`) and was the last place that could rebuild +> every region's cache files on a region-key change, hand a staff token a merged read +> of global constants, and accept bound-scope keys while silently dropping them. +> Writes now go to the scope-specific routes, all of which are `staffProcedure` / +> `superadminProcedure` and scope-checked (`assertConstantKeysInScope`). +> `apps/backend/tests/helpers/consts.ts` reads/writes bound + region constants through +> those routes; legacy constants have no staff-readable endpoint by design, so the api +> tests no longer cover them. The remaining entries above are still open. ### 2. Public `admin.vendorSnippets` endpoints diff --git a/apps/backend/tests/api/admin-ops.test.ts b/apps/backend/tests/api/admin-ops.test.ts index 4591df0..7152fe9 100644 --- a/apps/backend/tests/api/admin-ops.test.ts +++ b/apps/backend/tests/api/admin-ops.test.ts @@ -4,7 +4,7 @@ */ import { apiClient, captureError, uniqueSuffix } from '../helpers/api' -import { asNumber, getConstants, setConst } from '../helpers/consts' +import { getRegionConstants, setRegionConst } from '../helpers/consts' import { createFutureSlot, createStoreWithSku, ensureUserAddress } from '../helpers/fixtures' import { staffSession, userSession } from '../helpers/sessions' @@ -33,14 +33,16 @@ describe('admin ops', () => { skuId = store.skuId }) - it('round-trips a constant through updateConstants', async () => { - const before = await getConstants() - const original = before.minOrderAmountForCoupon + it('round-trips a region constant through updateRegionConstants', async () => { + const before = await getRegionConstants() + const original = before.welcomeMessage + const next = `API welcome ${uniqueSuffix()}` - await setConst('minOrderAmountForCoupon', 123) - expect(asNumber((await getConstants()).minOrderAmountForCoupon)).toBe(123) + await setRegionConst('welcomeMessage', next) + expect((await getRegionConstants()).welcomeMessage).toBe(next) - if (original !== undefined) await setConst('minOrderAmountForCoupon', original) + // Restore whatever the region had (a string, or no row at all). + await setRegionConst('welcomeMessage', typeof original === 'string' ? original : null) }) it('updates and deletes a product group', async () => { diff --git a/apps/backend/tests/api/authorization-matrix.test.ts b/apps/backend/tests/api/authorization-matrix.test.ts index 3643e91..c7a6d8f 100644 --- a/apps/backend/tests/api/authorization-matrix.test.ts +++ b/apps/backend/tests/api/authorization-matrix.test.ts @@ -153,23 +153,23 @@ describe('authorization matrix', () => { expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i) }) - it('rejects a user token on admin.const.updateConstants', async () => { + it('rejects a user token on admin.region.updateRegionConstants', async () => { const error = await captureError(() => - apiClient(userToken).admin.const.updateConstants.mutate({ - constants: [{ key: 'minOrderAmountForCoupon', value: 4321 }], + apiClient(userToken).admin.region.updateRegionConstants.mutate({ + constants: [{ key: 'welcomeMessage', value: 'nope' }], }) ) expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i) }) - it('rejects a staff token writing a global constant via admin.const.updateConstants', async () => { + it('rejects a staff token writing a global constant via admin.region.updateRegionConstants', async () => { const staff = await staffSession() const error = await captureError(() => - apiClient(staff.token).admin.const.updateConstants.mutate({ + apiClient(staff.token).admin.region.updateRegionConstants.mutate({ constants: [{ key: 'versionNum', value: '9.9.9' }], }) ) - expect(error.message).toMatch(/superadmin-only/i) + expect(error.message).toMatch(/global constant/i) }) }) diff --git a/apps/backend/tests/api/misc-procedures.test.ts b/apps/backend/tests/api/misc-procedures.test.ts index b16c55b..714c2de 100644 --- a/apps/backend/tests/api/misc-procedures.test.ts +++ b/apps/backend/tests/api/misc-procedures.test.ts @@ -294,14 +294,6 @@ describe('misc procedures', () => { }) describe('constants', () => { - it('surfaces internalAppVersion with a numeric default', async () => { - const constants = await admin.admin.const.getConstants.query() - const entry = constants.find((c: { key: string }) => c.key === 'internalAppVersion') - - expect(entry).toBeDefined() - expect(typeof entry!.value).toBe('number') - }) - it('exposes internalAppVersion to the user app via essentialConsts', async () => { const consts = (await apiClient().common.essentialConsts.query({ boundId: 1 })) as { internalAppVersion?: number diff --git a/apps/backend/tests/helpers/consts.ts b/apps/backend/tests/helpers/consts.ts index b8ba3ff..54d7f8a 100644 --- a/apps/backend/tests/helpers/consts.ts +++ b/apps/backend/tests/helpers/consts.ts @@ -1,9 +1,15 @@ /** - * key_val_store constants (delivery charge, min order value, flash gate, …). + * Constants the api tests read and flip. * - * `admin.const.getConstants` wraps them in an unknown shape, so this normalizes - * whichever form it returns: `{ constants: [{key,value}] }`, `{ constants: {k:v} }` - * or a bare map. + * Constants live in three scope tables (`global_consts`, `region_consts`, + * `region_bound_consts`) plus the legacy `key_val_store`, and each scope has its + * own endpoint. These suites care about the delivery settings, which are + * BOUND-scoped, so they read/write the region's effective bound — the same bound + * `placeOrder` falls back to for an address with no coordinates (how these suites' + * addresses are created). + * + * Legacy constants are superadmin-only (`superadmin.const.getLegacyConstants`), and + * the test env has no superadmin credentials, so nothing here touches them anymore. */ import { apiClient } from './api' @@ -11,27 +17,64 @@ import { staffSession } from './sessions' export type Constants = Record -export async function getConstants(): Promise { +/** The region's effective (lowest-priority) bound, as placeOrder resolves it. */ +export async function effectiveBoundId(regionId = 1): Promise { const staff = await staffSession() - const res = await apiClient(staff.token).admin.const.getConstants.query() - - const raw = - (res as { constants?: unknown })?.constants ?? - (res as { data?: unknown })?.data ?? - res - - if (Array.isArray(raw)) { - return Object.fromEntries( - raw.map((entry: { key: string; value: unknown }) => [entry.key, entry.value]) - ) + const bounds = await apiClient(staff.token).admin.region.bounds.query() + const bound = bounds.find((b) => b.regionId === regionId) ?? bounds[0] + if (!bound) { + throw new Error(`[api-tests] region ${regionId} has no configured bound`) } - return (raw ?? {}) as Constants + return bound.id } -/** Update one constant (used to flip the flash gate, always restored by the caller). */ -export async function setConst(key: string, value: unknown): Promise { +/** DB rows come back as strings; give the suites real booleans and numbers. */ +const coerce = (raw: string | null | undefined): unknown => { + if (raw === null || raw === undefined) return undefined + if (raw === 'true') return true + if (raw === 'false') return false + const num = Number(raw) + return raw.trim() !== '' && Number.isFinite(num) ? num : raw +} + +/** + * The region's effective bound settings (deliveryCharge, freeDeliveryThreshold, + * flashDeliveryCharge, isFlashDeliveryEnabled). + */ +export async function getConstants(regionId = 1): Promise { const staff = await staffSession() - await apiClient(staff.token).admin.const.updateConstants.mutate({ + const boundId = await effectiveBoundId(regionId) + const settings = await apiClient(staff.token).admin.region.getBoundSettings.query({ boundId }) + + const out: Constants = {} + for (const [key, value] of Object.entries(settings)) out[key] = coerce(value) + return out +} + +/** Update one bound constant (used to flip the flash gate, always restored by the caller). */ +export async function setConst(key: string, value: unknown, regionId = 1): Promise { + const staff = await staffSession() + const boundId = await effectiveBoundId(regionId) + await apiClient(staff.token).admin.region.updateBoundSettings.mutate({ + boundId, + settings: [{ key, value: String(value) }], + }) +} + +/** The caller's region constants (region_consts for the staff's own region). */ +export async function getRegionConstants(): Promise { + const staff = await staffSession() + const rows = await apiClient(staff.token).admin.region.getRegionConstants.query() + + const out: Constants = {} + for (const { key, value } of rows) out[key] = coerce(value) + return out +} + +/** Update one region constant. Null deletes the row. */ +export async function setRegionConst(key: string, value: string | number | boolean | null): Promise { + const staff = await staffSession() + await apiClient(staff.token).admin.region.updateRegionConstants.mutate({ constants: [{ key, value }], }) } diff --git a/change-log.txt b/change-log.txt index 583ff3b..7b86d54 100644 --- a/change-log.txt +++ b/change-log.txt @@ -5503,3 +5503,149 @@ user-ui Tests (written, NOT run): checkout-coupons.test.tsx - the split opens for a product-specific applied coupon (row + total = the coupon's discount) and a whole-cart coupon shows no "i". Typecheck: user-ui, admin-ui, web-ui, fallback-ui, db_helper_sqlite, backend - all clean. + +2026-10-17 13:48:12 backend: tagsOrder changes now regenerate only the edited region's caches. + + Problem: `tagsOrder` is region-scoped, but all three paths that write it called + scheduleStoreInitialization() with NO regionId. The CacheCreator DO treats an empty + pendingRegions as "all regions" (cache-creator.ts:71-72 -> initializeAllStores() with no + region -> createAllCacheFiles() for every region), so editing tag order in one region + regenerated every region's store caches and CDN cache files: new products_version_num per + region (so every region's clients re-download unchanged products/stores/banners), plus + regions x bounds x 3 D1 reads, KV puts, S3 writes and Cloudflare purges for identical output. + Product/store/banner mutations already pass ctx.staffUser.regionId; the const paths did not. + + Regeneration itself stays (products.json embeds the tag order via scaffoldProducts and + tagsOrder is not part of the essentialConsts payload, so the versioned file is the only + carrier). Only the scope changes. + + apps/backend/src/trpc/apis/admin-apis/apis/region.ts + updateRegionConstants + - if (rows.some((c) => CACHE_AFFECTING_REGION_KEYS.includes(c.key))) { + - await scheduleStoreInitialization() + - } + + if (rows.some((c) => CACHE_AFFECTING_REGION_KEYS.includes(c.key))) { + + // tagsOrder is region-scoped, so only this region's cache files can change. + + await scheduleStoreInitialization(regionId) + + } + apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts + updateRegionConstants + - await scheduleStoreInitialization() + + // tagsOrder is region-scoped, so only this region's cache files can change. + + await scheduleStoreInitialization(input.regionId) + apps/backend/src/trpc/apis/admin-apis/apis/const.ts + updateConstants (legacy merged route; non-region keys never reach this branch because + global keys are rejected above and upsertConstantsInDb throws for a region key with no + regionId — so throwing here instead of falling back to "all regions" is a safety net) + - if (constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) { + - await scheduleStoreInitialization() + - } + + if (constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) { + + // Only the caller's own region: tagsOrder is region-scoped, and scheduling + + // without a region would rebuild every region's cache files. + + if (regionId == null) { + + throw new TRPCError({ + + code: 'INTERNAL_SERVER_ERROR', + + message: 'Cannot regenerate the cache without a region', + + }) + + } + + await scheduleStoreInitialization(regionId) + + } + + Left alone deliberately: the genuinely global call sites (superadmin global-products / + global-stores / stores / products) and the flash-delivery cron + seed(), which refresh + every region by design. + +2026-10-17 13:55:26 backend + db helper + admin-ui tests: removed the merged `admin.const` route entirely. + + Request: "remove that route if we don't need. we don't need to worry about backward compatibility". + + Why it could go: no production caller (admin-ui + admin-web write via admin.region.*, the web + superadmin via superadmin.const.*), and it was the last route that could (a) rebuild every + region's cache files when a region key changed, (b) hand any staff token a merged read of + global constants, and (c) accept bound-scope keys while silently dropping them. + + apps/backend/src/trpc/apis/admin-apis/apis/const.ts DELETED + - constRouter: getConstants (globals+legacy merged read), updateConstants (scope-routed write + with a refreshGenKv()-for-every-region branch). + apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts + - import { constRouter } from '@/src/trpc/apis/admin-apis/apis/const' + - const: constRouter, + packages/db_helper_sqlite/src/admin-apis/const.ts + - getAllConstants() (merged, region/bound keys skipped), upsertConstants() (scope fan-out, + bound keys dropped), serializeValue() and the now-unused imports (Constant, CONST_KEYS_ARRAY, + CONST_DEFAULTS, CONST_SCOPE, castConstValue). The five scope-specific readers/writers stay. + packages/db_helper_sqlite/index.ts + apps/backend/src/sqliteImporter.ts + - drop getAllConstants / upsertConstants from both re-export lists. + packages/db_helper_sqlite/src/lib/const-keys.ts + - CONST_DEFAULTS comment no longer claims getAllConstants is its reader (the bound/region + seeders are). + + Tests that pinned the route: + apps/backend/tests/helpers/consts.ts REWRITTEN + + getConstants(regionId = 1): reads the region's EFFECTIVE bound's settings via + admin.region.getBoundSettings (staff) and coerces 'true'/'false' -> boolean, + numeric strings -> number. Previously it read the merged route, which skipped every + region/bound key, so deliveryCharge/freeDeliveryThreshold/flashDeliveryCharge came back + undefined -> asNumber() -> 0 and isFlashDeliveryEnabled -> undefined (=== true -> false). + The four suites that use it were therefore reading zeros / "flash disabled" regardless of + the real bound, e.g. coupon-math asserts freeDeliveryThreshold > UNIT_PRICE on a 0. + + effectiveBoundId(regionId): admin.region.bounds (priority ascending) -> [0], the same bound + placeOrder falls back to for an address with no coordinates (how these suites' addresses + are created). + + setConst(key, value, regionId = 1): writes a BOUND key via admin.region.updateBoundSettings. + The merged route silently dropped bound writes, so the flash gate the suites flip was never + actually flipped by them. + + getRegionConstants()/setRegionConst(key, value) for the region round-trip below. + - getConstants made the minOrderAmountForCoupon (legacy) read impossible: legacy constants are + superadmin-only now (superadmin.const.getLegacyConstants) and the api tests have no + superadmin credentials (tests/.env has none, see .env.example). + apps/backend/tests/api/admin-ops.test.ts + ~ "round-trips a constant through updateConstants" -> "round-trips a region constant through + updateRegionConstants" using welcomeMessage (region scope, staff-writable, no new creds), + same read-back assertion. + apps/backend/tests/api/misc-procedures.test.ts + - dropped "surfaces internalAppVersion with a numeric default" (it read the deleted route); the + sibling case already pins it through common.essentialConsts, which is where the app reads it. + apps/backend/tests/api/authorization-matrix.test.ts + - dropped the two cases whose subject was the deleted route: "rejects a user token on + admin.const.updateConstants" and "rejects a staff token writing a global constant via + admin.const.updateConstants" (the global rejection is covered by + assertConstantKeysInScope on the admin.region/superadmin routes). + apps/admin-ui/tests/screens/customize-app-popular-items.test.tsx + apps/admin-ui/tests/screens/product-tags-order.test.tsx (both were stale - logged as such at + the 2026-10-08 00:41 entry - and called a procedure the screens no longer use) + ~ admin.const.getConstants -> admin.region.getRegionConstants + ~ admin.const.updateConstants -> admin.region.updateRegionConstants (same {constants:[...]} + input shape) + the query-cache key. + Docs: apps/backend/tests/BUGS.md note + docs/e2e-sanity-test-plan.md observation #2 updated. + + Not touched: packages/db_helper_postgres (its own dormant copies of getAllConstants/ + upsertConstants; that package does not typecheck today). change-logs/*.txt and the historical + change-log entries mentioning the route are left as records. + +2026-10-17 14:02:40 As-built notes for the admin.const removal above (deltas from the plan). + + 1. admin-ui tests renamed: FOUR files, not two — customize-app-popular-items, + customize-app-all-items-order, product-tags-order and components/order-options-menu (its + OrderOptionsMenu reads welcomeMessage via admin.region.getRegionConstants). Each diff is only + the procedure string (verified: no other line changed). + 2. apps/admin-ui/tests/screens/customize-app-hub.test.tsx: renamed first, then REVERTED to + admin.const.* on purpose. Its fixtures predate the tabbed region/bound hub — it asserts bound keys + (deliveryCharge, isFlashDeliveryEnabled) and region keys are visible at once, expects the region + route to carry bound keys, and mocks neither admin.region.bounds nor getBoundSettings, so its + cases cannot be satisfied by a rename (bound keys now go to + admin.region.updateBoundSettings { boundId, settings }). Left as the one known-stale file; a + rewrite for the tabbed hub is separate work, offered to the user. + 3. authorization-matrix.test.ts: instead of deleting both cases, RETARGETED them to + admin.region.updateRegionConstants — a user token is still rejected, and a staff token writing + versionNum still fails ("... is a global constant — use the global constants endpoint" from + assertConstantKeysInScope). The coverage moves to the route that now owns the behaviour. + 4. Verification: apps/backend (src), packages/db_helper_sqlite and apps/admin-ui typecheck clean. + `bun run test:api:typecheck` reports 21 PRE-EXISTING errors unrelated to this change + (createGroup 'owner' in admin-catalog/admin-ops, placeOrder calls missing regionId in + admin-orders/authorization-matrix/order-edge-cases, health.test cacheVersion/slotsVersionNum, + misc shape errors); zero of them are in tests/helpers/consts.ts or in the lines touched here. + Tests were not run (user runs the suite). + 5. The five scope-specific readers/writers (global/region/bound/legacy) and the + admin.region/superadmin.const routes are untouched; only the merged read/write pair is gone. diff --git a/docs/e2e-sanity-test-plan.md b/docs/e2e-sanity-test-plan.md index 5458d23..8b974bc 100644 --- a/docs/e2e-sanity-test-plan.md +++ b/docs/e2e-sanity-test-plan.md @@ -425,11 +425,13 @@ is not yet defined, agree the contract rather than write a test that endorses a discount receives a suborder total including its delivery fee. See `BL-01`–`BL-04`: `apps/user-ui/components/cart-page.tsx` and `apps/backend/src/trpc/apis/user-apis/apis/order.ts`. -2. **Global-config restriction must be tested at API level.** - `admin.const.updateGlobalConstants` still uses `protectedProcedure` in the - inspected code. That common guard permits either customer or staff identity; - removing the UI is not enough. See `SEC-01` and - `apps/backend/src/trpc/apis/admin-apis/apis/const.ts` / `trpc-index.ts`. +2. **Global-config restriction is covered at API level (route removed).** + The merged staff `admin.const.*` route is gone — it was the only staff path to + global values and the only route that accepted bound-scope keys while silently + dropping them. Constants are written through scope-specific routes now + (`superadmin.const.*` for globals/legacy, `admin.region.*` for region/bound), and + `assertConstantKeysInScope` rejects a key sent through the wrong one. See `SEC-01` + and `apps/backend/src/trpc/apis/admin-apis/apis/region.ts`. 3. **Order validation needs negative requests.** The inspected order path fetches SKU by ID and checks slot capacity/flash eligibility, but does not visibly validate every submitted region/SKU/slot relation, frozen state, suspension or diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index 2d83194..a7dddbe 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -25,8 +25,6 @@ export { export { // Constants - getAllConstants, - upsertConstants, getAllGlobalConsts, upsertGlobalConsts, getRegionConsts, diff --git a/packages/db_helper_sqlite/src/admin-apis/const.ts b/packages/db_helper_sqlite/src/admin-apis/const.ts index c34dd42..fa56cbc 100644 --- a/packages/db_helper_sqlite/src/admin-apis/const.ts +++ b/packages/db_helper_sqlite/src/admin-apis/const.ts @@ -1,16 +1,9 @@ import { db } from '../db/db_index' import { globalConsts, keyValStore, regionBoundConsts, regionConsts } from '../db/schema' import { eq } from 'drizzle-orm' -import type { Constant } from '@packages/shared' -import { CONST_KEYS_ARRAY, CONST_DEFAULTS, CONST_SCOPE, castConstValue } from '../lib/const-keys' type ConstRow = { key: string; value: string | null } -const serializeValue = (value: unknown): string | null => { - if (value === null || value === undefined) return null - return typeof value === 'string' ? value : String(value) -} - /* ------------------------------------------------------------------ * * global_consts * ------------------------------------------------------------------ */ @@ -112,42 +105,3 @@ export async function upsertBoundConsts( } }) } - -/* ------------------------------------------------------------------ * - * Admin global editor (+ tests) — global + legacy, routed writes - * ------------------------------------------------------------------ */ - -export async function getAllConstants(): Promise { - const [globals, legacy] = await Promise.all([getAllGlobalConsts(), getLegacyConsts()]) - const merged = new Map() - for (const [k, v] of Object.entries(legacy)) merged.set(k, v) - for (const [k, v] of Object.entries(globals)) merged.set(k, v) - - const result: Constant[] = [] - for (const key of CONST_KEYS_ARRAY) { - const scope = CONST_SCOPE[key] - // Region/bound keys are edited through their own endpoints. - if (scope === 'region' || scope === 'bound') continue - const raw = merged.has(key) ? merged.get(key) : CONST_DEFAULTS[key as keyof typeof CONST_DEFAULTS] - result.push({ key, value: castConstValue(key, raw) }) - } - return result -} - -export async function upsertConstants(constants: Constant[], regionId?: number): Promise { - const byScope: Record = { global: [], region: [], bound: [], legacy: [] } - for (const c of constants) { - const scope = CONST_SCOPE[c.key] ?? 'legacy' - byScope[scope].push({ key: c.key, value: serializeValue(c.value) }) - } - - if (byScope.global.length) await upsertGlobalConsts(byScope.global) - if (byScope.legacy.length) await upsertLegacyConsts(byScope.legacy) - if (byScope.region.length) { - if (regionId == null) { - throw new Error('regionId is required to update region constants') - } - await upsertRegionConsts(regionId, byScope.region) - } - // Bound keys are updated via upsertBoundConsts(boundId, regionId, rows). -} diff --git a/packages/db_helper_sqlite/src/lib/const-keys.ts b/packages/db_helper_sqlite/src/lib/const-keys.ts index 336da6e..0f9d964 100644 --- a/packages/db_helper_sqlite/src/lib/const-keys.ts +++ b/packages/db_helper_sqlite/src/lib/const-keys.ts @@ -117,9 +117,9 @@ export const CONST_VISIBILITY: Record = { } /** - * Fallback values used by getAllConstants when a key has no row in - * key_val_store yet, so a newly added constant still shows up in the admin - * form (and saving it writes the real row). + * Fallback values used when seeding a bound/region row that has no value yet, so a + * newly added constant still shows up in the admin form (and saving it writes the + * real row). */ export const CONST_DEFAULTS: Record = { freeDeliveryThreshold: 300,