Compare commits

..

No commits in common. "bebe23f5f038a00d3c69524da026da358ba7422c" and "24d2add4e3a6756d013e3b80214400eee7e9527c" have entirely different histories.

28 changed files with 71 additions and 928 deletions

File diff suppressed because one or more lines are too long

View file

@ -87,7 +87,6 @@ Use these fixture names in the cases below.
| `dashboard/slots/slot-details.tsx` | `tests/pages/slot-details.test.tsx` | getSlotById, share link |
| `dashboard/coupons/index.tsx` | `tests/pages/coupons.test.tsx` | getAll, getReservedCoupons, delete |
| `dashboard/coupons/create.tsx` | `tests/pages/coupon-create.test.tsx` | create, createReservedCoupon |
| `dashboard/coupons/detail/[id].tsx` | `tests/pages/coupon-detail.test.tsx` | getById |
| `dashboard/coupons/edit/[id].tsx` | `tests/pages/coupon-edit.test.tsx` | getById, update |
| `dashboard/dashboard-banners/index.tsx` | `tests/pages/banners.test.tsx` | getBanners, update, delete |
| `dashboard/dashboard-banners/create.tsx` | `tests/pages/banner-create.test.tsx` | createBanner, upload |
@ -579,7 +578,6 @@ Use these fixture names in the cases below.
| ACOUPUI-11 | edge | applicable users | N Users vs All Users |
| ACOUPUI-12 | edge | skuIds empty | no Products line |
| ACOUPUI-13 | happy | Edit | edit route |
| ACOUPUI-13B | happy | View details | detail route |
| ACOUPUI-14 | happy | Delete | confirm; Cancel no API |
| ACOUPUI-15 | happy | confirm delete | mutation; success; refetch |
| ACOUPUI-16 | error | delete fails | alert |
@ -598,23 +596,7 @@ Use these fixture names in the cases below.
| ACOUPUI-29 | reserved status filter | active/expired/redeemed |
| ACOUPUI-30 | reserved pagination/search/refresh | works |
### 8.2 Coupon detail
| ID | Type | Case | Assert |
| --- | --- | --- | --- |
| ACOUPD-01 | happy | loading | “Loading coupon...” |
| ACOUPD-02 | error | missing coupon | “Coupon not found”; Go Back |
| ACOUPD-03 | happy | core fields | code/status/discount/min/max/validity/audience/products/creator/region |
| ACOUPD-04 | edge | flat discount | flat amount, min order, uses/user, formatted validity |
| ACOUPD-05 | edge | expired | “Expired” |
| ACOUPD-06 | edge | invalidated | “Inactive” |
| ACOUPD-07 | edge | global coupon | “Global”; “All regions”; no Edit |
| ACOUPD-08 | edge | user-based audience | “N users” + user name/mobile rows |
| ACOUPD-09 | edge | targeted products | “N selected” |
| ACOUPD-10 | happy | Edit | edit route |
| ACOUPD-11 | happy | Back | router.back |
### 8.3 Coupon create/edit
### 8.2 Coupon create/edit
| ID | Type | Case | Assert |
| --- | --- | --- | --- |
@ -641,7 +623,7 @@ Use these fixture names in the cases below.
| ACOUPE-09 | edge | back on OK | router.back |
| ACOUPE-10 | edge | global coupon edit | route should not be reachable; assert guard if direct |
### 8.4 CouponForm shared
### 8.3 CouponForm shared
| ID | Type | Case | Assert |
| --- | --- | --- | --- |

View file

@ -5,7 +5,6 @@ export default function Layout() {
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" options={{ title: "Coupons" }} />
<Stack.Screen name="create" options={{ title: "Create Coupon" }} />
<Stack.Screen name="detail/[id]" options={{ title: "Coupon Details" }} />
<Stack.Screen name="edit/[id]" options={{ title: "Edit Coupon" }} />
</Stack>
);

View file

@ -1,232 +0,0 @@
import React from 'react'
import { RefreshControl, ScrollView, View } from 'react-native'
import { useLocalSearchParams, useRouter } from 'expo-router'
import { MaterialCommunityIcons } from '@expo/vector-icons'
import { tw, MyText, MyTouchableOpacity, useMarkDataFetchers } from 'common-ui'
import { trpc } from '@/src/trpc-client'
const money = (value: string | number | null | undefined) =>
value == null || value === '' ? 'None' : `₹${Number(value)}`
const formatDate = (value: string | Date | null | undefined) =>
value ? new Date(value).toLocaleDateString() : 'No expiry'
const couponStatus = (coupon: any) => {
if (coupon.isInvalidated) return 'Inactive'
if (coupon.validTill && new Date(coupon.validTill) <= new Date()) return 'Expired'
return 'Active'
}
const statusStyles = (status: string) => {
if (status === 'Active') return { badge: 'bg-green-100', text: 'text-green-600' }
if (status === 'Expired') return { badge: 'bg-yellow-100', text: 'text-yellow-600' }
return { badge: 'bg-red-100', text: 'text-red-600' }
}
function DetailRow({
icon,
label,
value,
}: {
icon: React.ComponentProps<typeof MaterialCommunityIcons>['name']
label: string
value: string
}) {
return (
<View style={tw`flex-row items-center justify-between py-3 border-b border-gray-100`}>
<View style={tw`flex-row items-center flex-1 mr-3`}>
<MaterialCommunityIcons name={icon} size={18} color="#6b7280" />
<MyText style={tw`text-sm text-gray-500 ml-2`}>{label}</MyText>
</View>
<MyText style={tw`text-sm font-semibold text-gray-800 text-right`}>{value}</MyText>
</View>
)
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<View style={tw`bg-white rounded-2xl p-4 mb-4 shadow-sm`}>
<MyText style={tw`text-xs font-bold uppercase tracking-wider text-gray-400 mb-1`}>
{title}
</MyText>
{children}
</View>
)
}
export default function CouponDetails() {
const router = useRouter()
const { id } = useLocalSearchParams()
const rawId = Array.isArray(id) ? id[0] : id
const couponId = Number(rawId)
const hasValidId = Number.isInteger(couponId) && couponId > 0
const { data: coupon, isLoading, isFetching, error, refetch } =
trpc.admin.coupon.getById.useQuery(
{ id: couponId },
{ enabled: hasValidId }
)
useMarkDataFetchers(() => {
refetch()
})
const handleEdit = () => {
router.push(`/(drawer)/dashboard/coupons/edit/${couponId}`)
}
if (isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-white`}>
<MaterialCommunityIcons name="loading" size={32} color="#3b82f6" />
<MyText style={tw`text-gray-500 mt-4 font-medium`}>Loading coupon...</MyText>
</View>
)
}
if (error || !coupon) {
return (
<View style={tw`flex-1 justify-center items-center bg-white p-6`}>
<MaterialCommunityIcons name="ticket-percent-outline" size={56} color="#ef4444" />
<MyText style={tw`text-xl font-bold text-gray-900 mt-4`}>Coupon not found</MyText>
<MyTouchableOpacity
testID="coupon-detail-back"
onPress={() => router.back()}
style={tw`mt-6 px-8 py-3 bg-gray-100 rounded-full`}
>
<MyText style={tw`text-gray-800 font-semibold`}>Go Back</MyText>
</MyTouchableOpacity>
</View>
)
}
const status = couponStatus(coupon)
const colors = statusStyles(status)
const isGlobal = coupon.regionId == null
const users = coupon.applicableUsers ?? []
const skuCount = coupon.skuIds?.length ?? 0
const discount = coupon.discountPercent
? `${Number(coupon.discountPercent)}% off`
: coupon.flatDiscount
? `${money(coupon.flatDiscount)} off`
: 'None'
return (
<View style={tw`flex-1 bg-gray-50`}>
<View style={tw`flex-row items-center px-4 py-3 bg-white border-b border-gray-100`}>
<MyTouchableOpacity
testID="coupon-detail-back"
onPress={() => router.back()}
style={tw`p-2 -ml-2 mr-1`}
>
<MaterialCommunityIcons name="arrow-left" size={24} color="#111827" />
</MyTouchableOpacity>
<View style={tw`flex-1`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>Coupon Details</MyText>
<MyText style={tw`text-xs text-gray-500`}>ID: {coupon.id}</MyText>
</View>
{!isGlobal && (
<MyTouchableOpacity
testID="coupon-detail-edit"
onPress={handleEdit}
style={tw`flex-row items-center bg-blue-500 px-3 py-2 rounded-lg`}
>
<MaterialCommunityIcons name="pencil" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Edit</MyText>
</MyTouchableOpacity>
)}
</View>
<ScrollView
style={tw`flex-1`}
contentContainerStyle={tw`p-4 pb-10`}
refreshControl={<RefreshControl refreshing={isFetching} onRefresh={refetch} />}
>
<View style={tw`bg-white rounded-2xl p-5 mb-4 shadow-sm`}>
<View style={tw`flex-row items-center flex-wrap`}>
<MyText style={tw`text-2xl font-extrabold text-gray-900 mr-2`}>
{coupon.couponCode}
</MyText>
{isGlobal && (
<View style={tw`px-2 py-0.5 rounded-full bg-indigo-100 border border-indigo-200 mr-2`}>
<MyText style={tw`text-[10px] font-bold text-indigo-700`}>Global</MyText>
</View>
)}
<View style={tw`px-2 py-1 rounded-full ${colors.badge}`}>
<MyText style={tw`text-xs font-semibold ${colors.text}`}>{status}</MyText>
</View>
</View>
<MyText style={tw`text-base font-semibold text-gray-700 mt-3`}>{discount}</MyText>
{isGlobal && (
<View style={tw`mt-3 bg-indigo-50 border border-indigo-100 rounded-lg p-3`}>
<MyText style={tw`text-xs text-indigo-700`}>
Applies to all regions — created and managed by the superadmin.
</MyText>
</View>
)}
</View>
<Section title="Discount">
<DetailRow icon="percent" label="Type" value={coupon.discountPercent ? 'Percentage' : 'Flat amount'} />
<DetailRow icon="cart-outline" label="Min Order" value={money(coupon.minOrder)} />
<DetailRow icon="cash-multiple" label="Max Discount" value={money(coupon.maxValue)} />
<View style={tw`flex-row items-center justify-between py-3`}>
<View style={tw`flex-row items-center flex-1 mr-3`}>
<MaterialCommunityIcons name="repeat" size={18} color="#6b7280" />
<MyText style={tw`text-sm text-gray-500 ml-2`}>Uses / User</MyText>
</View>
<MyText style={tw`text-sm font-semibold text-gray-800 text-right`}>
{coupon.maxLimitForUser ? String(coupon.maxLimitForUser) : 'Unlimited'}
</MyText>
</View>
</Section>
<Section title="Validity & rules">
<DetailRow icon="calendar-blank-outline" label="Valid Till" value={formatDate(coupon.validTill)} />
<DetailRow icon="numeric-1-circle-outline" label="First Order Only" value={coupon.isFirstOrderOnly ? 'Yes' : 'No'} />
<DetailRow icon="lock-outline" label="Exclusive" value={coupon.exclusiveApply ? 'Yes' : 'No'} />
<DetailRow icon="map-marker-outline" label="Region" value={isGlobal ? 'All regions' : `Region #${coupon.regionId}`} />
</Section>
<Section title="Targeting">
<DetailRow
icon="account-group-outline"
label="Audience"
value={coupon.isApplyForAll ? 'All users' : `${users.length} users`}
/>
<DetailRow
icon="package-variant-closed"
label="Products"
value={skuCount === 0 ? 'Whole cart' : `${skuCount} selected`}
/>
{!coupon.isApplyForAll && users.length > 0 && (
<View style={tw`mt-2`}>
{users.map((user: any) => (
<View key={user.id} style={tw`flex-row items-center py-2 border-b border-gray-50`}>
<MaterialCommunityIcons name="account-circle-outline" size={18} color="#9ca3af" />
<MyText style={tw`text-sm text-gray-700 ml-2 flex-1`}>
{user.name || 'Unnamed user'}
</MyText>
<MyText style={tw`text-xs text-gray-500`}>{user.mobile || 'No mobile'}</MyText>
</View>
))}
</View>
)}
</Section>
<Section title="Created">
<DetailRow icon="account-outline" label="Created By" value={coupon.creator?.name || 'Unknown'} />
<View style={tw`flex-row items-center justify-between py-3`}>
<View style={tw`flex-row items-center flex-1 mr-3`}>
<MaterialCommunityIcons name="clock-outline" size={18} color="#6b7280" />
<MyText style={tw`text-sm text-gray-500 ml-2`}>Created On</MyText>
</View>
<MyText style={tw`text-sm font-semibold text-gray-800 text-right`}>
{coupon.createdAt ? new Date(coupon.createdAt).toLocaleDateString() : 'Unknown'}
</MyText>
</View>
</Section>
</ScrollView>
</View>
)
}

View file

@ -98,18 +98,8 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
)}
</View>
<MyTouchableOpacity
testID={`coupon-view-${item.id}`}
onPress={() => router.push(`/(drawer)/dashboard/coupons/detail/${item.id}` as any)}
accessibilityRole="button"
style={tw`flex-row items-center justify-center py-2 mb-2`}
>
<MyText style={tw`text-sm font-semibold text-blue-600`}>View details</MyText>
<MaterialCommunityIcons name="chevron-right" size={18} color="#2563eb" />
</MyTouchableOpacity>
{isGlobal ? (
<View style={tw`mt-1 bg-indigo-50 border border-indigo-100 rounded-lg p-3`}>
<View style={tw`mt-3 bg-indigo-50 border border-indigo-100 rounded-lg p-3`}>
<MyText style={tw`text-xs text-indigo-700`}>
Applies to all regions — created and managed by the superadmin.
</MyText>

View file

@ -400,13 +400,9 @@ export const COUPON_1 = {
applicableUsers: [],
isExclusive: false,
firstOrderOnly: false,
exclusiveApply: false,
isFirstOrderOnly: false,
regionId: 1,
maxLimitForUser: null,
usedCount: 0,
createdAt: '2026-01-01T00:00:00.000Z',
creator: { id: 1, name: 'Admin One', mobile: '9999999999' },
}
export const COUPON_GLOBAL = { ...COUPON_1, id: 22, couponCode: 'GLOBAL10', isApplyForAll: true, regionId: null }

View file

@ -1,152 +0,0 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 8.2 — Coupon detail (`tests/pages/coupon-detail.test.tsx`).
*/
import React from 'react'
import { fireEvent } from '@testing-library/react-native'
import CouponDetail from '@/app/(drawer)/dashboard/coupons/detail/[id]'
import { renderAndFlush, renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client'
import { __setParams, router } from '../mocks/expo-router-mock'
import { COUPON_1, COUPON_EXPIRED, COUPON_GLOBAL, COUPON_INVALIDATED } from '../fixtures'
function setCoupon(coupon: any) {
setProcedure('admin.coupon.getById', { data: coupon })
}
async function renderDetail() {
__setParams({ id: '21' })
return renderAndFlush(<CouponDetail />, { auth: false })
}
describe('Coupon detail (ACOUPD-01..11)', () => {
beforeEach(() => {
resetAllMocks()
__setParams({ id: '21' })
})
it('ACOUPD-01: shows the loading state', () => {
setProcedure('admin.coupon.getById', { mode: 'pending' })
const view = renderWithProviders(<CouponDetail />, { auth: false })
expect(view.getByText('Loading coupon...')).toBeTruthy()
})
it('ACOUPD-02: shows Coupon not found and goes back', async () => {
setCoupon(null)
const view = await renderDetail()
expect(view.getByText('Coupon not found')).toBeTruthy()
fireEvent.press(view.getByTestId('coupon-detail-back'))
expect(router.back).toHaveBeenCalled()
})
it('ACOUPD-03: renders the core coupon fields', async () => {
setCoupon(COUPON_1)
const view = await renderDetail()
expect(view.getByText('Coupon Details')).toBeTruthy()
expect(view.getByText('SAVE10')).toBeTruthy()
expect(view.getByText('Active')).toBeTruthy()
expect(view.getByText('10% off')).toBeTruthy()
expect(view.getByText('₹50')).toBeTruthy()
expect(view.getByText('All users')).toBeTruthy()
expect(view.getByText('Whole cart')).toBeTruthy()
expect(view.getByText('No expiry')).toBeTruthy()
expect(view.getByText('Admin One')).toBeTruthy()
expect(view.getByText('Region #1')).toBeTruthy()
})
it('ACOUPD-04: renders flat discounts, min order, usage limit and validity', async () => {
const validTill = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()
setCoupon({
...COUPON_1,
discountPercent: null,
flatDiscount: '50',
minOrder: '500',
maxLimitForUser: 2,
validTill,
})
const view = await renderDetail()
expect(view.getByText('₹50 off')).toBeTruthy()
expect(view.getByText('₹500')).toBeTruthy()
expect(view.queryByText('Percentage')).toBeNull()
expect(view.getByText('Flat amount')).toBeTruthy()
expect(view.getByText('Uses / User')).toBeTruthy()
expect(view.getByText('2')).toBeTruthy()
expect(view.queryByText('No expiry')).toBeNull()
})
it('ACOUPD-05: shows Expired for a past validTill', async () => {
setCoupon(COUPON_EXPIRED)
const view = await renderDetail()
expect(view.getByText('Expired')).toBeTruthy()
})
it('ACOUPD-06: shows Inactive for an invalidated coupon', async () => {
setCoupon(COUPON_INVALIDATED)
const view = await renderDetail()
expect(view.getByText('Inactive')).toBeTruthy()
})
it('ACOUPD-07: a global coupon is read-only and explains why', async () => {
setCoupon(COUPON_GLOBAL)
const view = await renderDetail()
expect(view.getByText('Global')).toBeTruthy()
expect(view.getByText('All regions')).toBeTruthy()
expect(
view.getByText('Applies to all regions — created and managed by the superadmin.')
).toBeTruthy()
expect(view.queryByTestId('coupon-detail-edit')).toBeNull()
expect(view.queryByText('Edit')).toBeNull()
})
it('ACOUPD-08: lists the targeted users for a user-based coupon', async () => {
setCoupon({
...COUPON_1,
isApplyForAll: false,
applicableUsers: [
{ id: 5, name: 'Test User', mobile: '9876543210' },
{ id: 6, name: 'Second User', mobile: '9876543211' },
],
})
const view = await renderDetail()
expect(view.getByText('2 users')).toBeTruthy()
expect(view.getByText('Test User')).toBeTruthy()
expect(view.getByText('9876543210')).toBeTruthy()
expect(view.getByText('Second User')).toBeTruthy()
expect(view.getByText('9876543211')).toBeTruthy()
})
it('ACOUPD-09: shows the number of targeted products', async () => {
setCoupon({ ...COUPON_1, skuIds: [11, 12] })
const view = await renderDetail()
expect(view.getByText('2 selected')).toBeTruthy()
})
it('ACOUPD-10: Edit opens the coupon edit route', async () => {
setCoupon(COUPON_1)
const view = await renderDetail()
fireEvent.press(view.getByTestId('coupon-detail-edit'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/edit/21')
})
it('ACOUPD-11: the header back button goes back', async () => {
setCoupon(COUPON_1)
const view = await renderDetail()
fireEvent.press(view.getByTestId('coupon-detail-back'))
expect(router.back).toHaveBeenCalled()
})
})

View file

@ -217,15 +217,6 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/edit/21')
})
it('ACOUPUI-13B: View details opens the coupon detail route', async () => {
setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const view = await renderCoupons()
fireEvent.press(view.getByTestId('coupon-view-21'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/detail/21')
})
it('ACOUPUI-14: Delete asks for confirmation and Cancel makes no API call', async () => {
setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const view = await renderCoupons()

View file

@ -49,7 +49,6 @@ import { Route as DashboardCouponsNewRouteImport } from './routes/dashboard.coup
import { Route as DashboardBannersNewRouteImport } from './routes/dashboard.banners.new'
import { Route as DashboardSlotsIdEditRouteImport } from './routes/dashboard.slots.$id.edit'
import { Route as DashboardProductGroupingsIdEditRouteImport } from './routes/dashboard.product-groupings.$id.edit'
import { Route as DashboardCouponsDetailIdRouteImport } from './routes/dashboard.coupons.detail.$id'
import { Route as DashboardCouponsIdEditRouteImport } from './routes/dashboard.coupons.$id.edit'
import { Route as DashboardBannersIdEditRouteImport } from './routes/dashboard.banners.$id.edit'
@ -260,12 +259,6 @@ const DashboardProductGroupingsIdEditRoute =
path: '/$id/edit',
getParentRoute: () => DashboardProductGroupingsRoute,
} as any)
const DashboardCouponsDetailIdRoute =
DashboardCouponsDetailIdRouteImport.update({
id: '/detail/$id',
path: '/detail/$id',
getParentRoute: () => DashboardCouponsRoute,
} as any)
const DashboardCouponsIdEditRoute = DashboardCouponsIdEditRouteImport.update({
id: '/$id/edit',
path: '/$id/edit',
@ -318,7 +311,6 @@ export interface FileRoutesByFullPath {
'/dashboard/users/$id': typeof DashboardUsersIdRoute
'/dashboard/banners/$id/edit': typeof DashboardBannersIdEditRoute
'/dashboard/coupons/$id/edit': typeof DashboardCouponsIdEditRoute
'/dashboard/coupons/detail/$id': typeof DashboardCouponsDetailIdRoute
'/dashboard/product-groupings/$id/edit': typeof DashboardProductGroupingsIdEditRoute
'/dashboard/slots/$id/edit': typeof DashboardSlotsIdEditRoute
}
@ -362,7 +354,6 @@ export interface FileRoutesByTo {
'/dashboard/users/$id': typeof DashboardUsersIdRoute
'/dashboard/banners/$id/edit': typeof DashboardBannersIdEditRoute
'/dashboard/coupons/$id/edit': typeof DashboardCouponsIdEditRoute
'/dashboard/coupons/detail/$id': typeof DashboardCouponsDetailIdRoute
'/dashboard/product-groupings/$id/edit': typeof DashboardProductGroupingsIdEditRoute
'/dashboard/slots/$id/edit': typeof DashboardSlotsIdEditRoute
}
@ -408,7 +399,6 @@ export interface FileRoutesById {
'/dashboard/users/$id': typeof DashboardUsersIdRoute
'/dashboard/banners/$id/edit': typeof DashboardBannersIdEditRoute
'/dashboard/coupons/$id/edit': typeof DashboardCouponsIdEditRoute
'/dashboard/coupons/detail/$id': typeof DashboardCouponsDetailIdRoute
'/dashboard/product-groupings/$id/edit': typeof DashboardProductGroupingsIdEditRoute
'/dashboard/slots/$id/edit': typeof DashboardSlotsIdEditRoute
}
@ -455,7 +445,6 @@ export interface FileRouteTypes {
| '/dashboard/users/$id'
| '/dashboard/banners/$id/edit'
| '/dashboard/coupons/$id/edit'
| '/dashboard/coupons/detail/$id'
| '/dashboard/product-groupings/$id/edit'
| '/dashboard/slots/$id/edit'
fileRoutesByTo: FileRoutesByTo
@ -499,7 +488,6 @@ export interface FileRouteTypes {
| '/dashboard/users/$id'
| '/dashboard/banners/$id/edit'
| '/dashboard/coupons/$id/edit'
| '/dashboard/coupons/detail/$id'
| '/dashboard/product-groupings/$id/edit'
| '/dashboard/slots/$id/edit'
id:
@ -544,7 +532,6 @@ export interface FileRouteTypes {
| '/dashboard/users/$id'
| '/dashboard/banners/$id/edit'
| '/dashboard/coupons/$id/edit'
| '/dashboard/coupons/detail/$id'
| '/dashboard/product-groupings/$id/edit'
| '/dashboard/slots/$id/edit'
fileRoutesById: FileRoutesById
@ -837,13 +824,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof DashboardProductGroupingsIdEditRouteImport
parentRoute: typeof DashboardProductGroupingsRoute
}
'/dashboard/coupons/detail/$id': {
id: '/dashboard/coupons/detail/$id'
path: '/detail/$id'
fullPath: '/dashboard/coupons/detail/$id'
preLoaderRoute: typeof DashboardCouponsDetailIdRouteImport
parentRoute: typeof DashboardCouponsRoute
}
'/dashboard/coupons/$id/edit': {
id: '/dashboard/coupons/$id/edit'
path: '/$id/edit'
@ -877,13 +857,11 @@ const DashboardBannersRouteWithChildren =
interface DashboardCouponsRouteChildren {
DashboardCouponsNewRoute: typeof DashboardCouponsNewRoute
DashboardCouponsIdEditRoute: typeof DashboardCouponsIdEditRoute
DashboardCouponsDetailIdRoute: typeof DashboardCouponsDetailIdRoute
}
const DashboardCouponsRouteChildren: DashboardCouponsRouteChildren = {
DashboardCouponsNewRoute: DashboardCouponsNewRoute,
DashboardCouponsIdEditRoute: DashboardCouponsIdEditRoute,
DashboardCouponsDetailIdRoute: DashboardCouponsDetailIdRoute,
}
const DashboardCouponsRouteWithChildren =

View file

@ -1,252 +0,0 @@
import React from 'react'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import {
ArrowLeft,
CalendarDays,
CircleAlert,
Globe2,
IndianRupee,
Loader2,
Lock,
Package,
Pencil,
Percent,
Repeat,
ShoppingCart,
User,
Users,
Wallet,
} from 'lucide-react'
import { AppContainer, p as MyText } from 'web-components'
import { trpc } from '@/lib/trpc-client'
import { useMarkDataFetchers } from '@/lib/refresh-context'
export const Route = createFileRoute('/dashboard/coupons/detail/$id')({
component: CouponDetail,
})
const money = (value: string | number | null | undefined) =>
value == null || value === '' ? 'None' : `₹${Number(value)}`
const formatDate = (value: string | Date | null | undefined) =>
value ? new Date(value).toLocaleDateString() : 'No expiry'
function couponStatus(coupon: any) {
if (coupon.isInvalidated) return 'Inactive'
if (coupon.validTill && new Date(coupon.validTill) <= new Date()) return 'Expired'
return 'Active'
}
function statusClasses(status: string) {
if (status === 'Active') return { badge: 'bg-green-100', text: 'text-green-600' }
if (status === 'Expired') return { badge: 'bg-yellow-100', text: 'text-yellow-600' }
return { badge: 'bg-red-100', text: 'text-red-600' }
}
function DetailRow({
icon,
label,
value,
}: {
icon: React.ReactNode
label: string
value: string
}) {
return (
<div className="flex flex-row items-center justify-between border-b border-gray-100 py-3">
<div className="mr-3 flex flex-1 flex-row items-center">
{icon}
<MyText className="ml-2 text-sm text-gray-500">{label}</MyText>
</div>
<MyText className="text-right text-sm font-semibold text-gray-800">{value}</MyText>
</div>
)
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<div className="mb-4 rounded-2xl bg-white p-4 shadow-sm">
<MyText className="mb-1 block text-xs font-bold uppercase tracking-wider text-gray-400">
{title}
</MyText>
{children}
</div>
)
}
function CouponDetail() {
const { id } = Route.useParams()
const navigate = useNavigate()
const couponId = Number(id)
const hasValidId = Number.isInteger(couponId) && couponId > 0
const { data: coupon, isLoading, isFetching, error, refetch } =
trpc.admin.coupon.getById.useQuery({ id: couponId }, { enabled: hasValidId })
useMarkDataFetchers(() => {
refetch()
})
if (isLoading) {
return (
<AppContainer>
<div className="flex flex-1 flex-col items-center justify-center bg-white">
<Loader2 size={32} color="#3b82f6" className="mb-4 animate-spin" />
<MyText className="mt-2 font-medium text-gray-500">Loading coupon...</MyText>
</div>
</AppContainer>
)
}
if (error || !coupon) {
return (
<AppContainer>
<div className="flex flex-1 flex-col items-center justify-center bg-white p-6">
<CircleAlert size={56} color="#ef4444" />
<MyText className="mt-4 block text-xl font-bold text-gray-900">Coupon not found</MyText>
<button
onClick={() => window.history.back()}
className="mt-6 rounded-full bg-gray-100 px-8 py-3"
>
<MyText className="font-semibold text-gray-800">Go Back</MyText>
</button>
</div>
</AppContainer>
)
}
const status = couponStatus(coupon)
const colors = statusClasses(status)
const isGlobal = coupon.regionId == null
const users = coupon.applicableUsers ?? []
const skuCount = coupon.skuIds?.length ?? 0
const discount = coupon.discountPercent
? `${Number(coupon.discountPercent)}% off`
: coupon.flatDiscount
? `${money(coupon.flatDiscount)} off`
: 'None'
return (
<AppContainer>
<div className="mb-4 flex flex-row items-center border-b border-gray-100 pb-3">
<button onClick={() => window.history.back()} aria-label="Back" className="mr-2 p-2">
<ArrowLeft size={24} color="#111827" />
</button>
<div className="flex-1">
<MyText className="block text-lg font-bold text-gray-900">Coupon Details</MyText>
<MyText className="block text-xs text-gray-500">ID: {coupon.id}</MyText>
</div>
{!isGlobal && (
<button
onClick={() =>
navigate({ to: '/dashboard/coupons/$id/edit', params: { id: String(couponId) } })
}
className="flex flex-row items-center rounded-lg bg-blue-500 px-3 py-2"
>
<Pencil size={16} color="white" />
<MyText className="ml-1 font-semibold text-white">Edit</MyText>
</button>
)}
</div>
<div className="mb-4 rounded-2xl bg-white p-5 shadow-sm">
<div className="flex flex-row flex-wrap items-center gap-2">
<MyText className="text-2xl font-extrabold text-gray-900">{coupon.couponCode}</MyText>
{isGlobal && (
<span className="rounded-full border border-indigo-200 bg-indigo-100 px-2 py-0.5 text-[10px] font-bold text-indigo-700">
Global
</span>
)}
<span className={`rounded-full px-2 py-1 text-xs font-semibold ${colors.badge} ${colors.text}`}>
{status}
</span>
</div>
<MyText className="mt-3 block text-base font-semibold text-gray-700">{discount}</MyText>
{isGlobal && (
<div className="mt-3 rounded-lg border border-indigo-100 bg-indigo-50 p-3">
<MyText className="block text-xs text-indigo-700">
Applies to all regions — created and managed by the superadmin.
</MyText>
</div>
)}
</div>
<Section title="Discount">
<DetailRow
icon={coupon.discountPercent ? <Percent size={18} color="#6b7280" /> : <IndianRupee size={18} color="#6b7280" />}
label="Type"
value={coupon.discountPercent ? 'Percentage' : 'Flat amount'}
/>
<DetailRow icon={<ShoppingCart size={18} color="#6b7280" />} label="Min Order" value={money(coupon.minOrder)} />
<DetailRow icon={<Wallet size={18} color="#6b7280" />} label="Max Discount" value={money(coupon.maxValue)} />
<div className="flex flex-row items-center justify-between py-3">
<div className="mr-3 flex flex-1 flex-row items-center">
<Repeat size={18} color="#6b7280" />
<MyText className="ml-2 text-sm text-gray-500">Uses / User</MyText>
</div>
<MyText className="text-right text-sm font-semibold text-gray-800">
{coupon.maxLimitForUser ? String(coupon.maxLimitForUser) : 'Unlimited'}
</MyText>
</div>
</Section>
<Section title="Validity & rules">
<DetailRow icon={<CalendarDays size={18} color="#6b7280" />} label="Valid Till" value={formatDate(coupon.validTill)} />
<DetailRow
icon={<User size={18} color="#6b7280" />}
label="First Order Only"
value={coupon.isFirstOrderOnly ? 'Yes' : 'No'}
/>
<DetailRow icon={<Lock size={18} color="#6b7280" />} label="Exclusive" value={coupon.exclusiveApply ? 'Yes' : 'No'} />
<DetailRow
icon={<Globe2 size={18} color="#6b7280" />}
label="Region"
value={isGlobal ? 'All regions' : `Region #${coupon.regionId}`}
/>
</Section>
<Section title="Targeting">
<DetailRow
icon={<Users size={18} color="#6b7280" />}
label="Audience"
value={coupon.isApplyForAll ? 'All users' : `${users.length} users`}
/>
<DetailRow
icon={<Package size={18} color="#6b7280" />}
label="Products"
value={skuCount === 0 ? 'Whole cart' : `${skuCount} selected`}
/>
{!coupon.isApplyForAll && users.length > 0 && (
<div className="mt-2">
{users.map((user: any) => (
<div key={user.id} className="flex flex-row items-center border-b border-gray-50 py-2">
<User size={18} color="#9ca3af" />
<MyText className="ml-2 flex-1 text-sm text-gray-700">
{user.name || 'Unnamed user'}
</MyText>
<MyText className="text-xs text-gray-500">{user.mobile || 'No mobile'}</MyText>
</div>
))}
</div>
)}
</Section>
<Section title="Created">
<DetailRow
icon={<User size={18} color="#6b7280" />}
label="Created By"
value={coupon.creator?.name || 'Unknown'}
/>
<div className="flex flex-row items-center justify-between py-3">
<div className="mr-3 flex flex-1 flex-row items-center">
<CalendarDays size={18} color="#6b7280" />
<MyText className="ml-2 text-sm text-gray-500">Created On</MyText>
</div>
<MyText className="text-right text-sm font-semibold text-gray-800">
{coupon.createdAt ? new Date(coupon.createdAt).toLocaleDateString() : 'Unknown'}
</MyText>
</div>
</Section>
</AppContainer>
)
}

View file

@ -1,6 +1,6 @@
import React, { useState, useCallback, useMemo } from 'react'
import { createFileRoute, Outlet, useLocation, useNavigate } from '@tanstack/react-router'
import { Percent, IndianRupee, Pencil, Trash2, TicketPercent, CircleAlert, Loader2, Users, Package, UserCheck, User, ListFilter, Plus, ChevronRight } from 'lucide-react'
import { Percent, IndianRupee, Pencil, Trash2, TicketPercent, CircleAlert, Loader2, Users, Package, UserCheck, User, ListFilter, Plus } from 'lucide-react'
import { p as MyText, MyButton, SearchBar, MyFlatList } from 'web-components'
import { useManualRefresh, useMarkDataFetchers } from '@/lib/refresh-context'
import { trpc } from '@/lib/trpc-client'
@ -101,16 +101,8 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v
)}
</div>
<button
onClick={() => navigate({ to: '/dashboard/coupons/detail/$id', params: { id: String(item.id) } })}
className="mb-2 flex w-full flex-row items-center justify-center gap-1 py-2"
>
<MyText className="text-sm font-semibold text-blue-600">View details</MyText>
<ChevronRight size={16} color="#2563eb" />
</button>
{isGlobal ? (
<div className="mt-1 rounded-lg border border-indigo-100 bg-indigo-50 p-3">
<div className="mt-3 rounded-lg border border-indigo-100 bg-indigo-50 p-3">
<MyText className="block text-xs text-indigo-700">
Applies to all regions — created and managed by the superadmin.
</MyText>

View file

@ -838,7 +838,6 @@ known stale-test bug.
| UORD-43 | edge | coupon owned by another user | rejected |
| UORD-44 | edge | invalidated/expired coupon | rejected |
| UORD-45 | edge | usage-limit coupon | rejected |
| UORD-45B | edge | coupon with 2 permitted usages | two orders store the coupon; usageCount is 2; third order rejects with usage limit exceeded |
| UORD-46 | edge | min-order not met | rejected/not applied |
| UORD-47 | edge | targeted SKU coupon | discount only target |
| UORD-47B | edge | targeted SKU coupon, target below minOrder but whole cart above it | accepted; discount only on target |
@ -1220,7 +1219,6 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
| ACOUP-13 | edge | validTill | parsed |
| ACOUP-14 | happy | getAll + pagination + search | |
| ACOUP-15 | happy | getById | coupon + applicableUsers ids |
| ACOUP-15B | happy | getById for a global coupon | region admin reads a superadmin-created global coupon |
| ACOUP-16 | error | unknown | error |
| ACOUP-17 | happy | update partial | fields present win |
| ACOUP-18 | edge | update code top-level/array | uppercase |
@ -1818,7 +1816,7 @@ and side-effect tests. Use this table as the completion gate.
| admin.order | cancelOrder | AORD-31..38 |
| admin.coupon | create | ACOUP-01..13 |
| admin.coupon | getAll | ACOUP-14 |
| admin.coupon | getById | ACOUP-15, 15B, 16 |
| admin.coupon | getById | ACOUP-15..16 |
| admin.coupon | update | ACOUP-17..21 |
| admin.coupon | delete | ACOUP-22..24 |
| admin.coupon | getReservedCoupons | ACOUP-25 |

View file

@ -1,17 +1,17 @@
# Generated by tests/seed-local.ts — local-only credentials.
API_BASE_URL=http://localhost:8787
TEST_STAFF_NAME=shafi
TEST_STAFF_PASSWORD=shafI123
TEST_STAFF_NAME=e2e_staff
TEST_STAFF_PASSWORD=FreshyoTest!2026
TEST_USER_IDENTIFIER=9676651496
TEST_USER_PASSWORD=meatfarmer@123
TEST_USER_IDENTIFIER=e2e.user@freshyo.test
TEST_USER_PASSWORD=FreshyoTest!2026
# Credentials-less account for UAUTH-09 / UPASS-04.
TEST_NOCREDS_IDENTIFIER=e2e.nocreds@freshyo.test
TEST_SUPERADMIN_USERNAME=superadmin
TEST_SUPERADMIN_PASSWORD=superadmiN123
TEST_SUPERADMIN_USERNAME=e2e_super
TEST_SUPERADMIN_PASSWORD=FreshyoTest!2026
# Region/bound used by most suites (seeded by migrations).
TEST_REGION_ID=1

View file

@ -16,7 +16,7 @@
*/
import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { anonClient, staffClient, superadminClient, userClient } from '../helpers/sessions'
import { anonClient, staffClient, userClient } from '../helpers/sessions'
import {
createCatalogOrderFixture,
placeOrder,
@ -283,24 +283,6 @@ describe('admin.coupon.getAll / getById (ACOUP-14..16)', () => {
expect(fetched.creator).toBeTruthy()
})
it('ACOUP-15B: a region admin can read a global coupon by id', async () => {
const superadmin = await superadminClient()
const created: any = await superadmin.superadmin.globalCoupons.create.mutate({
couponCode: code('GBYID'),
flatDiscount: 15,
isApplyForAll: true,
})
const global = created.coupons[0]
const admin = await staffClient()
const fetched: any = await admin.admin.coupon.getById.query({ id: Number(global.id) })
expect(fetched.id).toBe(Number(global.id))
expect(fetched.regionId).toBeNull()
expect(fetched.couponCode).toBe(global.couponCode)
expect(Number(fetched.flatDiscount)).toBe(15)
})
it('ACOUP-16 (current): an unknown id is an INTERNAL_SERVER_ERROR; a non-numeric id is BAD_REQUEST', async () => {
const admin = await staffClient()
await expectTrpcError(

View file

@ -1010,40 +1010,6 @@ describe('user.order.placeOrder — coupons (UORD-39..56)', () => {
)
})
it('UORD-45B: a two-use coupon is marked used after two orders and rejects the third', async () => {
const fx = await createCatalogOrderFixture({ price: 199 })
const c = await makeCoupon({ flatDiscount: 20, minOrder: 1, maxLimitForUser: 2 })
const place = () =>
placeCall(fx.user.token, {
addressId: fx.address.id,
skuId: fx.product.skuId,
slotId: fx.slot.slotId,
couponIds: [c.id],
})
const first = await place()
expect(first.success).toBe(true)
expect(Number(first.data[0].discountAmount)).toBe(20)
expect((await detail(fx.user.token, Number(first.data[0].id))).couponCode).toBe(c.couponCode)
const second = await place()
expect(second.success).toBe(true)
expect(Number(second.data[0].discountAmount)).toBe(20)
expect((await detail(fx.user.token, Number(second.data[0].id))).couponCode).toBe(c.couponCode)
const mine: any = await apiClient(fx.user.token).user.coupon.getMyCoupons.query({
regionId: REGION_1,
})
const found = [...(mine.data.personal ?? []), ...(mine.data.general ?? [])].find(
(coupon: any) => coupon.code === c.couponCode
)
expect(found?.usageCount).toBe(2)
expect(found?.isUsedUp).toBe(true)
await expectTrpcError(place, 'INTERNAL_SERVER_ERROR', 'usage limit exceeded')
})
it('UORD-46: a coupon whose minimum order is not met is rejected', async () => {
const fx = await createCatalogOrderFixture({ price: 199 })
const c = await makeCoupon({ flatDiscount: 50, minOrder: 100_000 })

View file

@ -130,7 +130,8 @@ Use these names in the cases below so the expected values stay consistent.
| ROOT-12 | happy | `webviewHtml` absent | children render |
| ROOT-13 | edge | `webviewHtml` present, not closable | WebView renders and children are hidden |
| ROOT-14 | edge | closable WebView | close button hides WebView and shows children |
| ROOT-16 | edge | remote internal version ahead | alert shown once; Update & Restart calls `fetchUpdateAsync` then `reloadAsync` |
| ROOT-15 | edge | `__DEV__` true and remote internal version ahead | UpdateChecker does not alert |
| ROOT-16 | edge | prod and remote internal version ahead | alert shown once; Update & Restart calls `fetchUpdateAsync` then `reloadAsync` |
| ROOT-17 | error | update fetch/reload rejects | alert stays/does not crash |
| ROOT-18 | happy | back press on home with empty stack | `Exit App` alert; Exit calls `BackHandler.exitApp`; returns `true` |
| ROOT-19 | edge | back press on non-home route | returns `false`; no alert |
@ -868,7 +869,7 @@ real.
| PAY-09 | edge | no coupons | `couponIds` omitted/undefined |
| PAY-10 | edge | selected coupons | ids in same order |
| PAY-11 | edge | bound resolution | `constsData.boundId` first, else `useRegion().boundId` |
| PAY-12 | happy | success | clears correct cart, invalidates local-cart, getOrders and getEligible |
| PAY-12 | happy | success | clears correct cart, invalidates local-cart and getOrders |
| PAY-13 | edge | success server total | sums all returned order totals |
| PAY-14 | edge | server total 0/missing | falls back to `finalTotalWithDelivery` |
| PAY-15 | edge | success navigation regular | `./order-success?orderId=…&totalAmount=…` |

View file

@ -85,10 +85,6 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
// keep showing the pre-order list.
utils.user.order.getOrders.invalidate();
// The cart/checkout coupon dropdown observes getEligible. An order consumes
// coupon usage and can flip `isFirstOrder`, so drop the pre-order list.
utils.user.coupon.getEligible.invalidate();
// Clear cart and navigate to success page. Prefer the amount the server
// actually stored across the (possibly split) orders over the local preview.
clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular');

View file

@ -18,6 +18,8 @@ const UpdateChecker: React.FC<ReactParentComponent> = ({ children }) => {
const prompted = useRef(false);
useEffect(() => {
// Never nag in development; the dev build talks to a dev backend.
// if (__DEV__) return;
if (prompted.current) return;
const remoteVersion = data?.internalAppVersion;

View file

@ -212,10 +212,8 @@ function DeliverySlotSummary({
))}
{!!mergeSuggestion && (
<MyTouchableOpacity
<View
testID="delivery-slot-merge"
onPress={onMerge}
activeOpacity={0.7}
style={tw`mt-3 flex-row items-center justify-between rounded-xl px-3 py-2.5 border bg-brand50 border-brand200`}
>
<View style={tw`flex-row items-center flex-1 mr-2`}>
@ -224,10 +222,15 @@ function DeliverySlotSummary({
Deliver All items at {mergeSuggestion.label}
</MyText>
</View>
<View testID="delivery-slot-merge-apply" style={tw`p-1`}>
<MyTouchableOpacity
testID="delivery-slot-merge-apply"
onPress={onMerge}
activeOpacity={0.7}
style={tw`p-1`}
>
<MaterialIcons name="chevron-right" size={20} color="#1570EF" />
</View>
</MyTouchableOpacity>
</View>
)}
</View>

View file

@ -56,6 +56,11 @@ const rootQueryClient = require('@/utils/queryClient').default
const fontsMock = useFonts as unknown as jest.Mock
const SOURCE_VERSION = '1.2.0'
const DEV = (global as any).__DEV__
function setDev(value: boolean) {
;(global as any).__DEV__ = value
}
function renderHealth(overrides: Record<string, any> = {}) {
seedRegion()
@ -94,6 +99,11 @@ describe('app shell (ROOT-01..ROOT-29)', () => {
resetAllMocks()
rootQueryClient.clear()
fontsMock.mockReturnValue([true, null])
setDev(DEV)
})
afterEach(() => {
setDev(DEV)
})
it('ROOT-01: an unloaded font set renders nothing', () => {
@ -281,7 +291,20 @@ describe('app shell (ROOT-01..ROOT-29)', () => {
expect(view.queryByTestId('webview')).toBeNull()
})
it('ROOT-16: a newer backend internal version alerts once and updates', async () => {
it('ROOT-15: in development a newer backend internal version does not alert', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
setDev(true)
renderUpdateChecker()
setProcedure('common.essentialConsts', {
data: { ...CONSTS, internalAppVersion: 5 },
})
await flush(3)
expect(alertSpy).not.toHaveBeenCalled()
})
it('ROOT-16: in production a newer backend internal version alerts once and updates', async () => {
setDev(false)
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
renderUpdateChecker()
setProcedure('common.essentialConsts', {
@ -305,6 +328,7 @@ describe('app shell (ROOT-01..ROOT-29)', () => {
})
it('ROOT-17: an update fetch failure does not crash or reload', async () => {
setDev(false)
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
;(Updates.fetchUpdateAsync as jest.Mock).mockRejectedValueOnce(new Error('no update'))
renderUpdateChecker()

View file

@ -9,6 +9,7 @@
import * as React from 'react'
import { ScrollView, TouchableOpacity } from 'react-native'
import { fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs'
import AddToCartDialog from '@/src/components/AddToCartDialog'
import { useCartStore } from '@/src/store/cartStore'
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
@ -18,8 +19,9 @@ import { CART_REG, P_CHICKEN, P_CUCUMBER, SLOTS } from '../fixtures'
const APPENDED_AT = '2024-01-01T00:00:00.000Z'
/** The dialog keys each slot row by the slot id. */
const slotTestId = (slot: { id: number }) => `slot-option-${slot.id}`
/** The dialog labels each slot row with its delivery minute. */
const slotTestId = (slot: { deliveryTime: string }) =>
`slot-${dayjs(slot.deliveryTime).format('YYYY-MM-DD-HH-mm')}`
// Chicken (SKU 2) is served by every fixture slot; only the three whose
// freezeTime is still in the future survive the dialog's filter.

View file

@ -278,7 +278,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
expect(view.getByTestId('address-delete-12')).toBeTruthy()
// `mode: 'pending'` short-circuits the registry before it records calls, so
// count the real client's request at the network boundary instead.
const deleteRequests = (global.fetch as unknown as jest.Mock).mock.calls.filter(([url]) =>
const deleteRequests = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
String(url).includes('user.address.deleteAddress')
)
expect(deleteRequests).toHaveLength(1)

View file

@ -685,7 +685,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 1, 1849), line(2, 5, 1, 1849), line(3, 2, 1, 1852), line(4, 5, 1, 1852)],
})
fireEvent.press(getByTestId('delivery-slot-merge'))
fireEvent.press(getByTestId('delivery-slot-merge-apply'))
await flush(2)
expect(getByTestId('delivery-slot-items-1849')).toBeTruthy()
expect(textOf(getByTestId('delivery-slot-items-1849'))).toContain('4 items')
@ -706,7 +706,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
lines: [line(1, 2, 1, 1852), line(2, 5, 1, 1852), line(3, 8, 1, 1850)],
})
expect(getByTestId('delivery-slot-merge')).toBeTruthy()
fireEvent.press(getByTestId('delivery-slot-merge'))
fireEvent.press(getByTestId('delivery-slot-merge-apply'))
await flush(2)
expect(getByTestId('delivery-slot-items-1852')).toBeTruthy()
expect(textOf(getByTestId('delivery-slot-items-1852'))).toContain('3 items')
@ -723,7 +723,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
],
setup: () => setProcedure('user.cart.getCartSlots', { data: customSlots }),
})
fireEvent.press(getByTestId('delivery-slot-merge'))
fireEvent.press(getByTestId('delivery-slot-merge-apply'))
await flush(2)
expect(textOf(getByTestId('delivery-slot-items-1852'))).toContain('3 items')
// The out-of-stock mutton keeps its old 1849 slot and is not merged.

View file

@ -22,6 +22,7 @@ import {
StyleSheet,
} from 'react-native'
import { act, fireEvent, waitFor, within } from '@testing-library/react-native'
import dayjs from 'dayjs'
import { QueryClient } from '@tanstack/react-query'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
@ -187,8 +188,9 @@ async function emitManualRefresh() {
await flush(2)
}
/** The dialog keys each slot row by the slot id. */
const slotTestId = (slot: { id: number }) => `slot-option-${slot.id}`
/** The dialog labels each slot row with its delivery minute. */
const slotTestId = (slot: { deliveryTime: string }) =>
`slot-${dayjs(slot.deliveryTime).format('YYYY-MM-DD-HH-mm')}`
const CART_LINE_ADDED_AT = '2024-01-01T00:00:00.000Z'

View file

@ -236,7 +236,7 @@ describe('PaymentAndOrder — PAY-01..29', () => {
/* Success, failure and loading */
/* ------------------------------------------------------------------------ */
it('PAY-12: success clears the regular cart and invalidates local-cart + getOrders + getEligible', async () => {
it('PAY-12: success clears the regular cart and invalidates local-cart + getOrders', async () => {
__set(CART_KEY, JSON.stringify([line(1, 2, 2, 1849)]))
__set(FLASH_KEY, JSON.stringify([line(9, 8, 1, 0)]))
const { getByTestId, queryClient } = await mountPay()
@ -249,7 +249,6 @@ describe('PaymentAndOrder — PAY-01..29', () => {
expect(JSON.parse(__snapshot()[FLASH_KEY])).toHaveLength(1)
expect(invalidate).toHaveBeenCalledWith({ queryKey: ['local-cart-regular'] })
expect(procedureInvalidations('user.order.getOrders').length).toBeGreaterThan(0)
expect(procedureInvalidations('user.coupon.getEligible').length).toBeGreaterThan(0)
})
it('PAY-13: success uses the sum of every returned order total', async () => {
@ -334,7 +333,7 @@ describe('PaymentAndOrder — PAY-01..29', () => {
// `mode: 'pending'` short-circuits the registry before it records calls, so
// count the real client's requests at the network boundary instead.
const placeOrderRequests = (global.fetch as unknown as jest.Mock).mock.calls.filter(([url]) =>
const placeOrderRequests = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
String(url).includes('user.order.placeOrder')
)
expect(placeOrderRequests).toHaveLength(1)

View file

@ -8828,120 +8828,3 @@ uses no usage cap and never retries the coupon. Add a stronger regression test:
same coupon usable again.
- apps/backend/API-TEST-CASES.md: document UORD-108B.
No production code change. No test suite run (repo instruction).
[2026-10-23 15:15:04 IST] Cart: make the whole merge-slot suggestion tappable.
- apps/user-ui/components/cart-page.tsx: the merge suggestion row is now one
MyTouchableOpacity (`delivery-slot-merge`) with `onPress={onMerge}`; the
chevron is a plain icon, so tapping the text/padding works too, not just the
right-most icon. `delivery-slot-merge-apply` remains as the chevron testID.
- apps/user-ui/tests/pages/cart.test.tsx: CART-46/49/50 press the whole
`delivery-slot-merge` row instead of the icon-only child.
Verified: apps/user-ui typecheck shows only the two pre-existing `fetch as Mock`
errors in addresses/payment tests. No test suite run (repo instruction).
[2026-10-23 15:18:35 IST] Fix test typecheck for the mocked global fetch.
- apps/user-ui/tests/pages/addresses.test.tsx: ADDR-13 casts `global.fetch`
through `unknown` before `jest.Mock` (the global is typed as `typeof fetch`).
- apps/user-ui/tests/pages/payment-and-order.test.tsx: PAY-18 same cast.
No behavior change. Verified: `npx tsc --noEmit --project tsconfig.json` in
apps/user-ui is now clean.
[2026-10-23 15:23:21 IST] Align add-to-cart slot test IDs with the component.
- apps/user-ui/tests/pages/home.test.tsx: `slotTestId` now returns
`slot-option-${slot.id}` (the live AddToCartDialog testID) instead of a
delivery-time string, and the unused dayjs import is removed.
- apps/user-ui/tests/components/add-to-cart-dialog.test.tsx: same helper change
and unused dayjs import removal. This fixes HOME-64/65/66/71/72/80 and
A2C-01/02, which were looking for the old date-based IDs.
Test-only change; no production behavior.
Verified: `npx tsc --noEmit --project tsconfig.json` in apps/user-ui is clean
after the helper change. `CI=true bunx jest --config tests/jest.config.js
--runInBand --silent` in apps/user-ui => 51/52 suites pass, 1166/1167 tests pass. The one
failure is ROOT-15 because `if (__DEV__) return;` is commented out in
components/UpdateChecker.tsx (commit c1becb82); left untouched because it looks
intentional for OTA testing. Backend UORD-47B/UORD-108B could not run:
globalSetup staff login returned 401 ("backend up and seeded?"); no seed or
migration was run.
[2026-10-23 15:28:29 IST] Point backend live-test env at the e2e test creds.
- apps/backend/tests/.env: set TEST_STAFF_NAME/TEST_STAFF_PASSWORD,
TEST_SUPERADMIN_USERNAME/TEST_SUPERADMIN_PASSWORD and
TEST_USER_IDENTIFIER/TEST_USER_PASSWORD to the values in
tests/e2e/test-creds.txt (copied verbatim; not duplicated in this log).
TEST_NOCREDS_IDENTIFIER, region/bound and cache knobs unchanged.
Verified: targeted UORD-47B and UORD-108B pass against localhost:8787 with these
creds (2 passed, 108 skipped). No migration or seed run.
[2026-10-23 15:32:18 IST] Invalidate eligible coupons after a successful order.
- apps/user-ui/components/PaymentAndOrderComponent.tsx: on a successful
placeOrder, also call `utils.user.coupon.getEligible.invalidate()`. This is
the query used by both cart-page and checkout-page; an order consumes coupon
usage and flips `isFirstOrder`, so the dropdown must not keep the pre-order
list.
- apps/user-ui/tests/pages/payment-and-order.test.tsx: PAY-12 now asserts
`user.coupon.getEligible` was invalidated along with local-cart and getOrders.
- apps/user-ui/JEST-TEST-CASES.md: update the PAY-12 row.
No web-ui mirror needed: web-ui has no `getEligible` query/coupon selection.
Verified: user-ui typecheck clean; `tests/pages/payment-and-order.test.tsx`
passes (29/29), including the new getEligible invalidation assertion.
[2026-10-23 15:36:34 IST] Cover a two-use coupon end to end.
The backend had UORD-45 for maxLimitForUser 1 but no test that spends a
multi-use allowance and then checks the next order is refused. Add:
- apps/backend/tests/api/user-order-place.test.ts: UORD-45B places two orders
with the same coupon (maxLimitForUser 2), asserts both orders store the coupon
code and discount, asserts getMyCoupons reports usageCount 2 + isUsedUp true,
then asserts the third order fails with "usage limit exceeded".
- apps/backend/API-TEST-CASES.md: document UORD-45B.
No production code change.
Verified: backend test typecheck clean; UORD-45B passes (1 passed, 71 skipped).
[2026-10-23 15:39:06 IST] Remove the UpdateChecker dev guard and its test.
- apps/user-ui/components/UpdateChecker.tsx: delete the commented-out
`if (__DEV__) return;` and its comment. The version gate now always compares
the shipped and remote internal versions, in development and production.
- apps/user-ui/tests/app/root-layout.test.tsx: remove ROOT-15 (dev-mode no
alert) plus the now-unused DEV/setDev helper and beforeEach/afterEach resets;
drop the remaining setDev(false) calls from ROOT-16/17.
- apps/user-ui/JEST-TEST-CASES.md: remove the ROOT-15 row and adjust ROOT-16.
No production behavior change (the guard was already commented out).
Verified: user-ui typecheck clean; root-layout 23/23; full user-ui suite
52/52 suites and 1166/1166 tests pass.
[2026-10-23 18:26:41 IST] Add a read-only coupon details screen (admin-ui + admin-web).
- packages/db_helper_sqlite/src/admin-apis/coupon.ts: getCouponById now accepts
a coupon from the staff member's own region OR a global coupon (region_id
NULL), matching getAll's visibility. Writes still use the region-scoped
update function.
- apps/backend/tests/api/admin-coupon.test.ts: add ACOUP-15B (region admin reads
a superadmin-created global coupon by id) and import superadminClient.
- apps/backend/API-TEST-CASES.md: document ACOUP-15B.
- apps/admin-ui/app/(drawer)/dashboard/coupons/detail/[id].tsx: new details
screen: header with back + edit, status/global badges, discount/limits/
validity/rules, audience list, product targeting, creator and created date.
Read-only; edit is hidden for global coupons.
- apps/admin-ui/app/(drawer)/dashboard/coupons/_layout.tsx: register the
detail/[id] route as "Coupon Details".
- apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx: add a "View details"
link on every general coupon card (including global coupons).
- apps/admin-ui/tests/fixtures/index.ts: enrich COUPON_1 with createdAt,
creator, maxLimitForUser, exclusiveApply and isFirstOrderOnly.
- apps/admin-ui/tests/pages/coupon-detail.test.tsx: new ACOUPD-01..11 suite
(loading, not found, core fields, flat/min/max, expired, invalidated, global,
audience, products, edit route, back).
- apps/admin-ui/tests/pages/coupons.test.tsx: add ACOUPUI-13B (View details
opens the detail route).
- apps/admin-ui/JEST-TEST-CASES.md: register the route/test mapping and add
ACOUPUI-13B + ACOUPD-01..11.
- apps/admin-web/src/routes/dashboard.coupons.detail.$id.tsx: new web details
screen mirroring the native one.
- apps/admin-web/src/routes/dashboard.coupons.tsx: add "View details" on each
card, navigating to /dashboard/coupons/detail/$id.
- apps/admin-web/src/routeTree.gen.ts: register the new
/dashboard/coupons/detail/$id route (TanStack plugin regenerated it).
No database migration.
Verified: admin-ui typecheck clean; admin-web typecheck clean; db_helper_sqlite
typecheck clean; backend tests typecheck clean. Admin-ui coupon suites: 5
suites / 88 tests pass (detail 11, list 31, create 12, edit 10, form 24 —
counts include the new cases). Backend admin-coupon suite: 37/37 passes
(including ACOUP-15B).

View file

@ -83,9 +83,7 @@ export async function getCouponById(regionId: number, id: number): Promise<any |
return await db.query.coupons.findFirst({
where: and(
eq(coupons.id, id),
// Region admins can read their own coupons and the global ones (region_id
// NULL), matching getAll. Writes stay region-scoped.
or(eq(coupons.regionId, regionId), isNull(coupons.regionId))
eq(coupons.regionId, regionId)
),
with: {
creator: true,

View file

@ -2,11 +2,6 @@ superadmin ui:
username: superadmin
password: superadmiN123
admin ui:
username: shafi
password: shafI123
user ui: (use login with password, not otp)
username: 9676651496
password: meatfarmer@123