enh
This commit is contained in:
parent
7e86ff5a5d
commit
1b7b3b97e9
79 changed files with 226 additions and 6237 deletions
|
|
@ -47,7 +47,6 @@ Use these fixture names in the cases below.
|
|||
| `TAG_1` | `{id:1,tagName:'Chicken',tagDescription:'...',isDashboardTag:true,productIds:[2]}` |
|
||||
| `TAG_2` | `{id:2,tagName:'Veg',productIds:[5]}` |
|
||||
| `GROUP_1` | `{id:1,groupName:'Breakfast',description:'...',products:[{id:2},{id:5}]}` |
|
||||
| `SNIPPET_1` | `{id:1,snippetCode:'ABC123',slotId:1849,skuIds:[11],accessUrl:'https://...'}` |
|
||||
| `BANNER_1` | `{id:1,name:'Dash Banner',imageUrl:'https://...',skuIds:[11],isActive:true}` |
|
||||
|
||||
### Global reset rules
|
||||
|
|
@ -107,7 +106,6 @@ Use these fixture names in the cases below.
|
|||
| `dashboard/send-notifications/index.tsx` | `tests/pages/send-notifications.test.tsx` | getUsersForNotification, sendNotification |
|
||||
| `dashboard/user-management/index.tsx` | `tests/pages/user-management.test.tsx` | getAllUsers |
|
||||
| `dashboard/user-management/[id].tsx` | `tests/pages/user-detail.test.tsx` | getUserDetails, suspension, incidents |
|
||||
| `dashboard/vendor-snippets/index.tsx` | `tests/pages/vendor-snippets.test.tsx` | getAll, create, update, delete, orders |
|
||||
| `dashboard/customize-app/index.tsx` | `tests/pages/customize-app.test.tsx` | bounds/settings/region constants |
|
||||
| `dashboard/customize-app/popular-items.tsx` | `tests/pages/popular-items.test.tsx` | region constants, products summary |
|
||||
| `dashboard/customize-app/all-items-order.tsx` | `tests/pages/all-items-order.test.tsx` | region constants, products summary |
|
||||
|
|
@ -168,7 +166,7 @@ Use these fixture names in the cases below.
|
|||
| ADRAW-08 | happy | Products and Prices | correct routes |
|
||||
| ADRAW-09 | happy | Groupings/Banners/Slots | correct routes |
|
||||
| ADRAW-10 | happy | Complaints/Manage Orders/Coupons | correct routes |
|
||||
| ADRAW-11 | happy | Vendor/Stores/Users/Notifications | correct routes |
|
||||
| ADRAW-11 | happy | Stores/Users/Notifications | correct routes |
|
||||
| ADRAW-12 | happy | Logout | deletes JWT/staff, clears query cache, replaces login |
|
||||
| ADRAW-13 | edge | force logout event | logout runs |
|
||||
| ADRAW-14 | edge | header back on nested route | `router.back()` |
|
||||
|
|
@ -528,21 +526,15 @@ Use these fixture names in the cases below.
|
|||
| ASLOTADD-06 | error | create fails | alert/SlotForm error |
|
||||
| ASLOTEDIT-01 | happy | loading | spinner |
|
||||
| ASLOTEDIT-02 | edge | missing id | “Slot not found” |
|
||||
| ASLOTEDIT-03 | happy | prefill | delivery/freeze/active/products/snippets/groups |
|
||||
| ASLOTEDIT-03 | happy | prefill | delivery/freeze/active/products/groups |
|
||||
| ASLOTEDIT-04 | happy | update | mutation; back |
|
||||
| ASLOTEDIT-05 | error | update fails | alert |
|
||||
| ASLOTDET-01 | happy | loading | “Loading slot details...” |
|
||||
| ASLOTDET-02 | error | fail | “Error loading slot details” |
|
||||
| ASLOTDET-03 | edge | no vendor snippets | empty copy |
|
||||
| ASLOTDET-04 | edge | snippets | name, expiry, copy/share link |
|
||||
| ASLOTDET-05 | edge | products | names/count; empty copy |
|
||||
| ASLOTDET-06 | happy | Edit FAB | edit route |
|
||||
| ASLOTDET-07 | error | share fails | alert |
|
||||
| ASLOTDET-08 | edge | share success | clipboard/Share called |
|
||||
| ASLOTDET-09 | edge | snippet link missing | “No link available” |
|
||||
| ASLOTDET-10 | edge | products dialog | all products |
|
||||
|
||||
### 7.3 SlotForm and VendorSnippetForm
|
||||
### 7.3 SlotForm
|
||||
|
||||
| ID | Type | Case | Assert |
|
||||
| --- | --- | --- | --- |
|
||||
|
|
@ -550,20 +542,9 @@ Use these fixture names in the cases below.
|
|||
| ASLOTF-02 | error | missing delivery/freeze | validation/API error |
|
||||
| ASLOTF-03 | edge | invalid date order | current behavior |
|
||||
| ASLOTF-04 | happy | select products | SKU ids payload |
|
||||
| ASLOTF-05 | happy | add vendor snippet | name/SKUs/validTill/groupIds |
|
||||
| ASLOTF-06 | edge | remove snippet | removed |
|
||||
| ASLOTF-07 | edge | snippet requires SKUs | validation |
|
||||
| ASLOTF-08 | edge | group selection | group ids |
|
||||
| ASLOTF-09 | edge | create/update labels | current |
|
||||
| ASLOTF-10 | edge | submit pending | loading/disabled |
|
||||
| AVSF-01 | happy | render | name/code/slot/products/validTill/permanent |
|
||||
| AVSF-02 | error | empty code | validation |
|
||||
| AVSF-03 | error | no products | validation |
|
||||
| AVSF-04 | edge | permanent hides validTill | current |
|
||||
| AVSF-05 | edge | edit prefill | values |
|
||||
| AVSF-06 | edge | product selector groups | selection |
|
||||
| AVSF-07 | edge | submit payload | complete object |
|
||||
| AVSF-08 | edge | cancel | onClose |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -1070,56 +1051,6 @@ Use these fixture names in the cases below.
|
|||
|
||||
---
|
||||
|
||||
## 15. Vendor snippets
|
||||
|
||||
| ID | Type | Case | Assert |
|
||||
| --- | --- | --- | --- |
|
||||
| AVENDUI-01 | happy | loading | “Loading vendor snippets...” |
|
||||
| AVENDUI-02 | error | fail | “Error loading snippets” |
|
||||
| AVENDUI-03 | edge | empty | empty state + add |
|
||||
| AVENDUI-04 | happy | list | code/slot/validity/created/products/access URL |
|
||||
| AVENDUI-05 | edge | expired | expired styling |
|
||||
| AVENDUI-06 | edge | no access URL | copy error |
|
||||
| AVENDUI-07 | happy | copy link | clipboard; no URL error |
|
||||
| AVENDUI-08 | happy | products | +N opens dialog |
|
||||
| AVENDUI-09 | edge | view slot | current inert (`onPress={() => {}}`) |
|
||||
| AVENDUI-10 | happy | create | form dialog; create mutation; refetch |
|
||||
| AVENDUI-11 | happy | edit | form prefilled; update |
|
||||
| AVENDUI-12 | happy | delete | confirm; delete; refetch |
|
||||
| AVENDUI-13 | error | create/update/delete fails | alert |
|
||||
| AVENDUI-14 | happy | View Orders | fetch getOrdersBySnippet; dialog |
|
||||
| AVENDUI-15 | error | fetch orders fails | alert |
|
||||
| AVENDUI-16 | edge | no orders | empty view |
|
||||
| AVENDUI-17 | edge | logout/invalid snippet | no crash |
|
||||
| AVENDUI-18 | edge | mark data fetchers | refetch |
|
||||
| AVENDUI-19 | edge | menu | copy/edit/view/delete |
|
||||
| AVENDUI-20 | edge | no snippets | add action |
|
||||
|
||||
### SnippetOrdersView / SnippetMenu / VendorSnippetForm
|
||||
|
||||
| ID | Type | Case | Assert |
|
||||
| --- | --- | --- | --- |
|
||||
| ASOV-01 | happy | order card | id/customer/total/date/slot |
|
||||
| ASOV-02 | edge | products | matched/non-matched styling |
|
||||
| ASOV-03 | edge | subtotal/total | correct |
|
||||
| ASOV-04 | edge | empty | “No matching orders” |
|
||||
| ASOV-05 | edge | close | onClose |
|
||||
| ASMENU-01 | happy | menu | View Orders/Edit/Copy URL/Delete |
|
||||
| ASMENU-02 | error | no URL | alert |
|
||||
| ASMENU-03 | happy | copy | clipboard |
|
||||
| ASMENU-04 | happy | delete | confirm/callback |
|
||||
| ASMENU-05 | edge | disabled option | no action |
|
||||
| AVFORM-01 | happy | fields | code/slot/products/validTill/permanent |
|
||||
| AVFORM-02 | error | code empty | validation |
|
||||
| AVFORM-03 | error | no products | validation |
|
||||
| AVFORM-04 | edge | permanent | validTill hidden |
|
||||
| AVFORM-05 | edge | product selector | skuIds |
|
||||
| AVFORM-06 | edge | submit | payload |
|
||||
| AVFORM-07 | edge | edit prefill | payload |
|
||||
| AVFORM-08 | edge | cancel | onClose |
|
||||
|
||||
---
|
||||
|
||||
## 16. Customize app
|
||||
|
||||
### 16.1 Main screen
|
||||
|
|
@ -1196,7 +1127,7 @@ Use these fixture names in the cases below.
|
|||
|
||||
## 17. Shared components and services
|
||||
|
||||
### 17.1 OrderOptionsMenu, UserIncidentsView, ProductListDialog
|
||||
### 17.1 OrderOptionsMenu, UserIncidentsView
|
||||
|
||||
| ID | Type | Case | Assert |
|
||||
| --- | --- | --- | --- |
|
||||
|
|
@ -1206,9 +1137,6 @@ Use these fixture names in the cases below.
|
|||
| AUIV-01 | happy | loading/empty/list | |
|
||||
| AUIV-02 | happy | add incident | API/refetch |
|
||||
| AUIV-03 | error | fail | alert |
|
||||
| APLD-01 | happy | dialog open | products list |
|
||||
| APLD-02 | edge | close | onClose |
|
||||
| APLD-03 | edge | empty | empty copy |
|
||||
|
||||
### 17.2 useJWT / upload hook / trpc client / queryClient
|
||||
|
||||
|
|
@ -1258,14 +1186,12 @@ Use these fixture names in the cases below.
|
|||
7. `admin.order.getAll` swallows backend errors in the API; the UI may show an empty list.
|
||||
8. `admin.order.getOrderDetails`/`updateNotes`/`removeDeliveryCharge` can surface raw 500s.
|
||||
9. Send Notifications can show two error alerts (mutation `onError` plus catch).
|
||||
10. Vendor snippet “view slot” action is currently a no-op.
|
||||
11. Vendor packaging update and snippet order lookup are public API endpoints.
|
||||
12. User suspension toggle has no error alert on failure (only stops the spinner).
|
||||
13. Slot update API masks failures as “Unable to Update Slot”.
|
||||
14. Product create/update requires a `quantity` feature; the UI auto-adds it but allows edge cases.
|
||||
15. `ProductForm` validation for a missing feature value must be explicit; do not rely on the
|
||||
10.User suspension toggle has no error alert on failure (only stops the spinner).
|
||||
11.Slot update API masks failures as “Unable to Update Slot”.
|
||||
12.Product create/update requires a `quantity` feature; the UI auto-adds it but allows edge cases.
|
||||
13.`ProductForm` validation for a missing feature value must be explicit; do not rely on the
|
||||
unguarded `.trim()` in the duplicate-signature check.
|
||||
16. All cache-dependent pages must not assume immediate refresh; the admin API is immediate but
|
||||
14.All cache-dependent pages must not assume immediate refresh; the admin API is immediate but
|
||||
the user cache is eventual.
|
||||
|
||||
---
|
||||
|
|
@ -1340,11 +1266,6 @@ Use these fixture names in the cases below.
|
|||
| `admin.user.sendNotification` | ANOTIF-06..15 |
|
||||
| `admin.user.getUserIncidents` | AINC-01..09 |
|
||||
| `admin.user.addUserIncident` | AINC-04..09 |
|
||||
| `admin.vendorSnippets.getAll` | AVENDUI-01..20 |
|
||||
| `admin.vendorSnippets.create` | AVENDUI-10, AVFORM-01..08 |
|
||||
| `admin.vendorSnippets.update` | AVENDUI-11, AVFORM-01..08 |
|
||||
| `admin.vendorSnippets.delete` | AVENDUI-12 |
|
||||
| `admin.vendorSnippets.getOrdersBySnippet` | AVENDUI-14..16, ASOV-01..05 |
|
||||
| `admin.region.current` | ACUST-01..26 |
|
||||
| `admin.region.bounds` | ACUST-01..06 |
|
||||
| `admin.region.getBoundSettings` | ACUST-07..13 |
|
||||
|
|
@ -1363,9 +1284,9 @@ Use these fixture names in the cases below.
|
|||
|
||||
1. `tests/lib` — auth, JWT, tRPC client, upload hook.
|
||||
2. `tests/components` — ProductForm, CouponForm, BannerForm, TagForm, SlotForm, StoreForm,
|
||||
ProductGroupForm, VendorSnippetForm, OrderOptionsMenu, VariantStockDialog.
|
||||
ProductGroupForm, OrderOptionsMenu, VariantStockDialog.
|
||||
3. `tests/pages` — login/dashboard → products → stores/slots → coupons/banners/tags/groups →
|
||||
orders/delivery → complaints/users/notifications → vendor/customize.
|
||||
orders/delivery → complaints/users/notifications → customize.
|
||||
4. `tests/app` — root, index, drawer.
|
||||
5. Full `NODE_ENV=test bun run test` from `apps/admin-ui`.
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ const SCREEN_TITLES: Record<string, string> = {
|
|||
complaints: "Complaints",
|
||||
"manage-orders": "Manage Orders",
|
||||
coupons: "Coupons",
|
||||
"vendor-snippets": "Vendor Snippets",
|
||||
stores: "Stores",
|
||||
"user-management": "User Management",
|
||||
"send-notifications": "Send Notifications",
|
||||
|
|
@ -136,13 +135,6 @@ function CustomDrawerContent() {
|
|||
<MaterialIcons name="local-offer" size={size} color={color} />
|
||||
)}
|
||||
/>
|
||||
<DrawerItem
|
||||
label="Vendor Snippets"
|
||||
onPress={() => router.push("/(drawer)/dashboard/vendor-snippets" as any)}
|
||||
icon={({ color, size }) => (
|
||||
<MaterialIcons name="code" size={size} color={color} />
|
||||
)}
|
||||
/>
|
||||
<DrawerItem
|
||||
label="Stores"
|
||||
onPress={() => router.push("/(drawer)/dashboard/stores" as any)}
|
||||
|
|
|
|||
|
|
@ -36,7 +36,6 @@ export default function Layout() {
|
|||
name="user-management"
|
||||
options={{ title: "User Management" }}
|
||||
/>
|
||||
<Stack.Screen name="vendor-snippets" options={{ title: "Vendor Snippets" }} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import React, { useState } from 'react';
|
||||
import { View, ScrollView, TouchableOpacity, Alert, Share } from 'react-native';
|
||||
import { theme, AppContainer, MyText, tw, MyTouchableOpacity, BottomDialog } from 'common-ui';
|
||||
import React from 'react';
|
||||
import { View, ScrollView } from 'react-native';
|
||||
import { AppContainer, MyText, tw, MyTouchableOpacity } from 'common-ui';
|
||||
import { trpc } from '@/src/trpc-client';
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import dayjs from "dayjs";
|
||||
|
|
@ -17,11 +17,6 @@ export default function SlotDetails() {
|
|||
|
||||
const slot = slotData?.slot;
|
||||
const products = slot?.products || [];
|
||||
const vendorSnippets = slot?.vendorSnippets || [];
|
||||
|
||||
// Dialog state for snippet products
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [dialogProducts, setDialogProducts] = useState<any[]>([]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
|
|
@ -73,102 +68,7 @@ export default function SlotDetails() {
|
|||
</View>
|
||||
</View>
|
||||
|
||||
{/* Vendor Snippets Section */}
|
||||
<View style={tw`mb-8`}>
|
||||
<View style={tw`flex-row items-center justify-between mb-4`}>
|
||||
<MyText style={tw`text-lg font-bold text-gray-900`}>Vendor Snippets</MyText>
|
||||
<View style={tw`bg-gray-100 px-2 py-1 rounded-full`}>
|
||||
<MyText style={tw`text-xs font-medium text-gray-600`}>{vendorSnippets.length} snippets</MyText>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{vendorSnippets.length === 0 ? (
|
||||
<View style={tw`bg-gray-50 p-6 rounded-lg items-center`}>
|
||||
<MaterialIcons name="code" size={32} color="#9CA3AF" />
|
||||
<MyText style={tw`text-gray-500 text-center mt-2`}>No vendor snippets for this slot</MyText>
|
||||
</View>
|
||||
) : (
|
||||
<View style={tw`space-y-2`}>
|
||||
{vendorSnippets.map((snippet, index) => {
|
||||
const isExpired = snippet.validTill && dayjs(snippet.validTill).isBefore(dayjs());
|
||||
|
||||
return (
|
||||
<View key={snippet.id} style={tw`bg-gray-50 p-4 rounded-lg`}>
|
||||
<View style={tw`flex-row items-center justify-between mb-3`}>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`font-bold text-gray-900`} numberOfLines={1}>
|
||||
{snippet.snippetCode}
|
||||
</MyText>
|
||||
</View>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<View style={tw`px-2 py-1 rounded-full mr-2 ${isExpired ? 'bg-red-100' : 'bg-green-100'}`}>
|
||||
<MyText style={tw`text-xs font-medium ${isExpired ? 'text-red-700' : 'text-green-700'}`}>
|
||||
{isExpired ? 'Expired' : 'Active'}
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={tw`flex-row items-center justify-between`}>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<TouchableOpacity
|
||||
onPress={() => {
|
||||
const snippetProducts = products.filter(p => snippet.skuIds.includes(p.id));
|
||||
setDialogProducts(snippetProducts);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
style={tw`flex-row items-center mr-4`}
|
||||
>
|
||||
<MaterialIcons name="shopping-bag" size={14} color="#94A3B8" />
|
||||
<MyText style={tw`text-xs font-medium text-blue-600 ml-1 underline`}>
|
||||
{snippet.skuIds.length} products
|
||||
</MyText>
|
||||
</TouchableOpacity>
|
||||
|
||||
<MyTouchableOpacity
|
||||
onPress={async () => {
|
||||
try {
|
||||
await Share.share({
|
||||
message: snippet.accessUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'Failed to share link');
|
||||
}
|
||||
}}
|
||||
style={tw`flex-row items-center`}
|
||||
>
|
||||
<MaterialIcons name="link" size={14} color={theme.colors.brand500} />
|
||||
<MyText style={tw`text-xs font-medium text-brand600 ml-1`}>
|
||||
Share
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
|
||||
{snippet.validTill && (
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<MaterialIcons name="schedule" size={14} color="#94A3B8" />
|
||||
<MyText style={tw`text-xs font-medium text-gray-600 ml-1`}>
|
||||
Expires {dayjs(snippet.validTill).format('MMM DD')}
|
||||
</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{snippet.createdAt && (
|
||||
<View style={tw`mt-2 pt-2 border-t border-gray-200`}>
|
||||
<MyText style={tw`text-xs text-gray-500`}>
|
||||
Created {dayjs(snippet.createdAt).format('MMM DD, YYYY')}
|
||||
</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Products Section */}
|
||||
{/* Products Section */}
|
||||
<View style={tw`mb-8`}>
|
||||
<View style={tw`flex-row items-center justify-between mb-4`}>
|
||||
<MyText style={tw`text-lg font-bold text-gray-900`}>Products</MyText>
|
||||
|
|
@ -213,33 +113,6 @@ export default function SlotDetails() {
|
|||
</LinearGradient>
|
||||
</MyTouchableOpacity>
|
||||
|
||||
<BottomDialog open={dialogOpen} onClose={() => setDialogOpen(false)}>
|
||||
<View style={tw`py-4`}>
|
||||
<MyText style={tw`text-lg font-semibold mb-4 text-center`}>Snippet Products</MyText>
|
||||
<ScrollView style={tw`max-h-80`}>
|
||||
{dialogProducts.length === 0 ? (
|
||||
<View style={tw`py-8 px-4 items-center`}>
|
||||
<MyText style={tw`text-gray-500 text-center`}>
|
||||
No products found for this snippet
|
||||
</MyText>
|
||||
</View>
|
||||
) : (
|
||||
dialogProducts.map(product => (
|
||||
<View key={product.id} style={tw`py-3 px-4 border-b border-gray-100`}>
|
||||
<MyText style={tw`text-base font-medium text-gray-900`}>
|
||||
{product.name}
|
||||
</MyText>
|
||||
{product.shortDescription && (
|
||||
<MyText style={tw`text-sm text-gray-600 mt-1`}>
|
||||
{product.shortDescription}
|
||||
</MyText>
|
||||
)}
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</BottomDialog>
|
||||
</View>
|
||||
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,9 +0,0 @@
|
|||
import { Stack } from 'expo-router';
|
||||
|
||||
export default function Layout() {
|
||||
return (
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
<Stack.Screen name="index" options={{ title: 'Vendor Snippets' }} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,442 +0,0 @@
|
|||
import React, { useState } from "react";
|
||||
import {
|
||||
View,
|
||||
ScrollView,
|
||||
TouchableOpacity,
|
||||
Alert,
|
||||
Dimensions,
|
||||
Share,
|
||||
} from "react-native";
|
||||
import {
|
||||
theme,
|
||||
AppContainer,
|
||||
MyText,
|
||||
tw,
|
||||
useManualRefresh,
|
||||
useMarkDataFetchers,
|
||||
MyTouchableOpacity,
|
||||
} from "common-ui";
|
||||
import { trpc, trpcClient } from "../../../../src/trpc-client";
|
||||
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import dayjs from "dayjs";
|
||||
import { LinearGradient } from "expo-linear-gradient";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
import VendorSnippetForm from "../../../../components/VendorSnippetForm";
|
||||
import SnippetOrdersView from "../../../../components/SnippetOrdersView";
|
||||
import { SnippetMenu } from "../../../../components/SnippetMenu";
|
||||
import { ProductListDialog } from "../../../../components/ProductListDialog";
|
||||
import {
|
||||
VendorSnippet,
|
||||
VendorSnippetProduct,
|
||||
VendorSnippetForm as VendorSnippetFormType,
|
||||
} from "../../../../types/vendor-snippets";
|
||||
|
||||
const SnippetItem = ({
|
||||
snippet,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onViewOrders,
|
||||
onViewProducts,
|
||||
index,
|
||||
}: {
|
||||
snippet: VendorSnippet;
|
||||
onEdit: (snippet: VendorSnippet) => void;
|
||||
onDelete: (id: number) => void;
|
||||
onViewOrders: (snippetCode: string) => void;
|
||||
onViewProducts: (products: VendorSnippetProduct[]) => void;
|
||||
index: number;
|
||||
}) => {
|
||||
|
||||
const isExpired =
|
||||
snippet.validTill && dayjs(snippet.validTill).isBefore(dayjs());
|
||||
|
||||
const handleCopyLink = async () => {
|
||||
try {
|
||||
if (!snippet.accessUrl) {
|
||||
Alert.alert("Error", "No link available");
|
||||
return;
|
||||
}
|
||||
await Share.share({
|
||||
message: snippet.accessUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
Alert.alert("Error", "Failed to share link");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={tw``}>
|
||||
<View style={tw`p-6`}>
|
||||
{/* Top Header: ID & Status */}
|
||||
<View style={tw`flex-row justify-between items-start mb-6`}>
|
||||
<View style={tw`flex-row items-center flex-1`}>
|
||||
<View
|
||||
style={tw`w-12 h-12 rounded-2xl bg-brand50 items-center justify-center mr-4`}
|
||||
>
|
||||
<MaterialIcons
|
||||
name="fingerprint"
|
||||
size={24}
|
||||
color={theme.colors.brand600}
|
||||
/>
|
||||
</View>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText
|
||||
style={tw`text-slate-400 text-[10px] font-black uppercase tracking-widest`}
|
||||
>
|
||||
Identifier
|
||||
</MyText>
|
||||
<MyText
|
||||
style={tw`text-xl font-black text-slate-900`}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{snippet.snippetCode}
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<View
|
||||
style={[
|
||||
tw`px-3 py-1.5 rounded-full flex-row items-center mr-2`,
|
||||
{ backgroundColor: isExpired ? "#FFF1F2" : "#F0FDF4" },
|
||||
]}
|
||||
>
|
||||
<View
|
||||
style={[
|
||||
tw`w-1.5 h-1.5 rounded-full mr-2`,
|
||||
{ backgroundColor: isExpired ? "#E11D48" : "#10B981" },
|
||||
]}
|
||||
/>
|
||||
<MyText
|
||||
style={[
|
||||
tw`text-[10px] font-black uppercase tracking-tighter`,
|
||||
{ color: isExpired ? "#E11D48" : "#10B981" },
|
||||
]}
|
||||
>
|
||||
{isExpired ? "Expired" : "Active"}
|
||||
</MyText>
|
||||
</View>
|
||||
<SnippetMenu
|
||||
snippet={snippet}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onViewOrders={onViewOrders}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Middle: Delivery Banner */}
|
||||
<View
|
||||
style={tw`bg-slate-50 rounded-3xl p-4 flex-row items-center mb-6 border border-slate-100`}
|
||||
>
|
||||
<View
|
||||
style={tw`bg-white w-10 h-10 rounded-2xl items-center justify-center shadow-sm`}
|
||||
>
|
||||
<MaterialIcons name="event-available" size={20} color="#64748B" />
|
||||
</View>
|
||||
<View style={tw`ml-4 flex-1`}>
|
||||
{snippet.isPermanent ? (
|
||||
<>
|
||||
<MyText style={tw`text-slate-900 font-extrabold text-sm`}>
|
||||
Permanent
|
||||
</MyText>
|
||||
<MyText style={tw`text-slate-500 text-[10px] font-bold uppercase`}>
|
||||
Always Active
|
||||
</MyText>
|
||||
</>
|
||||
) : snippet.slot?.deliveryTime ? (
|
||||
<>
|
||||
<MyText style={tw`text-slate-900 font-extrabold text-sm`}>
|
||||
{dayjs(snippet.slot.deliveryTime).format("ddd, MMM DD")}
|
||||
</MyText>
|
||||
<MyText style={tw`text-slate-500 text-[10px] font-bold uppercase`}>
|
||||
Time: {dayjs(snippet.slot.deliveryTime).format("hh:mm A")}
|
||||
</MyText>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<MyText style={tw`text-slate-900 font-extrabold text-sm`}>
|
||||
Schedule Pending
|
||||
</MyText>
|
||||
<MyText style={tw`text-slate-500 text-[10px] font-bold uppercase`}>
|
||||
N/A
|
||||
</MyText>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
{snippet.validTill && (
|
||||
<View style={tw`items-end`}>
|
||||
<MyText style={tw`text-slate-400 text-[9px] font-bold uppercase`}>
|
||||
Expires
|
||||
</MyText>
|
||||
<MyText
|
||||
style={[
|
||||
tw`text-xs font-black`,
|
||||
{ color: isExpired ? "#E11D48" : "#64748B" },
|
||||
]}
|
||||
>
|
||||
{dayjs(snippet.validTill).format("MMM DD")}
|
||||
</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Stats & Actions */}
|
||||
<View style={tw`flex-row items-center justify-between`}>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<MyTouchableOpacity
|
||||
onPress={() => onViewProducts(snippet.products)}
|
||||
style={tw`flex-row items-center mr-4`}
|
||||
>
|
||||
<MaterialIcons name="shopping-bag" size={14} color="#94A3B8" />
|
||||
<MyText style={tw`text-xs font-bold text-slate-500 ml-1.5`}>
|
||||
{snippet.skuIds.length} Items
|
||||
</MyText>
|
||||
<MaterialIcons name="chevron-right" size={14} color="#94A3B8" />
|
||||
</MyTouchableOpacity>
|
||||
<MyTouchableOpacity
|
||||
onPress={handleCopyLink}
|
||||
style={tw`flex-row items-center`}
|
||||
>
|
||||
<MaterialIcons
|
||||
name="link"
|
||||
size={16}
|
||||
color={theme.colors.brand500}
|
||||
/>
|
||||
<MyText style={tw`text-xs font-black text-brand600 ml-1`}>
|
||||
Share
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
|
||||
<MyTouchableOpacity
|
||||
// onPress={() => router.push(`/(drawer)/dashboard/slots/slot-details?slotId=${snippet.slotId}`)}
|
||||
onPress={() => {}}
|
||||
activeOpacity={0.7}
|
||||
style={tw`flex-row items-center`}
|
||||
>
|
||||
<MyText
|
||||
style={tw`text-xs font-black text-slate-900 uppercase tracking-widest`}
|
||||
>
|
||||
View Slot
|
||||
</MyText>
|
||||
<MaterialIcons name="chevron-right" size={16} color="#000" />
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
export default function VendorSnippets() {
|
||||
// const { data: snippets, isLoading, error, refetch } = useVendorSnippets();
|
||||
const {
|
||||
data: snippets,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = trpc.admin.vendorSnippets.getAll.useQuery();
|
||||
|
||||
const createSnippet = trpc.admin.vendorSnippets.create.useMutation();
|
||||
const updateSnippet = trpc.admin.vendorSnippets.update.useMutation();
|
||||
const deleteSnippet = trpc.admin.vendorSnippets.delete.useMutation();
|
||||
// const createSnippet = useCreateVendorSnippet();
|
||||
// const updateSnippet = useUpdateVendorSnippet();
|
||||
// const deleteSnippet = useDeleteVendorSnippet();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [editingSnippet, setEditingSnippet] =
|
||||
useState<VendorSnippetFormType | null>(null);
|
||||
const [showOrdersView, setShowOrdersView] = useState(false);
|
||||
const [ordersData, setOrdersData] = useState<any>(null);
|
||||
const [showProductList, setShowProductList] = useState(false);
|
||||
const [selectedProducts, setSelectedProducts] = useState<VendorSnippetProduct[] | null>(null);
|
||||
|
||||
useManualRefresh(refetch);
|
||||
|
||||
useMarkDataFetchers(() => {
|
||||
refetch();
|
||||
});
|
||||
|
||||
const handleCreate = () => {
|
||||
setShowCreateForm(true);
|
||||
setEditingSnippet(null);
|
||||
};
|
||||
|
||||
const handleViewProducts = (products: VendorSnippetProduct[]) => {
|
||||
setSelectedProducts(products);
|
||||
setShowProductList(true);
|
||||
};
|
||||
|
||||
const handleEdit = (snippet: VendorSnippet) => {
|
||||
// Convert to match the form's expected type
|
||||
const formSnippet: VendorSnippetFormType = {
|
||||
id: snippet.id,
|
||||
snippetCode: snippet.snippetCode,
|
||||
slotId: snippet.slotId || 0, // Convert null to number for form
|
||||
isPermanent: snippet.isPermanent,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill,
|
||||
createdAt: snippet.createdAt,
|
||||
};
|
||||
setEditingSnippet(formSnippet);
|
||||
setShowCreateForm(true);
|
||||
};
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
deleteSnippet.mutate(
|
||||
{ id },
|
||||
{
|
||||
onSuccess: () => {
|
||||
refetch();
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleViewOrders = async (snippetCode: string) => {
|
||||
try {
|
||||
const result =
|
||||
await trpcClient.admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode,
|
||||
});
|
||||
if (result.success) {
|
||||
setOrdersData({
|
||||
orders: result.data,
|
||||
snippetCode: snippetCode,
|
||||
});
|
||||
setShowOrdersView(true);
|
||||
} else {
|
||||
Alert.alert("Error", "Failed to fetch orders");
|
||||
}
|
||||
} catch (error: any) {
|
||||
Alert.alert("Error", error.message || "Failed to fetch orders");
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<AppContainer>
|
||||
<View style={tw`flex-1 justify-center items-center`}>
|
||||
<MyText style={tw`text-gray-600`}>Loading vendor snippets...</MyText>
|
||||
</View>
|
||||
</AppContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<AppContainer>
|
||||
<View style={tw`flex-1 justify-center items-center`}>
|
||||
<MyText style={tw`text-red-600`}>Error loading snippets</MyText>
|
||||
</View>
|
||||
</AppContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (showOrdersView && ordersData) {
|
||||
return (
|
||||
<SnippetOrdersView
|
||||
orders={ordersData.orders}
|
||||
snippetCode={ordersData.snippetCode}
|
||||
onClose={() => {
|
||||
setShowOrdersView(false);
|
||||
setOrdersData(null);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (showCreateForm) {
|
||||
return (
|
||||
<VendorSnippetForm
|
||||
snippet={editingSnippet}
|
||||
onClose={() => {
|
||||
setShowCreateForm(false);
|
||||
setEditingSnippet(null);
|
||||
}}
|
||||
onSuccess={() => {
|
||||
setShowCreateForm(false);
|
||||
setEditingSnippet(null);
|
||||
refetch();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppContainer>
|
||||
<View style={tw`flex-1 bg-white h-full`}>
|
||||
<ScrollView
|
||||
style={tw`flex-1`}
|
||||
contentContainerStyle={tw` pt-2 pb-32`}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{snippets && snippets.length === 0 ? (
|
||||
<View style={tw`flex-1 justify-center items-center py-20`}>
|
||||
<View
|
||||
style={tw`w-24 h-24 bg-slate-50 rounded-full items-center justify-center mb-6`}
|
||||
>
|
||||
<Ionicons name="code-working" size={48} color="#94A3B8" />
|
||||
</View>
|
||||
<MyText
|
||||
style={tw`text-slate-900 text-xl font-black tracking-tight`}
|
||||
>
|
||||
No Snippets Yet
|
||||
</MyText>
|
||||
<MyText
|
||||
style={tw`text-slate-500 text-center mt-2 font-medium px-8`}
|
||||
>
|
||||
Start by creating your first vendor identifier using the
|
||||
button below.
|
||||
</MyText>
|
||||
</View>
|
||||
) : (
|
||||
snippets?.map((snippet, index) => (
|
||||
<React.Fragment key={snippet.id}>
|
||||
<SnippetItem
|
||||
snippet={snippet}
|
||||
index={index}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onViewOrders={handleViewOrders}
|
||||
onViewProducts={handleViewProducts}
|
||||
/>
|
||||
{index < snippets.length - 1 && (
|
||||
<View style={tw`h-px bg-slate-200 w-full`} />
|
||||
)}
|
||||
</React.Fragment>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
|
||||
{/* Global Floating Action Button - Fixed Position */}
|
||||
</View>
|
||||
</AppContainer>
|
||||
<MyTouchableOpacity
|
||||
onPress={handleCreate}
|
||||
activeOpacity={0.95}
|
||||
style={tw`absolute bottom-8 right-6 shadow-2xl z-50`}
|
||||
>
|
||||
<LinearGradient
|
||||
colors={["#1570EF", "#194185"]}
|
||||
start={{ x: 0, y: 0 }}
|
||||
end={{ x: 1, y: 1 }}
|
||||
style={tw`w-16 h-16 rounded-[24px] items-center justify-center shadow-lg shadow-brand300`}
|
||||
>
|
||||
<MaterialIcons name="add" size={32} color="white" />
|
||||
</LinearGradient>
|
||||
</MyTouchableOpacity>
|
||||
<ProductListDialog
|
||||
open={showProductList}
|
||||
onClose={() => setShowProductList(false)}
|
||||
products={selectedProducts || []}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
import React from 'react';
|
||||
import { View, ScrollView } from 'react-native';
|
||||
import { BottomDialog, MyText, tw } from 'common-ui';
|
||||
import type { IdName } from '@packages/shared';
|
||||
|
||||
type VendorSnippetProduct = IdName;
|
||||
|
||||
interface ProductListDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
products: VendorSnippetProduct[];
|
||||
}
|
||||
|
||||
export const ProductListDialog: React.FC<ProductListDialogProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
products,
|
||||
}) => {
|
||||
return (
|
||||
<BottomDialog open={open} onClose={onClose}>
|
||||
<View style={tw`pt-4 pb-8`}>
|
||||
<MyText style={tw`text-lg font-bold mb-4 text-slate-900`}>
|
||||
Products ({products.length})
|
||||
</MyText>
|
||||
<ScrollView style={{ maxHeight: 400 }}>
|
||||
{products.map((product, index) => (
|
||||
<View
|
||||
key={product.id}
|
||||
style={[
|
||||
tw`py-3 border-b border-slate-100`,
|
||||
index === products.length - 1 && tw`border-b-0`,
|
||||
]}
|
||||
>
|
||||
<MyText style={tw`text-sm text-slate-800 font-medium`}>
|
||||
{product.name}
|
||||
</MyText>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</BottomDialog>
|
||||
);
|
||||
};
|
||||
|
|
@ -1,15 +1,11 @@
|
|||
import React, { useState } from 'react';
|
||||
import type { SlotSnippetInput } from '@packages/shared'
|
||||
import { View, Text, TouchableOpacity, Alert, Keyboard } from 'react-native';
|
||||
import { Formik, FieldArray } from 'formik';
|
||||
import { Formik } from 'formik';
|
||||
import DateTimePickerMod from 'common-ui/src/components/date-time-picker';
|
||||
import { tw, MyTextInput, BottomDialog } from 'common-ui';
|
||||
import { trpc } from '../src/trpc-client';
|
||||
import ProductsSelector from '../components/ProductsSelector';
|
||||
|
||||
// Snippet form row — single source in @packages/shared (complete payload)
|
||||
type VendorSnippet = SlotSnippetInput
|
||||
|
||||
// __DEV__ test hook: parse a YYYY-MM-DD + HH:MM wall-clock as IST (UTC+5:30).
|
||||
// Returns null for bad shapes, out-of-range fields, or impossible dates.
|
||||
const IST_OFFSET_MS = (5 * 60 + 30) * 60 * 1000
|
||||
|
|
@ -62,19 +58,11 @@ export default function SlotForm({
|
|||
{ enabled: !!slotId }
|
||||
);
|
||||
|
||||
const vendorSnippetsFromSlot = (slotData?.slot?.vendorSnippets || []).map((snippet: any) => ({
|
||||
name: snippet.name || '',
|
||||
groupIds: snippet.groupIds || [],
|
||||
skuIds: snippet.skuIds || [],
|
||||
validTill: snippet.validTill || null,
|
||||
})) as VendorSnippet[];
|
||||
|
||||
const initialValues = {
|
||||
deliveryTime: initialDeliveryTime || (slotData?.slot?.deliveryTime ? new Date(slotData.slot.deliveryTime) : null),
|
||||
freezeTime: initialFreezeTime || (slotData?.slot?.freezeTime ? new Date(slotData.slot.freezeTime) : null),
|
||||
selectedGroupIds: initialGroupIds.length > 0 ? initialGroupIds : (slotData?.slot?.groupIds || []),
|
||||
selectedSkuIds: initialProductIds.length > 0 ? initialProductIds : (slotData?.slot?.products?.map((p: any) => p.id) || []),
|
||||
vendorSnippetList: vendorSnippetsFromSlot,
|
||||
};
|
||||
|
||||
const { mutate: createSlot, isPending: isCreating } = trpc.admin.slots.createSlot.useMutation();
|
||||
|
|
@ -121,11 +109,6 @@ export default function SlotForm({
|
|||
isActive: initialIsActive,
|
||||
groupIds: values.selectedGroupIds,
|
||||
skuIds: values.selectedSkuIds,
|
||||
vendorSnippets: values.vendorSnippetList.map((snippet: VendorSnippet) => ({
|
||||
name: snippet.name,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill ?? undefined,
|
||||
})),
|
||||
};
|
||||
|
||||
if (isEditMode && slotId) {
|
||||
|
|
@ -214,58 +197,6 @@ export default function SlotForm({
|
|||
/>
|
||||
</View>
|
||||
|
||||
{/* Vendor Snippets */}
|
||||
<FieldArray name="vendorSnippetList">
|
||||
{({ push, remove }) => (
|
||||
<View style={tw`mb-4`}>
|
||||
<Text style={tw`text-lg font-semibold mb-4`}>Vendor Snippets</Text>
|
||||
{values.vendorSnippetList.map((snippet: VendorSnippet, index: number) => (
|
||||
<View key={index} style={tw`bg-gray-50 p-4 rounded-lg mb-4`}>
|
||||
<View style={tw`mb-4`}>
|
||||
<MyTextInput
|
||||
topLabel="Snippet Name *"
|
||||
placeholder="Enter snippet name"
|
||||
value={snippet.name}
|
||||
onChangeText={(text) => setFieldValue(`vendorSnippetList.${index}.name`, text)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={tw`mb-4`}>
|
||||
<ProductsSelector
|
||||
value={snippet.skuIds || []}
|
||||
onChange={(newSkuIds) => setFieldValue(`vendorSnippetList.${index}.skuIds`, newSkuIds)}
|
||||
groups={mappedGroups.filter(group =>
|
||||
values.selectedGroupIds.includes(group.id)
|
||||
).map(group => ({
|
||||
...group,
|
||||
products: group.products.filter((p: any) => values.selectedSkuIds.includes(p.id))
|
||||
}))}
|
||||
selectedGroupIds={snippet.groupIds || []}
|
||||
onGroupChange={(newGroupIds) => setFieldValue(`vendorSnippetList.${index}.groupIds`, newGroupIds)}
|
||||
label="Select Products"
|
||||
testID="snippet-products-selector"
|
||||
placeholder="Select products for snippet"
|
||||
isDisabled={(sku) => !values.selectedSkuIds.includes(sku.id)}
|
||||
/>
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
onPress={() => remove(index)}
|
||||
style={tw`bg-red-500 px-4 py-2 rounded-lg self-end`}
|
||||
>
|
||||
<Text style={tw`text-white font-medium`}>Remove Snippet</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
))}
|
||||
<TouchableOpacity
|
||||
onPress={() => push({ name: '', groupIds: [], skuIds: [], validTill: '' })}
|
||||
style={tw`bg-blue-500 px-4 py-3 rounded-lg items-center`}
|
||||
>
|
||||
<Text style={tw`text-white font-medium`}>Add Vendor Snippet</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
</FieldArray>
|
||||
|
||||
<TouchableOpacity
|
||||
testID="create-slot-button"
|
||||
accessibilityLabel="create-slot-button"
|
||||
|
|
|
|||
|
|
@ -1,146 +0,0 @@
|
|||
import React, { useState } from 'react';
|
||||
import { View, TouchableOpacity, Alert, Clipboard } from 'react-native';
|
||||
import { Entypo } from '@expo/vector-icons';
|
||||
import { MyText, tw, BottomDialog } from 'common-ui';
|
||||
import { SuccessToast } from '../services/toaster';
|
||||
import { VendorSnippet } from '../types/vendor-snippets';
|
||||
|
||||
export interface SnippetMenuOption {
|
||||
title: string;
|
||||
icon: keyof typeof Entypo.glyphMap;
|
||||
onPress: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface SnippetMenuProps {
|
||||
snippet: VendorSnippet;
|
||||
onEdit: (snippet: VendorSnippet) => void;
|
||||
onDelete: (id: number) => void;
|
||||
onViewOrders: (snippetCode: string) => void;
|
||||
triggerStyle?: any;
|
||||
iconSize?: number;
|
||||
iconColor?: string;
|
||||
}
|
||||
|
||||
export const SnippetMenu: React.FC<SnippetMenuProps> = ({
|
||||
snippet,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onViewOrders,
|
||||
triggerStyle = tw`p-2 rounded-full bg-gray-50`,
|
||||
iconSize = 16,
|
||||
iconColor = '#6B7280',
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const handleOpenMenu = () => {
|
||||
setIsOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseMenu = () => {
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
const handleViewOrders = () => {
|
||||
setIsOpen(false);
|
||||
onViewOrders(snippet.snippetCode);
|
||||
};
|
||||
|
||||
const handleEdit = () => {
|
||||
setIsOpen(false);
|
||||
onEdit(snippet);
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
setIsOpen(false);
|
||||
Alert.alert(
|
||||
'Delete Snippet',
|
||||
'Are you sure you want to delete this vendor snippet?',
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{
|
||||
text: 'Delete',
|
||||
style: 'destructive',
|
||||
onPress: () => onDelete(snippet.id),
|
||||
},
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
const handleCopyUrl = async () => {
|
||||
setIsOpen(false);
|
||||
if (!snippet.accessUrl) {
|
||||
Alert.alert('Error', 'No URL available to copy');
|
||||
return;
|
||||
}
|
||||
await Clipboard.setString(snippet.accessUrl);
|
||||
SuccessToast('URL copied to clipboard');
|
||||
};
|
||||
|
||||
const options: SnippetMenuOption[] = [
|
||||
{
|
||||
title: 'View Orders',
|
||||
icon: 'eye',
|
||||
onPress: handleViewOrders,
|
||||
},
|
||||
{
|
||||
title: 'Edit',
|
||||
icon: 'edit',
|
||||
onPress: handleEdit,
|
||||
},
|
||||
{
|
||||
title: 'Copy URL',
|
||||
icon: 'link',
|
||||
onPress: handleCopyUrl,
|
||||
},
|
||||
{
|
||||
title: 'Delete',
|
||||
icon: 'trash',
|
||||
onPress: handleDelete,
|
||||
},
|
||||
];
|
||||
|
||||
const handleOptionPress = (option: SnippetMenuOption) => {
|
||||
if (option.disabled) return;
|
||||
option.onPress();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Menu Trigger */}
|
||||
<TouchableOpacity
|
||||
onPress={handleOpenMenu}
|
||||
style={triggerStyle}
|
||||
>
|
||||
<Entypo name="dots-three-vertical" size={iconSize} color={iconColor} />
|
||||
</TouchableOpacity>
|
||||
|
||||
{/* Menu Dialog */}
|
||||
<BottomDialog open={isOpen} onClose={handleCloseMenu}>
|
||||
<View style={tw`p-6`}>
|
||||
<MyText style={tw`text-lg font-bold text-gray-800 mb-6`}>
|
||||
Snippet Options
|
||||
</MyText>
|
||||
|
||||
{options.map((option, index) => (
|
||||
<TouchableOpacity
|
||||
key={`${snippet.id}-${index}`}
|
||||
style={tw`flex-row items-center p-4 bg-gray-50 rounded-lg ${index < options.length - 1 ? 'mb-3' : ''} ${option.disabled ? 'opacity-50' : ''}`}
|
||||
onPress={() => handleOptionPress(option)}
|
||||
disabled={option.disabled}
|
||||
>
|
||||
<Entypo
|
||||
name={option.icon}
|
||||
size={20}
|
||||
color={option.disabled ? '#9CA3AF' : '#6B7280'}
|
||||
/>
|
||||
<MyText style={tw`text-gray-800 font-medium ml-3 ${option.disabled ? 'text-gray-400' : ''}`}>
|
||||
{option.title}
|
||||
</MyText>
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
</BottomDialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
|
@ -1,155 +0,0 @@
|
|||
import React from 'react';
|
||||
import { View, ScrollView, TouchableOpacity } from 'react-native';
|
||||
import { MyText, tw, AppContainer } from 'common-ui';
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import type {
|
||||
AdminVendorSnippetOrderProduct,
|
||||
AdminVendorSnippetOrderSummary as SharedSnippetOrderSummary,
|
||||
} from '@packages/shared';
|
||||
|
||||
// Line item + order summary anchored to the shared vendor-order contract
|
||||
// (string totalAmount + any[] sequence at this view layer)
|
||||
type OrderProduct = Pick<
|
||||
AdminVendorSnippetOrderProduct,
|
||||
'productId' | 'productName' | 'quantity' | 'price' | 'unit' | 'subtotal'
|
||||
>
|
||||
|
||||
type SnippetOrder = Omit<SharedSnippetOrderSummary, 'totalAmount' | 'slotInfo' | 'products'> & {
|
||||
totalAmount: string
|
||||
slotInfo: {
|
||||
time: string;
|
||||
sequence: any[];
|
||||
} | null;
|
||||
products: OrderProduct[];
|
||||
}
|
||||
|
||||
interface SnippetOrdersViewProps {
|
||||
orders: SnippetOrder[];
|
||||
snippetCode: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const OrderCard: React.FC<{ order: SnippetOrder; index: number }> = ({ order, index }) => {
|
||||
const orderDate = new Date(order.orderDate);
|
||||
const slotTime = order.slotInfo ? new Date(order.slotInfo.time) : null;
|
||||
|
||||
return (
|
||||
<View style={tw`py-6`}>
|
||||
{/* Order Header */}
|
||||
<View style={tw`flex-row justify-between items-start mb-3`}>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`font-bold text-gray-800 text-lg`}>{order.orderId}</MyText>
|
||||
<MyText style={tw`text-sm text-gray-600`}>{order.customerName}</MyText>
|
||||
</View>
|
||||
<View style={tw`items-end`}>
|
||||
<MyText style={tw`font-bold text-green-600`}>₹{order.totalAmount}</MyText>
|
||||
<MyText style={tw`text-xs text-gray-500`}>
|
||||
{orderDate.toLocaleDateString()}
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Slot Info */}
|
||||
{slotTime && (
|
||||
<View style={tw`mb-3 p-2 bg-blue-50 rounded-lg`}>
|
||||
<MyText style={tw`text-sm text-blue-800 font-medium`}>
|
||||
Delivery: {slotTime.toLocaleString()}
|
||||
</MyText>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Products */}
|
||||
<View style={tw`mb-3`}>
|
||||
<MyText style={tw`text-sm font-semibold text-gray-700 mb-2`}>Products:</MyText>
|
||||
{order.products.map((product, index) => {
|
||||
const isMatched = order.matchedProducts.includes(product.productId);
|
||||
return (
|
||||
<View
|
||||
key={index}
|
||||
style={tw`flex-row justify-between items-center py-1 ${isMatched ? 'bg-yellow-50 px-2 rounded' : ''}`}
|
||||
>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`text-sm ${isMatched ? 'font-semibold text-yellow-800' : 'text-gray-700'}`}>
|
||||
{product.productName}
|
||||
{isMatched && ' ⭐'}
|
||||
</MyText>
|
||||
<MyText style={tw`text-xs text-gray-500`}>
|
||||
{product.quantity} {product.unit} × ₹{product.price}
|
||||
</MyText>
|
||||
</View>
|
||||
<MyText style={tw`text-sm font-medium ${isMatched ? 'text-yellow-800' : 'text-gray-700'}`}>
|
||||
₹{product.subtotal.toFixed(2)}
|
||||
</MyText>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
{/* Matched Products Summary */}
|
||||
<View style={tw`p-2 bg-yellow-50 rounded-lg`}>
|
||||
<MyText style={tw`text-xs text-yellow-700`}>
|
||||
Matched {order.matchedProducts.length} product(s) from snippet "{order.snippetCode}"
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
const SnippetOrdersView: React.FC<SnippetOrdersViewProps> = ({
|
||||
orders,
|
||||
snippetCode,
|
||||
onClose,
|
||||
}) => {
|
||||
const totalOrders = orders.length;
|
||||
const totalRevenue = orders.reduce((sum, order) => sum + parseFloat(order.totalAmount), 0);
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<View style={tw`flex-1 bg-gray-50`}>
|
||||
{/* Header */}
|
||||
<View style={tw`px-6 py-4 bg-white border-b border-gray-200`}>
|
||||
<View style={tw`flex-row justify-between items-center`}>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`text-xl font-bold text-gray-800`}>Orders for "{snippetCode}"</MyText>
|
||||
<MyText style={tw`text-gray-600 mt-1`}>
|
||||
{totalOrders} order{totalOrders !== 1 ? 's' : ''} • Total: ₹{totalRevenue.toFixed(2)}
|
||||
</MyText>
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
onPress={onClose}
|
||||
style={tw`p-2`}
|
||||
>
|
||||
<MyText style={tw`text-gray-500 text-lg`}>✕</MyText>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Orders List */}
|
||||
<ScrollView style={tw`flex-1 px-6`} showsVerticalScrollIndicator={false}>
|
||||
{orders.length === 0 ? (
|
||||
<View style={tw`flex-1 justify-center items-center py-12`}>
|
||||
<MaterialIcons name="shopping-cart" size={64} color="#D1D5DB" />
|
||||
<MyText style={tw`text-gray-500 text-lg font-semibold mt-4`}>No matching orders</MyText>
|
||||
<MyText style={tw`text-gray-400 text-center mt-2`}>
|
||||
No orders found that match this snippet's criteria
|
||||
</MyText>
|
||||
</View>
|
||||
) : (
|
||||
<View style={tw`py-4`}>
|
||||
{orders.map((order, index) => (
|
||||
<React.Fragment key={index}>
|
||||
<OrderCard order={order} index={index} />
|
||||
{index < orders.length - 1 && (
|
||||
<View style={tw`h-px bg-slate-200 w-full`} />
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</AppContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default SnippetOrdersView;
|
||||
|
|
@ -1,238 +0,0 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import { View, TouchableOpacity, Alert, ScrollView } from 'react-native';
|
||||
import { useFormik } from 'formik';
|
||||
import { MyText, tw, DatePicker, MyTextInput } from 'common-ui';
|
||||
import BottomDropdown from 'common-ui/src/components/bottom-dropdown';
|
||||
import ProductsSelector from '../components/ProductsSelector';
|
||||
import { trpc } from '../src/trpc-client';
|
||||
import { useStaffAuth } from '@/components/context/staff-auth-context';
|
||||
import { VendorSnippetForm as VendorSnippetFormType, VendorSnippet } from '../types/vendor-snippets';
|
||||
|
||||
interface VendorSnippetFormProps {
|
||||
snippet?: VendorSnippetFormType | null;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
showIsPermanentCheckbox?: boolean;
|
||||
}
|
||||
|
||||
const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
|
||||
snippet,
|
||||
onClose,
|
||||
onSuccess,
|
||||
showIsPermanentCheckbox = false,
|
||||
}) => {
|
||||
|
||||
// Fetch the staff user's region's slots (getSlots now requires a region).
|
||||
const { regionId } = useStaffAuth();
|
||||
const { data: slotsData } = trpc.user.slots.getSlots.useQuery(
|
||||
{ regionId: regionId ?? 0 },
|
||||
{ enabled: regionId != null }
|
||||
);
|
||||
|
||||
const createSnippet = trpc.admin.vendorSnippets.create.useMutation();
|
||||
const updateSnippet = trpc.admin.vendorSnippets.update.useMutation();
|
||||
|
||||
const isEditing = !!snippet;
|
||||
|
||||
const formik = useFormik({
|
||||
initialValues: {
|
||||
snippetCode: snippet?.snippetCode || '',
|
||||
slotId: snippet?.slotId?.toString() || '',
|
||||
isPermanent: snippet?.isPermanent || false,
|
||||
skuIds: snippet?.skuIds?.map(id => id.toString()) || [],
|
||||
validTill: snippet?.validTill ? new Date(snippet.validTill) : null,
|
||||
},
|
||||
validate: (values) => {
|
||||
const errors: {[key: string]: string} = {};
|
||||
|
||||
if (!values.snippetCode.trim()) {
|
||||
errors.snippetCode = 'Snippet code is required';
|
||||
}
|
||||
|
||||
// Validate snippet code only contains alphanumeric characters and underscore
|
||||
const snippetCodeRegex = /^[a-zA-Z0-9_]+$/;
|
||||
if (values.snippetCode && !snippetCodeRegex.test(values.snippetCode)) {
|
||||
errors.snippetCode = 'Snippet code can only contain letters, numbers, and underscores';
|
||||
}
|
||||
|
||||
// Only require slotId if isPermanent is false
|
||||
if (!values.isPermanent && !values.slotId) {
|
||||
errors.slotId = 'Slot selection is required';
|
||||
}
|
||||
|
||||
if (values.skuIds.length === 0) {
|
||||
errors.skuIds = 'At least one product must be selected';
|
||||
}
|
||||
|
||||
return errors;
|
||||
},
|
||||
onSubmit: async (values) => {
|
||||
try {
|
||||
|
||||
const submitData = {
|
||||
snippetCode: values.snippetCode,
|
||||
slotId: values.isPermanent ? undefined : parseInt(values.slotId || '0'),
|
||||
isPermanent: values.isPermanent,
|
||||
skuIds: values.skuIds.map(id => parseInt(id)),
|
||||
validTill: values.validTill ? values.validTill.toISOString() : undefined,
|
||||
};
|
||||
|
||||
if (isEditing && snippet) {
|
||||
await updateSnippet.mutateAsync({
|
||||
id: snippet.id,
|
||||
updates: submitData,
|
||||
});
|
||||
Alert.alert('Success', 'Vendor snippet updated successfully');
|
||||
} else {
|
||||
await createSnippet.mutateAsync(submitData);
|
||||
Alert.alert('Success', 'Vendor snippet created successfully');
|
||||
}
|
||||
|
||||
onSuccess();
|
||||
onClose();
|
||||
} catch (error: any) {
|
||||
Alert.alert('Error', error.message || 'Failed to save vendor snippet');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Generate unique snippet code if creating new (only on mount)
|
||||
useEffect(() => {
|
||||
if (!isEditing && !formik.values.snippetCode) {
|
||||
const timestamp = Date.now();
|
||||
const random = Math.random().toString(36).substring(2, 8);
|
||||
formik.setFieldValue('snippetCode', `VS_${timestamp}_${random}`);
|
||||
}
|
||||
}, [isEditing]); // Removed formik.values.snippetCode from deps
|
||||
|
||||
|
||||
|
||||
const slotOptions = slotsData?.slots.map(slot => ({
|
||||
label: new Date(slot.deliveryTime).toLocaleString(),
|
||||
value: slot.id.toString(),
|
||||
})) || [];
|
||||
|
||||
return (
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<View style={tw`px-6 py-4 border-b border-gray-200`}>
|
||||
<View style={tw`flex-row justify-between items-center`}>
|
||||
<MyText style={tw`text-xl font-bold text-gray-800`}>
|
||||
{isEditing ? 'Edit Vendor Snippet' : 'Create Vendor Snippet'}
|
||||
</MyText>
|
||||
<TouchableOpacity
|
||||
onPress={onClose}
|
||||
style={tw`p-2`}
|
||||
>
|
||||
<MyText style={tw`text-gray-500 text-lg`}>✕</MyText>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<ScrollView style={tw`flex-1 px-6`} showsVerticalScrollIndicator={false}>
|
||||
<View style={tw`py-6 space-y-6`}>
|
||||
{/* Snippet Code */}
|
||||
<View>
|
||||
<MyTextInput
|
||||
testID="snippet-code-input"
|
||||
topLabel="Snippet Code"
|
||||
value={formik.values.snippetCode}
|
||||
onChangeText={formik.handleChange('snippetCode')}
|
||||
placeholder="Enter snippet code"
|
||||
error={!!formik.errors.snippetCode && formik.touched.snippetCode}
|
||||
/>
|
||||
{formik.errors.snippetCode && formik.touched.snippetCode && (
|
||||
<MyText style={tw`text-red-500 text-sm mt-1`}>{formik.errors.snippetCode}</MyText>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Is Permanent Checkbox */}
|
||||
<View>
|
||||
<TouchableOpacity
|
||||
onPress={() => formik.setFieldValue('isPermanent', !formik.values.isPermanent)}
|
||||
style={tw`flex-row items-center mb-2`}
|
||||
>
|
||||
<View style={[
|
||||
tw`w-6 h-6 border-2 rounded-md mr-3 justify-center items-center`,
|
||||
formik.values.isPermanent ? tw`bg-blue-500 border-blue-500` : tw`border-gray-300`
|
||||
]}>
|
||||
{formik.values.isPermanent && (
|
||||
<MyText style={tw`text-white text-center text-lg`}>✓</MyText>
|
||||
)}
|
||||
</View>
|
||||
<MyText style={tw`text-gray-700 font-medium`}>Is Permanent?</MyText>
|
||||
</TouchableOpacity>
|
||||
<MyText style={tw`text-sm text-gray-500`}>
|
||||
Check if this snippet is permanent and not tied to a specific delivery slot
|
||||
</MyText>
|
||||
</View>
|
||||
|
||||
{/* Slot Selection - Only show if not permanent */}
|
||||
{!formik.values.isPermanent && (
|
||||
<View>
|
||||
<MyText style={tw`text-gray-700 font-medium mb-2`}>Delivery Slot</MyText>
|
||||
<BottomDropdown
|
||||
label="Select Slot"
|
||||
value={formik.values.slotId}
|
||||
options={slotOptions}
|
||||
onValueChange={(value) => formik.setFieldValue('slotId', value)}
|
||||
placeholder="Choose a delivery slot"
|
||||
/>
|
||||
{formik.errors.slotId && formik.touched.slotId && (
|
||||
<MyText style={tw`text-red-500 text-sm mt-1`}>{formik.errors.slotId}</MyText>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Product Selection */}
|
||||
<View>
|
||||
<ProductsSelector
|
||||
testID="snippet-form-products-selector"
|
||||
value={formik.values.skuIds.map(id => parseInt(id))}
|
||||
onChange={(selectedProductIds) => formik.setFieldValue('skuIds', (selectedProductIds as number[]).map(id => id.toString()))}
|
||||
multiple={true}
|
||||
label="Select Products"
|
||||
placeholder="Select products"
|
||||
labelFormat={(product) => product.label}
|
||||
/>
|
||||
{formik.errors.skuIds && formik.touched.skuIds && (
|
||||
<MyText style={tw`text-red-500 text-sm mt-1`}>{formik.errors.skuIds}</MyText>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Valid Till Date */}
|
||||
<View>
|
||||
<MyText style={tw`text-gray-700 font-medium mb-2`}>Valid Till (Optional)</MyText>
|
||||
<DatePicker
|
||||
value={formik.values.validTill}
|
||||
setValue={(date) => formik.setFieldValue('validTill', date)}
|
||||
placeholder="Select expiry date"
|
||||
showLabel={false}
|
||||
/>
|
||||
<MyText style={tw`text-sm text-gray-500 mt-1`}>
|
||||
Leave empty for no expiry
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
{/* Submit Button */}
|
||||
<View style={tw`px-6 py-4 border-t border-gray-200`}>
|
||||
<TouchableOpacity
|
||||
testID="snippet-submit-button"
|
||||
onPress={() => formik.handleSubmit()}
|
||||
disabled={formik.isSubmitting}
|
||||
style={tw`bg-blue-500 py-3 rounded-lg ${formik.isSubmitting ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<MyText style={tw`text-white text-center font-semibold`}>
|
||||
{formik.isSubmitting
|
||||
? 'Saving...'
|
||||
: isEditing ? 'Update Snippet' : 'Create Snippet'
|
||||
}
|
||||
</MyText>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
export default VendorSnippetForm;
|
||||
|
|
@ -149,8 +149,8 @@ directly.
|
|||
`USER_NO_NAME`, `USERS`, `USER_DETAILS`, `USER_INCIDENTS`,
|
||||
`NOTIFICATION_USERS`, `COUPON_1`, `COUPON_GLOBAL`, `COUPON_EXPIRED`,
|
||||
`COUPON_INVALIDATED`, `COUPON_RESERVED`, `COUPONS`, `TAG_1`, `TAG_2`, `TAGS`,
|
||||
`GROUP_1`, `GROUPS`, `BANNER_1`, `BANNERS`, `SNIPPET_1`, `SNIPPETS`,
|
||||
`SNIPPET_ORDERS`, `COMPLAINT_1`, `COMPLAINT_2`, `COMPLAINTS`, `TEST_JWT`.
|
||||
`GROUP_1`, `GROUPS`, `BANNER_1`, `BANNERS`, `COMPLAINT_1`, `COMPLAINT_2`,
|
||||
`COMPLAINTS`, `TEST_JWT`.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -194,15 +194,13 @@ describe('Drawer layout (ADRAW-01..19)', () => {
|
|||
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons')
|
||||
})
|
||||
|
||||
it('ADRAW-11: Vendor Snippets / Stores / Users / Notifications open their routes', async () => {
|
||||
it('ADRAW-11: Stores / Users / Notifications open their routes', async () => {
|
||||
const view = await renderDrawer()
|
||||
|
||||
fireEvent.press(view.getByTestId('drawer-item-Vendor Snippets'))
|
||||
fireEvent.press(view.getByTestId('drawer-item-Stores'))
|
||||
fireEvent.press(view.getByTestId('drawer-item-User Management'))
|
||||
fireEvent.press(view.getByTestId('drawer-item-Send Notifications'))
|
||||
|
||||
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/vendor-snippets')
|
||||
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores')
|
||||
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management')
|
||||
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/send-notifications')
|
||||
|
|
@ -271,7 +269,6 @@ describe('Drawer layout (ADRAW-01..19)', () => {
|
|||
['complaints', 'Complaints'],
|
||||
['manage-orders', 'Manage Orders'],
|
||||
['coupons', 'Coupons'],
|
||||
['vendor-snippets', 'Vendor Snippets'],
|
||||
['stores', 'Stores'],
|
||||
['user-management', 'User Management'],
|
||||
['send-notifications', 'Send Notifications'],
|
||||
|
|
|
|||
|
|
@ -1,52 +0,0 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/**
|
||||
* Catalogue section 17.1 — ProductListDialog
|
||||
* (`tests/components/product-list-dialog.test.tsx`).
|
||||
*/
|
||||
import React from 'react'
|
||||
import { TouchableOpacity } from 'react-native'
|
||||
import { fireEvent, render } from '@testing-library/react-native'
|
||||
|
||||
import { ProductListDialog } from '@/components/ProductListDialog'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
|
||||
const PRODUCTS = [
|
||||
{ id: 11, name: 'Chicken Breast - 500g' },
|
||||
{ id: 13, name: 'Cucumber - 500g' },
|
||||
]
|
||||
|
||||
describe('ProductListDialog (APLD-01..03)', () => {
|
||||
beforeEach(() => resetAllMocks())
|
||||
|
||||
it('APLD-01: an open dialog lists every product with its count', () => {
|
||||
const onClose = jest.fn()
|
||||
const view = render(
|
||||
<ProductListDialog open onClose={onClose} products={PRODUCTS} />
|
||||
)
|
||||
|
||||
expect(view.getByText('Products (2)')).toBeTruthy()
|
||||
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
|
||||
expect(view.getByText('Cucumber - 500g')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('APLD-02: pressing the backdrop closes the dialog', () => {
|
||||
const onClose = jest.fn()
|
||||
const view = render(
|
||||
<ProductListDialog open onClose={onClose} products={PRODUCTS} />
|
||||
)
|
||||
|
||||
// BottomDialog's dismissible backdrop is the first touchable in the modal.
|
||||
fireEvent.press(view.UNSAFE_getAllByType(TouchableOpacity)[0])
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('APLD-03: no products shows the empty count and copy', () => {
|
||||
const view = render(
|
||||
<ProductListDialog open onClose={jest.fn()} products={[]} />
|
||||
)
|
||||
|
||||
expect(view.getByText('Products (0)')).toBeTruthy()
|
||||
expect(view.queryByText('Chicken Breast - 500g')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/**
|
||||
* Catalogue section 7.3 — SlotForm and VendorSnippetForm
|
||||
* Catalogue section 7.3 — SlotForm
|
||||
* (`tests/components/slot-form.test.tsx`).
|
||||
*/
|
||||
import React from 'react'
|
||||
|
|
@ -8,7 +8,6 @@ import { Alert } from 'react-native'
|
|||
import { fireEvent } from '@testing-library/react-native'
|
||||
|
||||
import SlotForm from '@/components/SlotForm'
|
||||
import VendorSnippetForm from '@/components/VendorSnippetForm'
|
||||
import { renderWithProviders, flush } from '../helpers/test-utils'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
|
||||
|
|
@ -56,7 +55,6 @@ describe('SlotForm (ASLOTF-01..10)', () => {
|
|||
expect(view.getByText('Create New Slot')).toBeTruthy()
|
||||
expect(view.getByText('Delivery Date & Time')).toBeTruthy()
|
||||
expect(view.getByText('Freeze Date & Time')).toBeTruthy()
|
||||
expect(view.getByText('Vendor Snippets')).toBeTruthy()
|
||||
expect(view.getByText('Create Slot')).toBeTruthy()
|
||||
})
|
||||
|
||||
|
|
@ -103,49 +101,6 @@ describe('SlotForm (ASLOTF-01..10)', () => {
|
|||
)
|
||||
})
|
||||
|
||||
it('ASLOTF-05: adding a vendor snippet includes name, SKUs and no expiry', async () => {
|
||||
const view = renderSlotForm()
|
||||
await flush()
|
||||
|
||||
selectSku(view, 'slot-products-selector', 13)
|
||||
fireEvent.press(view.getByText('Add Vendor Snippet'))
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet name'), 'Snippet A')
|
||||
selectSku(view, 'snippet-products-selector', 13)
|
||||
setDates(view)
|
||||
fireEvent.press(view.getByTestId('create-slot-button'))
|
||||
await flush(2)
|
||||
|
||||
const input = lastMutationInput('admin.slots.createSlot')
|
||||
expect(input.vendorSnippets).toEqual([
|
||||
{ name: 'Snippet A', skuIds: [13], validTill: '' },
|
||||
])
|
||||
})
|
||||
|
||||
it('ASLOTF-06: removing a vendor snippet drops it from the list', () => {
|
||||
const view = renderSlotForm()
|
||||
|
||||
fireEvent.press(view.getByText('Add Vendor Snippet'))
|
||||
expect(view.getByText('Snippet Name *')).toBeTruthy()
|
||||
|
||||
fireEvent.press(view.getByText('Remove Snippet'))
|
||||
expect(view.queryByText('Snippet Name *')).toBeNull()
|
||||
})
|
||||
|
||||
it('ASLOTF-07: a snippet without SKUs is submitted as-is (no validation)', async () => {
|
||||
const view = renderSlotForm()
|
||||
|
||||
fireEvent.press(view.getByText('Add Vendor Snippet'))
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet name'), 'Empty Snippet')
|
||||
setDates(view)
|
||||
fireEvent.press(view.getByTestId('create-slot-button'))
|
||||
await flush(2)
|
||||
|
||||
const input = lastMutationInput('admin.slots.createSlot')
|
||||
expect(input.vendorSnippets).toEqual([
|
||||
{ name: 'Empty Snippet', skuIds: [], validTill: '' },
|
||||
])
|
||||
})
|
||||
|
||||
it('ASLOTF-08: group selection is sent as group ids', async () => {
|
||||
const view = renderSlotForm()
|
||||
await flush()
|
||||
|
|
@ -187,128 +142,3 @@ describe('SlotForm (ASLOTF-01..10)', () => {
|
|||
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('VendorSnippetForm (AVSF-01..08)', () => {
|
||||
let alertSpy: jest.SpyInstance
|
||||
let onClose: jest.Mock
|
||||
let onSuccess: jest.Mock
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllMocks()
|
||||
onClose = jest.fn()
|
||||
onSuccess = jest.fn()
|
||||
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
})
|
||||
|
||||
afterEach(() => alertSpy?.mockRestore())
|
||||
|
||||
function renderSnippetForm(snippet?: any) {
|
||||
return renderWithProviders(
|
||||
<VendorSnippetForm snippet={snippet} onClose={onClose} onSuccess={onSuccess} />,
|
||||
{ auth: 'in' }
|
||||
)
|
||||
}
|
||||
|
||||
it('AVSF-01: renders code, slot, products, expiry and permanent fields', () => {
|
||||
const view = renderSnippetForm()
|
||||
|
||||
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
|
||||
expect(view.getByTestId('snippet-code-input').props.value).toMatch(/^VS_/)
|
||||
expect(view.getByText('Is Permanent?')).toBeTruthy()
|
||||
expect(view.getByText('Delivery Slot')).toBeTruthy()
|
||||
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
|
||||
expect(view.getByTestId('snippet-form-products-selector')).toBeTruthy()
|
||||
expect(view.getByText('Create Snippet')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVSF-02: an empty code is rejected', async () => {
|
||||
const view = renderSnippetForm()
|
||||
|
||||
fireEvent.changeText(view.getByTestId('snippet-code-input'), '')
|
||||
fireEvent.press(view.getByTestId('snippet-submit-button'))
|
||||
await flush(2)
|
||||
|
||||
expect(view.getByText('Snippet code is required')).toBeTruthy()
|
||||
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('AVSF-03: submitting without products is rejected', async () => {
|
||||
const view = renderSnippetForm()
|
||||
|
||||
fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1')
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
fireEvent.press(view.getByTestId('snippet-submit-button'))
|
||||
await flush(2)
|
||||
|
||||
expect(view.getByText('At least one product must be selected')).toBeTruthy()
|
||||
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('AVSF-04: permanent hides the slot selector', () => {
|
||||
const view = renderSnippetForm()
|
||||
|
||||
expect(view.getByText('Delivery Slot')).toBeTruthy()
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
|
||||
expect(view.queryByText('Delivery Slot')).toBeNull()
|
||||
// Current behaviour: the expiry field stays visible for permanent snippets.
|
||||
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVSF-05: editing prefills the saved values', () => {
|
||||
const validTill = new Date(Date.now() + 24 * HOUR)
|
||||
const view = renderSnippetForm({
|
||||
id: 1,
|
||||
snippetCode: 'ABC123',
|
||||
slotId: 1849,
|
||||
isPermanent: false,
|
||||
skuIds: [11],
|
||||
validTill,
|
||||
})
|
||||
|
||||
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
|
||||
expect(view.getByTestId('snippet-code-input').props.value).toBe('ABC123')
|
||||
expect(view.getByText('Update Snippet')).toBeTruthy()
|
||||
expect(view.getAllByText(validTill.toLocaleDateString()).length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('AVSF-06: the product selector updates the selection', async () => {
|
||||
const view = renderSnippetForm()
|
||||
await flush()
|
||||
|
||||
selectSku(view, 'snippet-form-products-selector', 11)
|
||||
|
||||
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVSF-07: submit sends the complete snippet payload', async () => {
|
||||
const view = renderSnippetForm()
|
||||
await flush()
|
||||
|
||||
fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1')
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
selectSku(view, 'snippet-form-products-selector', 11)
|
||||
fireEvent.press(view.getByTestId('snippet-submit-button'))
|
||||
await flush(2)
|
||||
|
||||
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
|
||||
snippetCode: 'TEST_1',
|
||||
slotId: undefined,
|
||||
isPermanent: true,
|
||||
skuIds: [11],
|
||||
validTill: undefined,
|
||||
})
|
||||
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
|
||||
expect(onSuccess).toHaveBeenCalled()
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('AVSF-08: cancel calls onClose', () => {
|
||||
const view = renderSnippetForm()
|
||||
|
||||
fireEvent.press(view.getByText('✕'))
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,135 +0,0 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/**
|
||||
* Catalogue section 15 — SnippetMenu (`tests/components/snippet-menu.test.tsx`).
|
||||
*/
|
||||
import React from 'react'
|
||||
import { Alert, Clipboard } from 'react-native'
|
||||
import { fireEvent, render } from '@testing-library/react-native'
|
||||
|
||||
import { SnippetMenu } from '@/components/SnippetMenu'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import { SNIPPET_1 } from '../fixtures'
|
||||
|
||||
function openMenu(view: ReturnType<typeof render>) {
|
||||
const trigger = view.UNSAFE_getAllByProps({ name: 'dots-three-vertical' })[0]
|
||||
fireEvent.press(trigger)
|
||||
}
|
||||
|
||||
describe('SnippetMenu (ASMENU-01..05)', () => {
|
||||
beforeEach(() => resetAllMocks())
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('ASMENU-01: the menu lists View Orders / Edit / Copy URL / Delete', () => {
|
||||
const view = render(
|
||||
<SnippetMenu
|
||||
snippet={SNIPPET_1 as any}
|
||||
onEdit={jest.fn()}
|
||||
onDelete={jest.fn()}
|
||||
onViewOrders={jest.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
openMenu(view)
|
||||
|
||||
expect(view.getByText('Snippet Options')).toBeTruthy()
|
||||
expect(view.getByText('View Orders')).toBeTruthy()
|
||||
expect(view.getByText('Edit')).toBeTruthy()
|
||||
expect(view.getByText('Copy URL')).toBeTruthy()
|
||||
expect(view.getByText('Delete')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASMENU-02: Copy URL without an access URL alerts and copies nothing', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const copySpy = jest.spyOn(Clipboard, 'setString').mockImplementation(async () => undefined)
|
||||
const view = render(
|
||||
<SnippetMenu
|
||||
snippet={{ ...SNIPPET_1, accessUrl: null } as any}
|
||||
onEdit={jest.fn()}
|
||||
onDelete={jest.fn()}
|
||||
onViewOrders={jest.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('Copy URL'))
|
||||
|
||||
expect(alertSpy).toHaveBeenCalledWith('Error', 'No URL available to copy')
|
||||
expect(copySpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ASMENU-03: Copy URL writes the access URL to the clipboard', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const copySpy = jest.spyOn(Clipboard, 'setString').mockImplementation(async () => undefined)
|
||||
const view = render(
|
||||
<SnippetMenu
|
||||
snippet={SNIPPET_1 as any}
|
||||
onEdit={jest.fn()}
|
||||
onDelete={jest.fn()}
|
||||
onViewOrders={jest.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('Copy URL'))
|
||||
|
||||
expect(copySpy).toHaveBeenCalledWith('https://access.test/ABC123')
|
||||
expect(alertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ASMENU-04: Delete confirms, then calls onDelete with the snippet id', () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const onDelete = jest.fn()
|
||||
const view = render(
|
||||
<SnippetMenu
|
||||
snippet={SNIPPET_1 as any}
|
||||
onEdit={jest.fn()}
|
||||
onDelete={onDelete}
|
||||
onViewOrders={jest.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('Delete'))
|
||||
|
||||
expect(alertSpy).toHaveBeenCalledTimes(1)
|
||||
const [title, message, buttons] = alertSpy.mock.calls[0]
|
||||
expect(title).toBe('Delete Snippet')
|
||||
expect(message).toBe('Are you sure you want to delete this vendor snippet?')
|
||||
expect(buttons?.map((button) => button.text)).toEqual(['Cancel', 'Delete'])
|
||||
expect(onDelete).not.toHaveBeenCalled()
|
||||
|
||||
buttons?.find((button) => button.text === 'Delete')?.onPress?.()
|
||||
expect(onDelete).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('ASMENU-05: no menu option is currently disabled and a disabled option would no-op', () => {
|
||||
const onEdit = jest.fn()
|
||||
const onViewOrders = jest.fn()
|
||||
const onDelete = jest.fn()
|
||||
const view = render(
|
||||
<SnippetMenu
|
||||
snippet={SNIPPET_1 as any}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onViewOrders={onViewOrders}
|
||||
/>
|
||||
)
|
||||
|
||||
openMenu(view)
|
||||
|
||||
// The source supports `option.disabled` (handleOptionPress returns early and
|
||||
// the row gets `disabled`), but every built-in option is enabled today.
|
||||
const titles = ['View Orders', 'Edit', 'Copy URL', 'Delete']
|
||||
titles.forEach((title) => {
|
||||
expect(view.getByText(title).parent?.props.disabled).toBeFalsy()
|
||||
})
|
||||
|
||||
fireEvent.press(view.getByText('View Orders'))
|
||||
expect(onViewOrders).toHaveBeenCalledWith('ABC123')
|
||||
expect(onEdit).not.toHaveBeenCalled()
|
||||
expect(onDelete).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,109 +0,0 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/**
|
||||
* Catalogue section 15 — SnippetOrdersView
|
||||
* (`tests/components/snippet-orders-view.test.tsx`).
|
||||
*/
|
||||
import React from 'react'
|
||||
import { fireEvent } from '@testing-library/react-native'
|
||||
|
||||
import SnippetOrdersView from '@/components/SnippetOrdersView'
|
||||
import { renderWithProviders } from '../helpers/test-utils'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import { SNIPPET_ORDERS } from '../fixtures'
|
||||
|
||||
type Order = any
|
||||
|
||||
const ORDER: Order = {
|
||||
...SNIPPET_ORDERS.data[0],
|
||||
totalAmount: '445',
|
||||
slotInfo: {
|
||||
time: new Date('2026-10-19T12:00:00.000Z').toISOString(),
|
||||
sequence: [],
|
||||
},
|
||||
products: [
|
||||
{
|
||||
orderItemId: 1,
|
||||
productId: 2,
|
||||
productName: 'Chicken Breast',
|
||||
quantity: 2,
|
||||
productSize: 500,
|
||||
price: 215,
|
||||
unit: '500g',
|
||||
subtotal: 430,
|
||||
},
|
||||
{
|
||||
orderItemId: 2,
|
||||
productId: 5,
|
||||
productName: 'Cucumber',
|
||||
quantity: 1,
|
||||
productSize: 500,
|
||||
price: 15,
|
||||
unit: '500g',
|
||||
subtotal: 15,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
function renderView(props: { orders: Order[]; snippetCode: string; onClose: () => void }) {
|
||||
return renderWithProviders(<SnippetOrdersView {...props} />, { auth: false })
|
||||
}
|
||||
|
||||
describe('SnippetOrdersView (ASOV-01..05)', () => {
|
||||
beforeEach(() => resetAllMocks())
|
||||
|
||||
it('ASOV-01: an order card shows id, customer, total, date and slot', () => {
|
||||
const view = renderView({ orders: [ORDER], snippetCode: 'ABC123', onClose: jest.fn() })
|
||||
|
||||
expect(view.getByText('Orders for "ABC123"')).toBeTruthy()
|
||||
expect(view.getByText('ORD-1011')).toBeTruthy()
|
||||
expect(view.getByText('Test User')).toBeTruthy()
|
||||
expect(view.getByText('₹445')).toBeTruthy()
|
||||
expect(view.getByText(new Date(ORDER.orderDate).toLocaleDateString())).toBeTruthy()
|
||||
expect(
|
||||
view.getByText(`Delivery: ${new Date(ORDER.slotInfo.time).toLocaleString()}`)
|
||||
).toBeTruthy()
|
||||
expect(view.getByText('1 order • Total: ₹445.00')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASOV-02: matched products are highlighted and non-matched ones are not', () => {
|
||||
const view = renderView({
|
||||
orders: [{ ...ORDER, matchedProducts: [2] }],
|
||||
snippetCode: 'ABC123',
|
||||
onClose: jest.fn(),
|
||||
})
|
||||
|
||||
// Matched rows get the star suffix; the non-matched row keeps its plain name.
|
||||
expect(view.getByText('Chicken Breast ⭐')).toBeTruthy()
|
||||
expect(view.getByText('Cucumber')).toBeTruthy()
|
||||
expect(view.getByText('Matched 1 product(s) from snippet "ABC123"')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASOV-03: line subtotals and the order total are formatted to two decimals', () => {
|
||||
const view = renderView({ orders: [ORDER], snippetCode: 'ABC123', onClose: jest.fn() })
|
||||
|
||||
expect(view.getByText('₹430.00')).toBeTruthy()
|
||||
expect(view.getByText('₹15.00')).toBeTruthy()
|
||||
expect(view.getByText('2 500g × ₹215')).toBeTruthy()
|
||||
expect(view.getByText('1 500g × ₹15')).toBeTruthy()
|
||||
expect(view.getByText('1 order • Total: ₹445.00')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASOV-04: an empty order list shows the empty state', () => {
|
||||
const view = renderView({ orders: [], snippetCode: 'ABC123', onClose: jest.fn() })
|
||||
|
||||
expect(view.getByText('No matching orders')).toBeTruthy()
|
||||
expect(
|
||||
view.getByText("No orders found that match this snippet's criteria")
|
||||
).toBeTruthy()
|
||||
expect(view.getByText('0 orders • Total: ₹0.00')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASOV-05: the close button calls onClose', () => {
|
||||
const onClose = jest.fn()
|
||||
const view = renderView({ orders: [ORDER], snippetCode: 'ABC123', onClose })
|
||||
|
||||
fireEvent.press(view.getByText('✕'))
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,183 +0,0 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/**
|
||||
* Catalogue section 15 — VendorSnippetForm
|
||||
* (`tests/components/vendor-snippet-form.test.tsx`).
|
||||
*/
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent } from '@testing-library/react-native'
|
||||
|
||||
jest.mock('@/components/context/staff-auth-context', () =>
|
||||
require('../mocks/staff-auth-context')
|
||||
)
|
||||
|
||||
import VendorSnippetForm from '@/components/VendorSnippetForm'
|
||||
import { __setStaffState } from '../mocks/staff-auth-context'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import { flush, renderWithProviders } from '../helpers/test-utils'
|
||||
import { lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
|
||||
import { SLOT_1, SNIPPET_1, STAFF } from '../fixtures'
|
||||
|
||||
function renderForm(props: Partial<React.ComponentProps<typeof VendorSnippetForm>> = {}) {
|
||||
return renderWithProviders(
|
||||
<VendorSnippetForm onClose={jest.fn()} onSuccess={jest.fn()} {...props} />,
|
||||
{ auth: 'in' }
|
||||
)
|
||||
}
|
||||
|
||||
async function selectProduct(view: ReturnType<typeof renderForm>, label: string) {
|
||||
fireEvent.press(view.getByText('Select products'))
|
||||
fireEvent.press(view.getByText(label))
|
||||
fireEvent.press(view.getByText('Done'))
|
||||
}
|
||||
|
||||
describe('VendorSnippetForm (AVFORM-01..08)', () => {
|
||||
beforeEach(() => {
|
||||
resetAllMocks()
|
||||
__setStaffState({ isLoggedIn: true, isLoading: false, staff: STAFF })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('AVFORM-01: renders code / slot / products / validTill / permanent fields', () => {
|
||||
const view = renderForm()
|
||||
|
||||
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
|
||||
expect(view.getByText('Snippet Code')).toBeTruthy()
|
||||
expect(view.getByText('Is Permanent?')).toBeTruthy()
|
||||
expect(view.getByText('Delivery Slot')).toBeTruthy()
|
||||
expect(view.getByText('Choose a delivery slot')).toBeTruthy()
|
||||
expect(view.getByText('Select products')).toBeTruthy()
|
||||
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
|
||||
expect(view.getByText('Create Snippet')).toBeTruthy()
|
||||
|
||||
// A unique snippet code is generated on mount for new snippets.
|
||||
const codeInput = view.getByPlaceholderText('Enter snippet code')
|
||||
expect(String(codeInput.props.value)).toMatch(/^VS_\d+_[a-z0-9]+$/)
|
||||
})
|
||||
|
||||
it('AVFORM-02: an empty code blocks submit with a validation message', async () => {
|
||||
const view = renderForm()
|
||||
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), '')
|
||||
fireEvent.press(view.getByText('Create Snippet'))
|
||||
await flush()
|
||||
|
||||
expect(view.getByText('Snippet code is required')).toBeTruthy()
|
||||
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('AVFORM-03: submitting without products blocks the mutation', async () => {
|
||||
const view = renderForm()
|
||||
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'CODE123')
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
fireEvent.press(view.getByText('Create Snippet'))
|
||||
await flush()
|
||||
|
||||
expect(view.getByText('At least one product must be selected')).toBeTruthy()
|
||||
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('AVFORM-04: permanent snippets hide the delivery slot section', () => {
|
||||
const view = renderForm()
|
||||
|
||||
expect(view.getByText('Delivery Slot')).toBeTruthy()
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
|
||||
expect(view.queryByText('Delivery Slot')).toBeNull()
|
||||
expect(view.queryByText('Select Slot')).toBeNull()
|
||||
// validTill is not tied to the permanence toggle in the current form.
|
||||
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVFORM-05: the product selector stores the selected SKU ids', async () => {
|
||||
const view = renderForm()
|
||||
await flush()
|
||||
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'CODE123')
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
|
||||
fireEvent.press(view.getByText('Select products'))
|
||||
fireEvent.press(view.getByText('Chicken Breast - 500g'))
|
||||
fireEvent.press(view.getByText('Chicken Breast - 1kg'))
|
||||
fireEvent.press(view.getByText('Done'))
|
||||
|
||||
expect(view.getByText('Chicken Breast - 500g, Chicken Breast - 1kg')).toBeTruthy()
|
||||
|
||||
fireEvent.press(view.getByText('Create Snippet'))
|
||||
await flush()
|
||||
|
||||
expect(lastMutationInput('admin.vendorSnippets.create').skuIds).toEqual([11, 12])
|
||||
})
|
||||
|
||||
it('AVFORM-06: create submits the exact payload and reports success', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const onClose = jest.fn()
|
||||
const onSuccess = jest.fn()
|
||||
const view = renderForm({ onClose, onSuccess })
|
||||
await flush()
|
||||
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'MYCODE')
|
||||
fireEvent.press(view.getByText('Choose a delivery slot'))
|
||||
fireEvent.press(view.getByText(new Date(SLOT_1.deliveryTime).toLocaleString()))
|
||||
await selectProduct(view, 'Chicken Breast - 500g')
|
||||
fireEvent.press(view.getByText('Create Snippet'))
|
||||
await flush()
|
||||
|
||||
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
|
||||
snippetCode: 'MYCODE',
|
||||
slotId: 1849,
|
||||
isPermanent: false,
|
||||
skuIds: [11],
|
||||
validTill: undefined,
|
||||
})
|
||||
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
|
||||
expect(onSuccess).toHaveBeenCalledTimes(1)
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('AVFORM-07: editing prefills the form and submits an update payload', async () => {
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const onSuccess = jest.fn()
|
||||
const view = renderForm({ snippet: SNIPPET_1 as any, onSuccess })
|
||||
await flush()
|
||||
|
||||
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
|
||||
expect(view.getByDisplayValue('ABC123')).toBeTruthy()
|
||||
// The existing SKU is shown as the current selection.
|
||||
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
|
||||
expect(view.getByText(`Delivery Slot`)).toBeTruthy()
|
||||
expect(
|
||||
view.getByText(new Date(SLOT_1.deliveryTime).toLocaleString())
|
||||
).toBeTruthy()
|
||||
|
||||
fireEvent.press(view.getByText('Update Snippet'))
|
||||
await flush()
|
||||
|
||||
expect(lastMutationInput('admin.vendorSnippets.update')).toEqual({
|
||||
id: 1,
|
||||
updates: {
|
||||
snippetCode: 'ABC123',
|
||||
slotId: 1849,
|
||||
isPermanent: false,
|
||||
skuIds: [11],
|
||||
validTill: SNIPPET_1.validTill,
|
||||
},
|
||||
})
|
||||
expect(onSuccess).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('AVFORM-08: the close button calls onClose without saving', async () => {
|
||||
const onClose = jest.fn()
|
||||
const view = renderForm({ onClose })
|
||||
|
||||
fireEvent.press(view.getByText('✕'))
|
||||
await flush()
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
42
apps/admin-ui/tests/fixtures/index.ts
vendored
42
apps/admin-ui/tests/fixtures/index.ts
vendored
|
|
@ -254,9 +254,6 @@ export const SLOT_DETAIL = {
|
|||
...SLOT_1,
|
||||
deliverySequence: [101, 102],
|
||||
groupIds: [1],
|
||||
vendorSnippets: [
|
||||
{ id: 1, snippetCode: 'ABC123', slotId: 1849, skuIds: [11], isPermanent: false, validTill: iso(24 * HOUR), createdAt: iso(0), accessUrl: 'https://access.test/ABC123' },
|
||||
],
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
|
@ -485,45 +482,6 @@ export const BANNER_1 = {
|
|||
export const BANNERS = [BANNER_1]
|
||||
export const BANNERS_RESPONSE = { banners: BANNERS, count: BANNERS.length }
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Vendor snippets */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
export const SNIPPET_1 = {
|
||||
id: 1,
|
||||
snippetCode: 'ABC123',
|
||||
slotId: 1849,
|
||||
skuIds: [11],
|
||||
isPermanent: false,
|
||||
validTill: iso(24 * HOUR),
|
||||
createdAt: iso(0),
|
||||
accessUrl: 'https://access.test/ABC123',
|
||||
slot: SLOT_1,
|
||||
products: [{ id: 11, name: 'Chicken Breast - 500g' }],
|
||||
}
|
||||
|
||||
export const SNIPPETS = [SNIPPET_1]
|
||||
export const SNIPPETS_RESPONSE = { snippets: SNIPPETS, count: SNIPPETS.length }
|
||||
|
||||
export const SNIPPET_ORDERS = {
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
orderId: 'ORD-1011',
|
||||
orderDate: iso(0),
|
||||
customerName: 'Test User',
|
||||
totalAmount: 445,
|
||||
slotInfo: { time: iso(2 * HOUR), sequence: 1 },
|
||||
products: [
|
||||
{ orderItemId: 1, productId: 2, productName: 'Chicken Breast', quantity: 2, productSize: 500, price: 215, unit: '500g', subtotal: 430, is_packaged: false, is_package_verified: false },
|
||||
],
|
||||
matchedProducts: [2],
|
||||
snippetCode: 'ABC123',
|
||||
},
|
||||
],
|
||||
snippet: { id: 1, snippetCode: 'ABC123', slotId: 1849, skuIds: [11], createdAt: iso(0), isPermanent: false },
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Complaints */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
|
|
|||
|
|
@ -32,8 +32,6 @@ import {
|
|||
SLOT_1,
|
||||
SLOT_DETAIL,
|
||||
SLOT_ORDERS,
|
||||
SNIPPETS_RESPONSE,
|
||||
SNIPPET_1,
|
||||
STAFF,
|
||||
STORES,
|
||||
STORE_1,
|
||||
|
|
@ -102,8 +100,8 @@ export const defaultProcedures: Record<string, ProcConfig> = {
|
|||
// ---- slots ----
|
||||
'admin.slots.getAll': { data: SLOTS_RESPONSE },
|
||||
'admin.slots.getSlotById': { data: { slot: SLOT_DETAIL } },
|
||||
'admin.slots.createSlot': { data: { slot: SLOT_1, createdSnippets: [], message: 'Slot created' } },
|
||||
'admin.slots.updateSlot': { data: { slot: SLOT_1, createdSnippets: [], message: 'Slot updated' } },
|
||||
'admin.slots.createSlot': { data: { slot: SLOT_1, message: 'Slot created' } },
|
||||
'admin.slots.updateSlot': { data: { slot: SLOT_1, message: 'Slot updated' } },
|
||||
'admin.slots.updateSlotCapacity': { data: { success: true, slot: SLOT_1, message: 'Capacity updated' } },
|
||||
'admin.slots.getDeliverySequence': { data: { deliverySequence: {} } },
|
||||
'admin.slots.updateDeliverySequence': { data: { slot: { id: 1849, deliverySequence: [] }, message: 'Sequence updated' } },
|
||||
|
|
@ -151,12 +149,6 @@ export const defaultProcedures: Record<string, ProcConfig> = {
|
|||
'admin.user.getUserIncidents': { data: { incidents: USER_INCIDENTS } },
|
||||
'admin.user.addUserIncident': { data: { incident: USER_INCIDENTS[0] } },
|
||||
|
||||
// ---- vendor snippets ----
|
||||
'admin.vendorSnippets.getAll': { data: SNIPPETS_RESPONSE },
|
||||
'admin.vendorSnippets.create': { data: { snippet: SNIPPET_1 } },
|
||||
'admin.vendorSnippets.update': { data: { snippet: SNIPPET_1 } },
|
||||
'admin.vendorSnippets.delete': { data: { message: 'Snippet deleted' } },
|
||||
|
||||
// ---- region / customize ----
|
||||
'admin.region.current': { data: { region: REGION } },
|
||||
'admin.region.bounds': { data: { bounds: BOUNDS } },
|
||||
|
|
|
|||
|
|
@ -99,7 +99,6 @@ describe('Add slot (ASLOTADD-01..06)', () => {
|
|||
isActive: true,
|
||||
groupIds: [],
|
||||
skuIds: [],
|
||||
vendorSnippets: [],
|
||||
})
|
||||
)
|
||||
await waitFor(() =>
|
||||
|
|
|
|||
|
|
@ -3,9 +3,7 @@
|
|||
* Catalogue section 7.2 — Slot details (`tests/pages/slot-details.test.tsx`).
|
||||
*/
|
||||
import React from 'react'
|
||||
import { Alert, Share } from 'react-native'
|
||||
import { fireEvent, waitFor } from '@testing-library/react-native'
|
||||
import dayjs from 'dayjs'
|
||||
import { fireEvent } from '@testing-library/react-native'
|
||||
|
||||
import SlotDetails from '@/app/(drawer)/dashboard/slots/slot-details'
|
||||
import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
|
||||
|
|
@ -18,21 +16,10 @@ function renderDetails() {
|
|||
return renderAndFlush(<SlotDetails />, { auth: 'in' })
|
||||
}
|
||||
|
||||
const SNIPPET = SLOT_DETAIL.vendorSnippets[0]
|
||||
|
||||
describe('Slot details (ASLOTDET-01..10)', () => {
|
||||
let alertSpy: jest.SpyInstance
|
||||
|
||||
describe('Slot details (ASLOTDET-01, 02, 05, 06)', () => {
|
||||
beforeEach(() => {
|
||||
resetAllMocks()
|
||||
__setParams({ slotId: '1849' })
|
||||
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' } as any)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
alertSpy?.mockRestore()
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('ASLOTDET-01: shows the loading copy', () => {
|
||||
|
|
@ -50,25 +37,6 @@ describe('Slot details (ASLOTDET-01..10)', () => {
|
|||
expect(await view.findByText('Error loading slot details')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASLOTDET-03: with no vendor snippets the empty copy is shown', async () => {
|
||||
setProcedure('admin.slots.getSlotById', {
|
||||
data: { slot: { ...SLOT_DETAIL, vendorSnippets: [] } },
|
||||
})
|
||||
const view = await renderDetails()
|
||||
|
||||
expect(view.getByText('No vendor snippets for this slot')).toBeTruthy()
|
||||
expect(view.getByText('0 snippets')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASLOTDET-04: renders snippet code, expiry and share action', async () => {
|
||||
const view = await renderDetails()
|
||||
|
||||
expect(view.getByText('ABC123')).toBeTruthy()
|
||||
expect(view.getByText('1 snippets')).toBeTruthy()
|
||||
expect(view.getByText('Share')).toBeTruthy()
|
||||
expect(view.getByText(`Expires ${dayjs(SNIPPET.validTill).format('MMM DD')}`)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASLOTDET-05: renders product names/count and the empty copy', async () => {
|
||||
const view = await renderDetails()
|
||||
expect(view.getByText('2 items')).toBeTruthy()
|
||||
|
|
@ -77,7 +45,7 @@ describe('Slot details (ASLOTDET-01..10)', () => {
|
|||
|
||||
view.unmount()
|
||||
setProcedure('admin.slots.getSlotById', {
|
||||
data: { slot: { ...SLOT_DETAIL, products: [], vendorSnippets: [] } },
|
||||
data: { slot: { ...SLOT_DETAIL, products: [] } },
|
||||
})
|
||||
const empty = await renderDetails()
|
||||
expect(empty.getByText('0 items')).toBeTruthy()
|
||||
|
|
@ -91,55 +59,4 @@ describe('Slot details (ASLOTDET-01..10)', () => {
|
|||
|
||||
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/edit/1849')
|
||||
})
|
||||
|
||||
it('ASLOTDET-07: a failed share alerts', async () => {
|
||||
;(Share.share as jest.Mock).mockRejectedValue(new Error('share failed'))
|
||||
const view = await renderDetails()
|
||||
|
||||
fireEvent.press(view.getByText('Share'))
|
||||
|
||||
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to share link'))
|
||||
})
|
||||
|
||||
it('ASLOTDET-08: a successful share passes the access URL', async () => {
|
||||
const view = await renderDetails()
|
||||
|
||||
fireEvent.press(view.getByText('Share'))
|
||||
|
||||
await waitFor(() => expect(Share.share).toHaveBeenCalledWith({ message: SNIPPET.accessUrl }))
|
||||
})
|
||||
|
||||
it('ASLOTDET-09: a snippet without a link shares an undefined message', async () => {
|
||||
setProcedure('admin.slots.getSlotById', {
|
||||
data: {
|
||||
slot: {
|
||||
...SLOT_DETAIL,
|
||||
vendorSnippets: [{ ...SNIPPET, accessUrl: undefined }],
|
||||
},
|
||||
},
|
||||
})
|
||||
const view = await renderDetails()
|
||||
|
||||
fireEvent.press(view.getByText('Share'))
|
||||
|
||||
await waitFor(() => expect(Share.share).toHaveBeenCalledWith({ message: undefined }))
|
||||
})
|
||||
|
||||
it('ASLOTDET-10: the snippet products dialog lists the matching products', async () => {
|
||||
setProcedure('admin.slots.getSlotById', {
|
||||
data: {
|
||||
slot: {
|
||||
...SLOT_DETAIL,
|
||||
vendorSnippets: [{ ...SNIPPET, skuIds: [2, 5] }],
|
||||
},
|
||||
},
|
||||
})
|
||||
const view = await renderDetails()
|
||||
|
||||
fireEvent.press(view.getByText('2 products'))
|
||||
|
||||
expect(view.getByText('Snippet Products')).toBeTruthy()
|
||||
expect(view.getAllByText('Chicken Breast').length).toBeGreaterThanOrEqual(2)
|
||||
expect(view.getAllByText('Cucumber').length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ describe('Edit slot (ASLOTEDIT-01..05)', () => {
|
|||
expect(view.getByText('Slot not found')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ASLOTEDIT-03: prefills times, active state, products, snippets and groups', async () => {
|
||||
it('ASLOTEDIT-03: prefills times, active state, products and groups', async () => {
|
||||
const view = await renderEditSlot()
|
||||
|
||||
expect(view.getByText('Edit Slot')).toBeTruthy()
|
||||
|
|
@ -55,8 +55,6 @@ describe('Edit slot (ASLOTEDIT-01..05)', () => {
|
|||
).toBeGreaterThanOrEqual(1)
|
||||
// The group selection is restored from the server payload.
|
||||
expect(await view.findByText('Breakfast')).toBeTruthy()
|
||||
// One snippet row is present for the slot's vendor snippet.
|
||||
expect(view.getByText('Snippet Name *')).toBeTruthy()
|
||||
expect(view.getByText('Update Slot')).toBeTruthy()
|
||||
})
|
||||
|
||||
|
|
@ -73,13 +71,6 @@ describe('Edit slot (ASLOTEDIT-01..05)', () => {
|
|||
isActive: true,
|
||||
groupIds: [1],
|
||||
skuIds: [2, 5],
|
||||
vendorSnippets: [
|
||||
{
|
||||
name: '',
|
||||
skuIds: [11],
|
||||
validTill: SLOT_DETAIL.vendorSnippets[0].validTill,
|
||||
},
|
||||
],
|
||||
})
|
||||
)
|
||||
await waitFor(() =>
|
||||
|
|
|
|||
|
|
@ -1,384 +0,0 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/**
|
||||
* Catalogue section 15 — Vendor snippets page
|
||||
* (`tests/pages/vendor-snippets.test.tsx`).
|
||||
*/
|
||||
import React from 'react'
|
||||
import { Alert, DeviceEventEmitter, Share } from 'react-native'
|
||||
import { fireEvent, waitFor } from '@testing-library/react-native'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
jest.mock('@/components/context/staff-auth-context', () =>
|
||||
require('../mocks/staff-auth-context')
|
||||
)
|
||||
|
||||
import VendorSnippets from '@/app/(drawer)/dashboard/vendor-snippets/index'
|
||||
import { __setStaffState } from '../mocks/staff-auth-context'
|
||||
import { renderAndFlush, renderWithProviders, flush } from '../helpers/test-utils'
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import {
|
||||
lastMutationInput,
|
||||
lastProcedureInput,
|
||||
procedureMutationCalls,
|
||||
setProcedure,
|
||||
} from '../mocks/trpc-client'
|
||||
import { router } from '../mocks/expo-router-mock'
|
||||
import {
|
||||
SLOT_1,
|
||||
SNIPPET_1,
|
||||
SNIPPET_ORDERS,
|
||||
SNIPPETS,
|
||||
STAFF,
|
||||
} from '../fixtures'
|
||||
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
|
||||
|
||||
async function renderPage() {
|
||||
const view = await renderAndFlush(<VendorSnippets />, { auth: false })
|
||||
await flush(2)
|
||||
return view
|
||||
}
|
||||
|
||||
type View = Awaited<ReturnType<typeof renderPage>>
|
||||
|
||||
function pressIcon(view: View, name: string, index = 0) {
|
||||
fireEvent.press(view.UNSAFE_getAllByProps({ name })[index])
|
||||
}
|
||||
|
||||
function openMenu(view: View) {
|
||||
pressIcon(view, 'dots-three-vertical')
|
||||
}
|
||||
|
||||
function confirmDelete(alertSpy: jest.SpyInstance) {
|
||||
const buttons = alertSpy.mock.calls[0][2] as any[]
|
||||
buttons.find((button: any) => button.text === 'Delete')?.onPress?.()
|
||||
}
|
||||
|
||||
describe('Vendor snippets page (AVENDUI-01..20)', () => {
|
||||
beforeEach(() => {
|
||||
resetAllMocks()
|
||||
__setStaffState({ isLoggedIn: true, isLoading: false, staff: STAFF })
|
||||
// The backend returns a bare array; the harness default is `{ snippets, count }`.
|
||||
setProcedure('admin.vendorSnippets.getAll', { data: SNIPPETS })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('AVENDUI-01: shows the loading copy', () => {
|
||||
setProcedure('admin.vendorSnippets.getAll', { mode: 'pending' })
|
||||
const view = renderWithProviders(<VendorSnippets />, { auth: false })
|
||||
|
||||
expect(view.getByText('Loading vendor snippets...')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-02: a failed query shows the error copy', async () => {
|
||||
setProcedure('admin.vendorSnippets.getAll', { mode: 'error', error: new Error('boom') })
|
||||
const view = await renderPage()
|
||||
|
||||
expect(view.getByText('Error loading snippets')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-03: an empty result shows the empty state and the add action', async () => {
|
||||
setProcedure('admin.vendorSnippets.getAll', { data: [] })
|
||||
const view = await renderPage()
|
||||
|
||||
expect(view.getByText('No Snippets Yet')).toBeTruthy()
|
||||
expect(
|
||||
view.getByText(
|
||||
'Start by creating your first vendor identifier using the button below.'
|
||||
)
|
||||
).toBeTruthy()
|
||||
|
||||
pressIcon(view, 'add')
|
||||
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-04: a snippet card shows code, slot, validity, products and share', async () => {
|
||||
const view = await renderPage()
|
||||
|
||||
expect(view.getByText('Identifier')).toBeTruthy()
|
||||
expect(view.getByText('ABC123')).toBeTruthy()
|
||||
expect(view.getByText('Active')).toBeTruthy()
|
||||
expect(view.getByText(dayjs(SLOT_1.deliveryTime).format('ddd, MMM DD'))).toBeTruthy()
|
||||
expect(
|
||||
view.getByText(`Time: ${dayjs(SLOT_1.deliveryTime).format('hh:mm A')}`)
|
||||
).toBeTruthy()
|
||||
expect(view.getByText('Expires')).toBeTruthy()
|
||||
expect(view.getByText(dayjs(SNIPPET_1.validTill).format('MMM DD'))).toBeTruthy()
|
||||
expect(view.getByText('1 Items')).toBeTruthy()
|
||||
expect(view.getByText('Share')).toBeTruthy()
|
||||
expect(view.getByText('View Slot')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-05: an expired snippet is badged as expired', async () => {
|
||||
const expired = {
|
||||
...SNIPPET_1,
|
||||
validTill: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
|
||||
}
|
||||
setProcedure('admin.vendorSnippets.getAll', {
|
||||
data: [expired],
|
||||
})
|
||||
const view = await renderPage()
|
||||
|
||||
expect(view.getByText('Expired')).toBeTruthy()
|
||||
expect(view.queryByText('Active')).toBeNull()
|
||||
})
|
||||
|
||||
it('AVENDUI-06: sharing a snippet without an access URL alerts', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'dismissedAction' } as any)
|
||||
setProcedure('admin.vendorSnippets.getAll', {
|
||||
data: [{ ...SNIPPET_1, accessUrl: null }],
|
||||
})
|
||||
const view = await renderPage()
|
||||
|
||||
fireEvent.press(view.getByText('Share'))
|
||||
|
||||
expect(alertSpy).toHaveBeenCalledWith('Error', 'No link available')
|
||||
expect(shareSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('AVENDUI-07: sharing a snippet hands the access URL to the share sheet', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' } as any)
|
||||
const view = await renderPage()
|
||||
|
||||
fireEvent.press(view.getByText('Share'))
|
||||
await waitFor(() => {
|
||||
expect(shareSpy).toHaveBeenCalledWith({ message: 'https://access.test/ABC123' })
|
||||
})
|
||||
expect(alertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('AVENDUI-08: the products count opens the product list dialog', async () => {
|
||||
const view = await renderPage()
|
||||
|
||||
fireEvent.press(view.getByText('1 Items'))
|
||||
|
||||
expect(view.getByText('Products (1)')).toBeTruthy()
|
||||
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-09: the View Slot action is currently inert', async () => {
|
||||
const view = await renderPage()
|
||||
|
||||
fireEvent.press(view.getByText('View Slot'))
|
||||
|
||||
// Catalogue gap #10: the slot navigation handler is `onPress={() => {}}`.
|
||||
expect(router.push).not.toHaveBeenCalled()
|
||||
expect(router.navigate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('AVENDUI-10: the add button creates a snippet and refetches', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const view = await renderPage()
|
||||
|
||||
pressIcon(view, 'add')
|
||||
await flush(2)
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE')
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
fireEvent.press(view.getByText('Select products'))
|
||||
fireEvent.press(view.getByText('Chicken Breast - 500g'))
|
||||
fireEvent.press(view.getByText('Done'))
|
||||
fireEvent.press(view.getByTestId('snippet-submit-button'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
|
||||
snippetCode: 'NEWCODE',
|
||||
slotId: undefined,
|
||||
isPermanent: true,
|
||||
skuIds: [11],
|
||||
validTill: undefined,
|
||||
})
|
||||
})
|
||||
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
|
||||
// onSuccess closes the form and returns to the list.
|
||||
await waitFor(() => {
|
||||
expect(view.queryByText('Create Vendor Snippet')).toBeNull()
|
||||
})
|
||||
expect(view.getByText('ABC123')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-11: Edit opens a prefilled form and updates the snippet', async () => {
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const view = await renderPage()
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('Edit'))
|
||||
|
||||
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
|
||||
expect(view.getByDisplayValue('ABC123')).toBeTruthy()
|
||||
|
||||
fireEvent.press(view.getByTestId('snippet-submit-button'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lastMutationInput('admin.vendorSnippets.update')).toEqual({
|
||||
id: 1,
|
||||
updates: {
|
||||
snippetCode: 'ABC123',
|
||||
slotId: 1849,
|
||||
isPermanent: false,
|
||||
skuIds: [11],
|
||||
validTill: SNIPPET_1.validTill,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('AVENDUI-12: Delete confirms then deletes and refetches', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
const view = await renderPage()
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('Delete'))
|
||||
|
||||
expect(alertSpy).toHaveBeenCalledWith(
|
||||
'Delete Snippet',
|
||||
'Are you sure you want to delete this vendor snippet?',
|
||||
expect.any(Array)
|
||||
)
|
||||
expect(procedureMutationCalls('admin.vendorSnippets.delete')).toHaveLength(0)
|
||||
|
||||
confirmDelete(alertSpy)
|
||||
await waitFor(() => {
|
||||
expect(lastMutationInput('admin.vendorSnippets.delete')).toEqual({ id: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
it('AVENDUI-13: a failing create/update/delete surfaces an alert', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
setProcedure('admin.vendorSnippets.create', { mode: 'error', error: new Error('save failed') })
|
||||
setProcedure('admin.vendorSnippets.update', { mode: 'error', error: new Error('update failed') })
|
||||
const view = await renderPage()
|
||||
|
||||
pressIcon(view, 'add')
|
||||
await flush(2)
|
||||
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE')
|
||||
fireEvent.press(view.getByText('Is Permanent?'))
|
||||
fireEvent.press(view.getByText('Select products'))
|
||||
fireEvent.press(view.getByText('Chicken Breast - 500g'))
|
||||
fireEvent.press(view.getByText('Done'))
|
||||
fireEvent.press(view.getByTestId('snippet-submit-button'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertSpy).toHaveBeenCalledWith('Error', 'save failed')
|
||||
})
|
||||
|
||||
// The failed create keeps the form open; close it and fail an update too.
|
||||
fireEvent.press(view.getByText('✕'))
|
||||
await flush()
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('Edit'))
|
||||
fireEvent.press(view.getByTestId('snippet-submit-button'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertSpy).toHaveBeenCalledWith('Error', 'update failed')
|
||||
})
|
||||
})
|
||||
|
||||
it('AVENDUI-14: View Orders fetches by snippet code and opens the orders view', async () => {
|
||||
setProcedure('admin.vendorSnippets.getOrdersBySnippet', { data: SNIPPET_ORDERS })
|
||||
const view = await renderPage()
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('View Orders'))
|
||||
await flush(2)
|
||||
|
||||
expect(lastProcedureInput('admin.vendorSnippets.getOrdersBySnippet')).toEqual({
|
||||
snippetCode: 'ABC123',
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(view.getByText('Orders for "ABC123"')).toBeTruthy()
|
||||
})
|
||||
expect(view.getByText('ORD-1011')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-15: a failed orders fetch alerts and stays on the list', async () => {
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
||||
setProcedure('admin.vendorSnippets.getOrdersBySnippet', {
|
||||
mode: 'error',
|
||||
error: new Error('orders boom'),
|
||||
})
|
||||
const view = await renderPage()
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('View Orders'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertSpy).toHaveBeenCalledWith('Error', 'orders boom')
|
||||
})
|
||||
expect(view.getByText('ABC123')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-16: no matching orders shows the empty orders view', async () => {
|
||||
setProcedure('admin.vendorSnippets.getOrdersBySnippet', {
|
||||
data: { ...SNIPPET_ORDERS, data: [] },
|
||||
})
|
||||
const view = await renderPage()
|
||||
|
||||
openMenu(view)
|
||||
fireEvent.press(view.getByText('View Orders'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(view.getByText('No matching orders')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
it('AVENDUI-17: a snippet without an access URL/slot renders without crashing', async () => {
|
||||
setProcedure('admin.vendorSnippets.getAll', {
|
||||
data: [{ ...SNIPPET_1, slot: null, validTill: null, isPermanent: true }],
|
||||
})
|
||||
const view = await renderPage()
|
||||
|
||||
expect(view.getByText('ABC123')).toBeTruthy()
|
||||
expect(view.getByText('Permanent')).toBeTruthy()
|
||||
expect(view.getByText('Always Active')).toBeTruthy()
|
||||
expect(view.getByText('View Slot')).toBeTruthy()
|
||||
expect(view.queryByText('Expires')).toBeNull()
|
||||
})
|
||||
|
||||
it('AVENDUI-18: the refresh shortcut is wired to refetch the list', async () => {
|
||||
const addListener = jest.spyOn(DeviceEventEmitter, 'addListener')
|
||||
const view = await renderPage()
|
||||
|
||||
// useManualRefresh subscribes the query refetch to REFRESH_EVENT.
|
||||
const refreshSubscriptions = addListener.mock.calls.filter(
|
||||
([eventName]) => eventName === REFRESH_EVENT
|
||||
)
|
||||
expect(refreshSubscriptions.length).toBeGreaterThanOrEqual(1)
|
||||
|
||||
// A manual refresh re-renders from the latest query payload without crashing.
|
||||
setProcedure('admin.vendorSnippets.getAll', {
|
||||
data: [{ ...SNIPPET_1, snippetCode: 'REFRESHED' }],
|
||||
})
|
||||
DeviceEventEmitter.emit(REFRESH_EVENT)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(view.getByText('REFRESHED')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
it('AVENDUI-19: the snippet menu exposes copy/edit/view/delete', async () => {
|
||||
const view = await renderPage()
|
||||
|
||||
openMenu(view)
|
||||
|
||||
expect(view.getByText('Snippet Options')).toBeTruthy()
|
||||
expect(view.getByText('View Orders')).toBeTruthy()
|
||||
expect(view.getByText('Edit')).toBeTruthy()
|
||||
expect(view.getByText('Copy URL')).toBeTruthy()
|
||||
expect(view.getByText('Delete')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AVENDUI-20: with no snippets the add action still creates one', async () => {
|
||||
setProcedure('admin.vendorSnippets.getAll', { data: [] })
|
||||
const view = await renderPage()
|
||||
|
||||
expect(view.getByText('No Snippets Yet')).toBeTruthy()
|
||||
pressIcon(view, 'add')
|
||||
|
||||
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
|
||||
expect(view.getByText('Snippet Code')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
import type { IdName } from '@packages/shared';
|
||||
import type { AdminVendorSnippetInput } from '@packages/shared'
|
||||
|
||||
export type VendorSnippetProduct = IdName;
|
||||
|
||||
export interface VendorSnippet {
|
||||
id: number;
|
||||
snippetCode: string;
|
||||
slotId: number | null;
|
||||
isPermanent: boolean;
|
||||
skuIds: number[];
|
||||
products: VendorSnippetProduct[];
|
||||
validTill: string | null;
|
||||
createdAt: string;
|
||||
accessUrl?: string;
|
||||
slot?: {
|
||||
id: number;
|
||||
deliveryTime: string;
|
||||
freezeTime: string;
|
||||
isActive: boolean;
|
||||
deliverySequence?: unknown;
|
||||
isFlash?: boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
// Vendor-snippet form row — anchored to the shared input (wire validTill);
|
||||
// form requires slotId and carries the serialized createdAt.
|
||||
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId'> & {
|
||||
id: number;
|
||||
slotId: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
import type { FC } from 'react'
|
||||
import { BottomDialog, p as P } from 'web-components'
|
||||
import type { IdName } from '@packages/shared'
|
||||
|
||||
type VendorSnippetProduct = IdName
|
||||
|
||||
interface ProductListDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
products: VendorSnippetProduct[]
|
||||
}
|
||||
|
||||
export const ProductListDialog: FC<ProductListDialogProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
products,
|
||||
}) => {
|
||||
return (
|
||||
<BottomDialog open={open} onClose={onClose}>
|
||||
<div className="pt-4 pb-8">
|
||||
<P className="text-lg font-bold mb-4 text-slate-900 block">
|
||||
Products ({products.length})
|
||||
</P>
|
||||
<div className="overflow-auto" style={{ maxHeight: 400 }}>
|
||||
{products.map((product, index) => (
|
||||
<div
|
||||
key={product.id}
|
||||
className={`py-3 border-b border-slate-100 ${index === products.length - 1 ? 'border-b-0' : ''}`}
|
||||
>
|
||||
<P className="text-sm text-slate-800 font-medium">
|
||||
{product.name}
|
||||
</P>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</BottomDialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,14 +1,10 @@
|
|||
import React from 'react'
|
||||
import type { SlotSnippetInput } from '@packages/shared'
|
||||
import { Formik, FieldArray } from 'formik'
|
||||
import { Formik } from 'formik'
|
||||
import DateTimeInput from './DateTimeInput'
|
||||
import { p as P, pInput as PInput } from 'web-components'
|
||||
import { trpc } from '@/lib/trpc-client'
|
||||
import ProductsSelector from './ProductsSelector'
|
||||
|
||||
// Snippet form row — single source in @packages/shared (complete payload)
|
||||
type VendorSnippet = SlotSnippetInput
|
||||
|
||||
interface SlotFormProps {
|
||||
onSlotAdded?: () => void
|
||||
initialDeliveryTime?: Date | null
|
||||
|
|
@ -33,19 +29,11 @@ export default function SlotForm({
|
|||
{ enabled: !!slotId }
|
||||
)
|
||||
|
||||
const vendorSnippetsFromSlot = (slotData?.slot?.vendorSnippets || []).map((snippet: any) => ({
|
||||
name: snippet.name || '',
|
||||
groupIds: snippet.groupIds || [],
|
||||
skuIds: snippet.skuIds || [],
|
||||
validTill: snippet.validTill || null,
|
||||
})) as VendorSnippet[]
|
||||
|
||||
const initialValues = {
|
||||
deliveryTime: initialDeliveryTime || (slotData?.slot?.deliveryTime ? new Date(slotData.slot.deliveryTime) : null),
|
||||
freezeTime: initialFreezeTime || (slotData?.slot?.freezeTime ? new Date(slotData.slot.freezeTime) : null),
|
||||
selectedGroupIds: initialGroupIds.length > 0 ? initialGroupIds : (slotData?.slot?.groupIds || []),
|
||||
selectedSkuIds: initialProductIds.length > 0 ? initialProductIds : (slotData?.slot?.products?.map((p: any) => p.id) || []),
|
||||
vendorSnippetList: vendorSnippetsFromSlot,
|
||||
}
|
||||
|
||||
const { mutate: createSlot, isPending: isCreating } = trpc.admin.slots.createSlot.useMutation()
|
||||
|
|
@ -73,11 +61,6 @@ export default function SlotForm({
|
|||
isActive: initialIsActive,
|
||||
groupIds: values.selectedGroupIds,
|
||||
skuIds: values.selectedSkuIds,
|
||||
vendorSnippets: values.vendorSnippetList.map((snippet: VendorSnippet) => ({
|
||||
name: snippet.name,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill ?? undefined,
|
||||
})),
|
||||
}
|
||||
|
||||
if (isEditMode && slotId) {
|
||||
|
|
@ -162,59 +145,6 @@ export default function SlotForm({
|
|||
/>
|
||||
</div>
|
||||
|
||||
{/* Vendor Snippets */}
|
||||
<FieldArray name="vendorSnippetList">
|
||||
{({ push, remove }) => (
|
||||
<div className="mb-4">
|
||||
<P className="text-lg font-semibold mb-4 block">Vendor Snippets</P>
|
||||
{values.vendorSnippetList.map((snippet: VendorSnippet, index: number) => (
|
||||
<div key={index} className="bg-gray-50 p-4 rounded-lg mb-4">
|
||||
<div className="mb-4">
|
||||
<PInput
|
||||
topLabel="Snippet Name *"
|
||||
placeholder="Enter snippet name"
|
||||
value={snippet.name}
|
||||
onChange={(e) => setFieldValue(`vendorSnippetList.${index}.name`, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<ProductsSelector
|
||||
value={snippet.skuIds || []}
|
||||
onChange={(newSkuIds) => setFieldValue(`vendorSnippetList.${index}.skuIds`, newSkuIds)}
|
||||
groups={mappedGroups.filter(group =>
|
||||
values.selectedGroupIds.includes(group.id)
|
||||
).map(group => ({
|
||||
...group,
|
||||
products: group.products.filter((prod: any) => values.selectedSkuIds.includes(prod.id))
|
||||
}))}
|
||||
selectedGroupIds={snippet.groupIds || []}
|
||||
onGroupChange={(newGroupIds) => setFieldValue(`vendorSnippetList.${index}.groupIds`, newGroupIds)}
|
||||
label="Select Products"
|
||||
placeholder="Select products for snippet"
|
||||
isDisabled={(sku) => !values.selectedSkuIds.includes(sku.id)}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => remove(index)}
|
||||
className="bg-red-500 px-4 py-2 rounded-lg self-end text-white font-medium"
|
||||
>
|
||||
Remove Snippet
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => push({ name: '', groupIds: [], skuIds: [], validTill: '' })}
|
||||
className="bg-blue-500 px-4 py-3 rounded-lg items-center text-white font-medium w-full"
|
||||
>
|
||||
Add Vendor Snippet
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</FieldArray>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
data-testid="create-slot-button"
|
||||
|
|
|
|||
|
|
@ -1,156 +0,0 @@
|
|||
import { useState, type FC } from 'react'
|
||||
import { p as P, BottomDialog } from 'web-components'
|
||||
import { SuccessToast } from '@/services/toaster'
|
||||
import type { VendorSnippet } from '@/types/vendor-snippets'
|
||||
import { Eye, Pencil, Link, Trash2, MoreVertical } from 'lucide-react'
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
export interface SnippetMenuOption {
|
||||
title: string
|
||||
icon: 'eye' | 'edit' | 'link' | 'trash'
|
||||
onPress: () => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export interface SnippetMenuProps {
|
||||
snippet: VendorSnippet
|
||||
onEdit: (snippet: VendorSnippet) => void
|
||||
onDelete: (id: number) => void
|
||||
onViewOrders: (snippetCode: string) => void
|
||||
triggerStyle?: any
|
||||
iconSize?: number
|
||||
iconColor?: string
|
||||
}
|
||||
|
||||
const iconMap = {
|
||||
eye: Eye,
|
||||
edit: Pencil,
|
||||
link: Link,
|
||||
trash: Trash2,
|
||||
}
|
||||
|
||||
export const SnippetMenu: FC<SnippetMenuProps> = ({
|
||||
snippet,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onViewOrders,
|
||||
triggerStyle = 'p-2 rounded-full bg-gray-50',
|
||||
iconSize = 16,
|
||||
iconColor = '#6B7280',
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
|
||||
const handleOpenMenu = () => {
|
||||
setIsOpen(true)
|
||||
}
|
||||
|
||||
const handleCloseMenu = () => {
|
||||
setIsOpen(false)
|
||||
}
|
||||
|
||||
const handleViewOrders = () => {
|
||||
setIsOpen(false)
|
||||
onViewOrders(snippet.snippetCode)
|
||||
}
|
||||
|
||||
const handleEdit = () => {
|
||||
setIsOpen(false)
|
||||
onEdit(snippet)
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
setIsOpen(false)
|
||||
const confirmed = window.confirm(
|
||||
'Delete Snippet? Are you sure you want to delete this vendor snippet?'
|
||||
)
|
||||
if (confirmed) {
|
||||
onDelete(snippet.id)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopyUrl = async () => {
|
||||
setIsOpen(false)
|
||||
if (!snippet.accessUrl) {
|
||||
window.alert('Error: No URL available to copy')
|
||||
return
|
||||
}
|
||||
await navigator.clipboard.writeText(snippet.accessUrl)
|
||||
SuccessToast('URL copied to clipboard')
|
||||
}
|
||||
|
||||
const options: SnippetMenuOption[] = [
|
||||
{
|
||||
title: 'View Orders',
|
||||
icon: 'eye',
|
||||
onPress: handleViewOrders,
|
||||
},
|
||||
{
|
||||
title: 'Edit',
|
||||
icon: 'edit',
|
||||
onPress: handleEdit,
|
||||
},
|
||||
{
|
||||
title: 'Copy URL',
|
||||
icon: 'link',
|
||||
onPress: handleCopyUrl,
|
||||
},
|
||||
{
|
||||
title: 'Delete',
|
||||
icon: 'trash',
|
||||
onPress: handleDelete,
|
||||
},
|
||||
]
|
||||
|
||||
const handleOptionPress = (option: SnippetMenuOption) => {
|
||||
if (option.disabled) return
|
||||
option.onPress()
|
||||
}
|
||||
|
||||
const triggerClassName = typeof triggerStyle === 'string' ? triggerStyle : 'p-2 rounded-full bg-gray-50'
|
||||
const triggerStyleObj: CSSProperties | undefined = typeof triggerStyle === 'object' ? triggerStyle : undefined
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Menu Trigger */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleOpenMenu}
|
||||
className={triggerClassName}
|
||||
style={triggerStyleObj}
|
||||
aria-label="Snippet options"
|
||||
>
|
||||
<MoreVertical size={iconSize} color={iconColor} />
|
||||
</button>
|
||||
|
||||
{/* Menu Dialog */}
|
||||
<BottomDialog open={isOpen} onClose={handleCloseMenu}>
|
||||
<div className="p-6">
|
||||
<P className="text-lg font-bold text-gray-800 mb-6 block">
|
||||
Snippet Options
|
||||
</P>
|
||||
|
||||
{options.map((option, index) => {
|
||||
const Icon = iconMap[option.icon]
|
||||
return (
|
||||
<button
|
||||
key={`${snippet.id}-${index}`}
|
||||
type="button"
|
||||
onClick={() => handleOptionPress(option)}
|
||||
disabled={option.disabled}
|
||||
className={`flex flex-row items-center p-4 bg-gray-50 rounded-lg w-full text-left ${index < options.length - 1 ? 'mb-3' : ''} ${option.disabled ? 'opacity-50' : ''}`}
|
||||
>
|
||||
<Icon
|
||||
size={20}
|
||||
color={option.disabled ? '#9CA3AF' : '#6B7280'}
|
||||
/>
|
||||
<P className={`font-medium ml-3 ${option.disabled ? 'text-gray-400' : 'text-gray-800'}`}>
|
||||
{option.title}
|
||||
</P>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</BottomDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,156 +0,0 @@
|
|||
import { Fragment, type FC } from 'react'
|
||||
import { p as P, AppContainer } from 'web-components'
|
||||
import { ShoppingCart } from 'lucide-react'
|
||||
import type {
|
||||
AdminVendorSnippetOrderProduct,
|
||||
AdminVendorSnippetOrderSummary as SharedSnippetOrderSummary,
|
||||
} from '@packages/shared'
|
||||
|
||||
// Line item + order summary anchored to the shared vendor-order contract
|
||||
// (string totalAmount + any[] sequence at this view layer)
|
||||
type OrderProduct = Pick<
|
||||
AdminVendorSnippetOrderProduct,
|
||||
'productId' | 'productName' | 'quantity' | 'price' | 'unit' | 'subtotal'
|
||||
>
|
||||
|
||||
type SnippetOrder = Omit<SharedSnippetOrderSummary, 'totalAmount' | 'slotInfo' | 'products'> & {
|
||||
totalAmount: string
|
||||
slotInfo: {
|
||||
time: string
|
||||
sequence: any[]
|
||||
} | null
|
||||
products: OrderProduct[]
|
||||
}
|
||||
|
||||
interface SnippetOrdersViewProps {
|
||||
orders: SnippetOrder[]
|
||||
snippetCode: string
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const OrderCard: FC<{ order: SnippetOrder; index: number }> = ({ order, index }) => {
|
||||
const orderDate = new Date(order.orderDate)
|
||||
const slotTime = order.slotInfo ? new Date(order.slotInfo.time) : null
|
||||
|
||||
return (
|
||||
<div className="py-6">
|
||||
{/* Order Header */}
|
||||
<div className="flex flex-row justify-between items-start mb-3">
|
||||
<div className="flex-1">
|
||||
<P className="font-bold text-gray-800 text-lg block">{order.orderId}</P>
|
||||
<P className="text-sm text-gray-600 block">{order.customerName}</P>
|
||||
</div>
|
||||
<div className="items-end text-right">
|
||||
<P className="font-bold text-green-600 block">₹{order.totalAmount}</P>
|
||||
<P className="text-xs text-gray-500 block">
|
||||
{orderDate.toLocaleDateString()}
|
||||
</P>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Slot Info */}
|
||||
{slotTime && (
|
||||
<div className="mb-3 p-2 bg-blue-50 rounded-lg">
|
||||
<P className="text-sm text-blue-800 font-medium">
|
||||
Delivery: {slotTime.toLocaleString()}
|
||||
</P>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Products */}
|
||||
<div className="mb-3">
|
||||
<P className="text-sm font-semibold text-gray-700 mb-2 block">Products:</P>
|
||||
{order.products.map((product, index) => {
|
||||
const isMatched = order.matchedProducts.includes(product.productId)
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={`flex flex-row justify-between items-center py-1 ${isMatched ? 'bg-yellow-50 px-2 rounded' : ''}`}
|
||||
>
|
||||
<div className="flex-1">
|
||||
<P className={`text-sm block ${isMatched ? 'font-semibold text-yellow-800' : 'text-gray-700'}`}>
|
||||
{product.productName}
|
||||
{isMatched && ' ⭐'}
|
||||
</P>
|
||||
<P className="text-xs text-gray-500 block">
|
||||
{product.quantity} {product.unit} × ₹{product.price}
|
||||
</P>
|
||||
</div>
|
||||
<P className={`text-sm font-medium ${isMatched ? 'text-yellow-800' : 'text-gray-700'}`}>
|
||||
₹{product.subtotal.toFixed(2)}
|
||||
</P>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Matched Products Summary */}
|
||||
<div className="p-2 bg-yellow-50 rounded-lg">
|
||||
<P className="text-xs text-yellow-700">
|
||||
Matched {order.matchedProducts.length} product(s) from snippet "{order.snippetCode}"
|
||||
</P>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SnippetOrdersView: FC<SnippetOrdersViewProps> = ({
|
||||
orders,
|
||||
snippetCode,
|
||||
onClose,
|
||||
}) => {
|
||||
const totalOrders = orders.length
|
||||
const totalRevenue = orders.reduce((sum, order) => sum + parseFloat(order.totalAmount), 0)
|
||||
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="flex-1 bg-gray-50">
|
||||
{/* Header */}
|
||||
<div className="px-6 py-4 bg-white border-b border-gray-200">
|
||||
<div className="flex flex-row justify-between items-center">
|
||||
<div className="flex-1">
|
||||
<P className="text-xl font-bold text-gray-800 block">Orders for "{snippetCode}"</P>
|
||||
<P className="text-gray-600 mt-1 block">
|
||||
{totalOrders} order{totalOrders !== 1 ? 's' : ''} • Total: ₹{totalRevenue.toFixed(2)}
|
||||
</P>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="p-2 text-gray-500 text-lg"
|
||||
aria-label="Close"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Orders List */}
|
||||
<div className="flex-1 overflow-auto px-6">
|
||||
{orders.length === 0 ? (
|
||||
<div className="flex-1 flex flex-col justify-center items-center py-12">
|
||||
<ShoppingCart className="h-16 w-16 text-gray-300" />
|
||||
<P className="text-gray-500 text-lg font-semibold mt-4">No matching orders</P>
|
||||
<P className="text-gray-400 text-center mt-2">
|
||||
No orders found that match this snippet's criteria
|
||||
</P>
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-4">
|
||||
{orders.map((order, index) => (
|
||||
<Fragment key={index}>
|
||||
<OrderCard order={order} index={index} />
|
||||
{index < orders.length - 1 && (
|
||||
<div className="h-px bg-slate-200 w-full" />
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
||||
export default SnippetOrdersView
|
||||
|
|
@ -1,230 +0,0 @@
|
|||
import { useEffect, type FC } from 'react'
|
||||
import { useFormik } from 'formik'
|
||||
import { p as P, Dropdown, pInput as PInput, Checkbox } from 'web-components'
|
||||
import ProductsSelector from './ProductsSelector'
|
||||
import DateInput from './DateInput'
|
||||
import { trpc } from '@/lib/trpc-client'
|
||||
import { useStaffAuth } from './context/staff-auth-context'
|
||||
import type { VendorSnippetForm as VendorSnippetFormType } from '@/types/vendor-snippets'
|
||||
|
||||
interface VendorSnippetFormProps {
|
||||
snippet?: VendorSnippetFormType | null
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
showIsPermanentCheckbox?: boolean
|
||||
}
|
||||
|
||||
const VendorSnippetForm: FC<VendorSnippetFormProps> = ({
|
||||
snippet,
|
||||
onClose,
|
||||
onSuccess,
|
||||
showIsPermanentCheckbox = false,
|
||||
}) => {
|
||||
|
||||
// Fetch the staff user's region's slots (getSlots now requires a region).
|
||||
const { regionId } = useStaffAuth()
|
||||
const { data: slotsData } = trpc.user.slots.getSlots.useQuery(
|
||||
{ regionId: regionId ?? 0 },
|
||||
{ enabled: regionId != null }
|
||||
)
|
||||
|
||||
const createSnippet = trpc.admin.vendorSnippets.create.useMutation()
|
||||
const updateSnippet = trpc.admin.vendorSnippets.update.useMutation()
|
||||
|
||||
const isEditing = !!snippet
|
||||
|
||||
const formik = useFormik({
|
||||
initialValues: {
|
||||
snippetCode: snippet?.snippetCode || '',
|
||||
slotId: snippet?.slotId?.toString() || '',
|
||||
isPermanent: snippet?.isPermanent || false,
|
||||
skuIds: snippet?.skuIds?.map(id => id.toString()) || [],
|
||||
validTill: snippet?.validTill ? new Date(snippet.validTill) : null,
|
||||
},
|
||||
validate: (values) => {
|
||||
const errors: {[key: string]: string} = {}
|
||||
|
||||
if (!values.snippetCode.trim()) {
|
||||
errors.snippetCode = 'Snippet code is required'
|
||||
}
|
||||
|
||||
// Validate snippet code only contains alphanumeric characters and underscore
|
||||
const snippetCodeRegex = /^[a-zA-Z0-9_]+$/
|
||||
if (values.snippetCode && !snippetCodeRegex.test(values.snippetCode)) {
|
||||
errors.snippetCode = 'Snippet code can only contain letters, numbers, and underscores'
|
||||
}
|
||||
|
||||
// Only require slotId if isPermanent is false
|
||||
if (!values.isPermanent && !values.slotId) {
|
||||
errors.slotId = 'Slot selection is required'
|
||||
}
|
||||
|
||||
if (values.skuIds.length === 0) {
|
||||
errors.skuIds = 'At least one product must be selected'
|
||||
}
|
||||
|
||||
return errors
|
||||
},
|
||||
onSubmit: async (values) => {
|
||||
try {
|
||||
|
||||
const submitData = {
|
||||
snippetCode: values.snippetCode,
|
||||
slotId: values.isPermanent ? undefined : parseInt(values.slotId || '0'),
|
||||
isPermanent: values.isPermanent,
|
||||
skuIds: values.skuIds.map(id => parseInt(id)),
|
||||
validTill: values.validTill ? values.validTill.toISOString() : undefined,
|
||||
}
|
||||
|
||||
if (isEditing && snippet) {
|
||||
await updateSnippet.mutateAsync({
|
||||
id: snippet.id,
|
||||
updates: submitData,
|
||||
})
|
||||
window.alert('Success: Vendor snippet updated successfully')
|
||||
} else {
|
||||
await createSnippet.mutateAsync(submitData)
|
||||
window.alert('Success: Vendor snippet created successfully')
|
||||
}
|
||||
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (error: any) {
|
||||
window.alert(`Error: ${error.message || 'Failed to save vendor snippet'}`)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
// Generate unique snippet code if creating new (only on mount)
|
||||
useEffect(() => {
|
||||
if (!isEditing && !formik.values.snippetCode) {
|
||||
const timestamp = Date.now()
|
||||
const random = Math.random().toString(36).substring(2, 8)
|
||||
formik.setFieldValue('snippetCode', `VS_${timestamp}_${random}`)
|
||||
}
|
||||
}, [isEditing]) // Removed formik.values.snippetCode from deps
|
||||
|
||||
const slotOptions = slotsData?.slots.map(slot => ({
|
||||
label: new Date(slot.deliveryTime).toLocaleString(),
|
||||
value: slot.id.toString(),
|
||||
})) || []
|
||||
|
||||
return (
|
||||
<div className="flex-1 bg-white">
|
||||
<div className="px-6 py-4 border-b border-gray-200">
|
||||
<div className="flex flex-row justify-between items-center">
|
||||
<P className="text-xl font-bold text-gray-800">
|
||||
{isEditing ? 'Edit Vendor Snippet' : 'Create Vendor Snippet'}
|
||||
</P>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="p-2 text-gray-500 text-lg"
|
||||
aria-label="Close"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-auto px-6">
|
||||
<div className="py-6 space-y-6">
|
||||
{/* Snippet Code */}
|
||||
<div>
|
||||
<PInput
|
||||
topLabel="Snippet Code"
|
||||
value={formik.values.snippetCode}
|
||||
onChange={formik.handleChange('snippetCode')}
|
||||
placeholder="Enter snippet code"
|
||||
error={!!formik.errors.snippetCode && !!formik.touched.snippetCode}
|
||||
/>
|
||||
{formik.errors.snippetCode && formik.touched.snippetCode && (
|
||||
<P className="text-red-500 text-sm mt-1">{formik.errors.snippetCode}</P>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Is Permanent Checkbox */}
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => formik.setFieldValue('isPermanent', !formik.values.isPermanent)}
|
||||
className="flex flex-row items-center mb-2"
|
||||
>
|
||||
<Checkbox
|
||||
checked={formik.values.isPermanent}
|
||||
onPress={() => formik.setFieldValue('isPermanent', !formik.values.isPermanent)}
|
||||
/>
|
||||
<P className="text-gray-700 font-medium ml-3">Is Permanent?</P>
|
||||
</button>
|
||||
<P className="text-sm text-gray-500 block">
|
||||
Check if this snippet is permanent and not tied to a specific delivery slot
|
||||
</P>
|
||||
</div>
|
||||
|
||||
{/* Slot Selection - Only show if not permanent */}
|
||||
{!formik.values.isPermanent && (
|
||||
<div>
|
||||
<P className="text-gray-700 font-medium mb-2 block">Delivery Slot</P>
|
||||
<Dropdown
|
||||
label="Select Slot"
|
||||
value={formik.values.slotId}
|
||||
options={slotOptions}
|
||||
onValueChange={(value) => formik.setFieldValue('slotId', String(value))}
|
||||
className="w-full"
|
||||
/>
|
||||
{formik.errors.slotId && formik.touched.slotId && (
|
||||
<P className="text-red-500 text-sm mt-1">{formik.errors.slotId}</P>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Product Selection */}
|
||||
<div>
|
||||
<ProductsSelector
|
||||
value={formik.values.skuIds.map(id => parseInt(id))}
|
||||
onChange={(selectedProductIds) => formik.setFieldValue('skuIds', (selectedProductIds as number[]).map(id => id.toString()))}
|
||||
multiple={true}
|
||||
label="Select Products"
|
||||
placeholder="Select products"
|
||||
labelFormat={(product) => product.label}
|
||||
/>
|
||||
{formik.errors.skuIds && formik.touched.skuIds && (
|
||||
<P className="text-red-500 text-sm mt-1">{formik.errors.skuIds}</P>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Valid Till Date */}
|
||||
<div>
|
||||
<P className="text-gray-700 font-medium mb-2 block">Valid Till (Optional)</P>
|
||||
<DateInput
|
||||
value={formik.values.validTill}
|
||||
setValue={(date) => formik.setFieldValue('validTill', date)}
|
||||
placeholder="Select expiry date"
|
||||
showLabel={false}
|
||||
/>
|
||||
<P className="text-sm text-gray-500 mt-1 block">
|
||||
Leave empty for no expiry
|
||||
</P>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="px-6 py-4 border-t border-gray-200">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => formik.handleSubmit()}
|
||||
disabled={formik.isSubmitting}
|
||||
className={`bg-blue-500 py-3 rounded-lg w-full text-white text-center font-semibold disabled:opacity-50 ${formik.isSubmitting ? 'opacity-50' : ''}`}
|
||||
>
|
||||
{formik.isSubmitting
|
||||
? 'Saving...'
|
||||
: isEditing ? 'Update Snippet' : 'Create Snippet'
|
||||
}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VendorSnippetForm
|
||||
|
|
@ -34,8 +34,8 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
|
|||
const location = useLocation()
|
||||
|
||||
// Only the JWT survives a reload. Restore the staff identity (and therefore
|
||||
// regionId) from the authenticated endpoint so region-scoped screens such as
|
||||
// the vendor-snippet slot picker are not permanently disabled until re-login.
|
||||
// regionId) from the authenticated endpoint so region-scoped screens are not
|
||||
// permanently disabled until re-login.
|
||||
const meQuery = trpc.admin.staffUser.me.useQuery(undefined, {
|
||||
enabled: isLoggedIn,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import { Route as LoginRouteImport } from './routes/login'
|
|||
import { Route as DashboardRouteImport } from './routes/dashboard'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as DashboardIndexRouteImport } from './routes/dashboard.index'
|
||||
import { Route as DashboardVendorSnippetsRouteImport } from './routes/dashboard.vendor-snippets'
|
||||
import { Route as DashboardUsersRouteImport } from './routes/dashboard.users'
|
||||
import { Route as DashboardStoresRouteImport } from './routes/dashboard.stores'
|
||||
import { Route as DashboardSlotsRouteImport } from './routes/dashboard.slots'
|
||||
|
|
@ -73,11 +72,6 @@ const DashboardIndexRoute = DashboardIndexRouteImport.update({
|
|||
path: '/',
|
||||
getParentRoute: () => DashboardRoute,
|
||||
} as any)
|
||||
const DashboardVendorSnippetsRoute = DashboardVendorSnippetsRouteImport.update({
|
||||
id: '/vendor-snippets',
|
||||
path: '/vendor-snippets',
|
||||
getParentRoute: () => DashboardRoute,
|
||||
} as any)
|
||||
const DashboardUsersRoute = DashboardUsersRouteImport.update({
|
||||
id: '/users',
|
||||
path: '/users',
|
||||
|
|
@ -295,7 +289,6 @@ export interface FileRoutesByFullPath {
|
|||
'/dashboard/slots': typeof DashboardSlotsRouteWithChildren
|
||||
'/dashboard/stores': typeof DashboardStoresRouteWithChildren
|
||||
'/dashboard/users': typeof DashboardUsersRouteWithChildren
|
||||
'/dashboard/vendor-snippets': typeof DashboardVendorSnippetsRoute
|
||||
'/dashboard/': typeof DashboardIndexRoute
|
||||
'/dashboard/banners/new': typeof DashboardBannersNewRoute
|
||||
'/dashboard/coupons/new': typeof DashboardCouponsNewRoute
|
||||
|
|
@ -339,7 +332,6 @@ export interface FileRoutesByTo {
|
|||
'/dashboard/slots': typeof DashboardSlotsRouteWithChildren
|
||||
'/dashboard/stores': typeof DashboardStoresRouteWithChildren
|
||||
'/dashboard/users': typeof DashboardUsersRouteWithChildren
|
||||
'/dashboard/vendor-snippets': typeof DashboardVendorSnippetsRoute
|
||||
'/dashboard': typeof DashboardIndexRoute
|
||||
'/dashboard/banners/new': typeof DashboardBannersNewRoute
|
||||
'/dashboard/coupons/new': typeof DashboardCouponsNewRoute
|
||||
|
|
@ -385,7 +377,6 @@ export interface FileRoutesById {
|
|||
'/dashboard/slots': typeof DashboardSlotsRouteWithChildren
|
||||
'/dashboard/stores': typeof DashboardStoresRouteWithChildren
|
||||
'/dashboard/users': typeof DashboardUsersRouteWithChildren
|
||||
'/dashboard/vendor-snippets': typeof DashboardVendorSnippetsRoute
|
||||
'/dashboard/': typeof DashboardIndexRoute
|
||||
'/dashboard/banners/new': typeof DashboardBannersNewRoute
|
||||
'/dashboard/coupons/new': typeof DashboardCouponsNewRoute
|
||||
|
|
@ -432,7 +423,6 @@ export interface FileRouteTypes {
|
|||
| '/dashboard/slots'
|
||||
| '/dashboard/stores'
|
||||
| '/dashboard/users'
|
||||
| '/dashboard/vendor-snippets'
|
||||
| '/dashboard/'
|
||||
| '/dashboard/banners/new'
|
||||
| '/dashboard/coupons/new'
|
||||
|
|
@ -476,7 +466,6 @@ export interface FileRouteTypes {
|
|||
| '/dashboard/slots'
|
||||
| '/dashboard/stores'
|
||||
| '/dashboard/users'
|
||||
| '/dashboard/vendor-snippets'
|
||||
| '/dashboard'
|
||||
| '/dashboard/banners/new'
|
||||
| '/dashboard/coupons/new'
|
||||
|
|
@ -521,7 +510,6 @@ export interface FileRouteTypes {
|
|||
| '/dashboard/slots'
|
||||
| '/dashboard/stores'
|
||||
| '/dashboard/users'
|
||||
| '/dashboard/vendor-snippets'
|
||||
| '/dashboard/'
|
||||
| '/dashboard/banners/new'
|
||||
| '/dashboard/coupons/new'
|
||||
|
|
@ -585,13 +573,6 @@ declare module '@tanstack/react-router' {
|
|||
preLoaderRoute: typeof DashboardIndexRouteImport
|
||||
parentRoute: typeof DashboardRoute
|
||||
}
|
||||
'/dashboard/vendor-snippets': {
|
||||
id: '/dashboard/vendor-snippets'
|
||||
path: '/vendor-snippets'
|
||||
fullPath: '/dashboard/vendor-snippets'
|
||||
preLoaderRoute: typeof DashboardVendorSnippetsRouteImport
|
||||
parentRoute: typeof DashboardRoute
|
||||
}
|
||||
'/dashboard/users': {
|
||||
id: '/dashboard/users'
|
||||
path: '/users'
|
||||
|
|
@ -1023,7 +1004,6 @@ interface DashboardRouteChildren {
|
|||
DashboardSlotsRoute: typeof DashboardSlotsRouteWithChildren
|
||||
DashboardStoresRoute: typeof DashboardStoresRouteWithChildren
|
||||
DashboardUsersRoute: typeof DashboardUsersRouteWithChildren
|
||||
DashboardVendorSnippetsRoute: typeof DashboardVendorSnippetsRoute
|
||||
DashboardIndexRoute: typeof DashboardIndexRoute
|
||||
}
|
||||
|
||||
|
|
@ -1042,7 +1022,6 @@ const DashboardRouteChildren: DashboardRouteChildren = {
|
|||
DashboardSlotsRoute: DashboardSlotsRouteWithChildren,
|
||||
DashboardStoresRoute: DashboardStoresRouteWithChildren,
|
||||
DashboardUsersRoute: DashboardUsersRouteWithChildren,
|
||||
DashboardVendorSnippetsRoute: DashboardVendorSnippetsRoute,
|
||||
DashboardIndexRoute: DashboardIndexRoute,
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import React, { useState } from 'react'
|
||||
import React from 'react'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { p as MyText, BottomDialog } from 'web-components'
|
||||
import { p as MyText } from 'web-components'
|
||||
import { trpc } from '@/lib/trpc-client'
|
||||
import { ErrorToast } from '@/services/toaster'
|
||||
import { theme } from '@/lib/theme'
|
||||
import { Code2, ShoppingBag, Link2, Clock, Package, Pencil } from 'lucide-react'
|
||||
import { Package, Pencil } from 'lucide-react'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
export const Route = createFileRoute('/dashboard/slots/detail')({
|
||||
|
|
@ -24,11 +23,6 @@ function SlotDetails() {
|
|||
|
||||
const slot = slotData?.slot
|
||||
const products = slot?.products || []
|
||||
const vendorSnippets = slot?.vendorSnippets || []
|
||||
|
||||
// Dialog state for snippet products
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [dialogProducts, setDialogProducts] = useState<any[]>([])
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
|
|
@ -71,104 +65,6 @@ function SlotDetails() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Vendor Snippets Section */}
|
||||
<div className="mb-8">
|
||||
<div className="mb-4 flex flex-row items-center justify-between">
|
||||
<MyText className="text-lg font-bold text-gray-900">Vendor Snippets</MyText>
|
||||
<span className="rounded-full bg-gray-100 px-2 py-1">
|
||||
<MyText className="text-xs font-medium text-gray-600">{vendorSnippets.length} snippets</MyText>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{vendorSnippets.length === 0 ? (
|
||||
<div className="items-center rounded-lg bg-gray-50 p-6 text-center">
|
||||
<Code2 size={32} color="#9CA3AF" className="mx-auto" />
|
||||
<MyText className="mt-2 block text-center text-gray-500">No vendor snippets for this slot</MyText>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{vendorSnippets.map((snippet, index) => {
|
||||
const isExpired = snippet.validTill && dayjs(snippet.validTill).isBefore(dayjs())
|
||||
|
||||
return (
|
||||
<div key={snippet.id} className="rounded-lg bg-gray-50 p-4">
|
||||
<div className="mb-3 flex flex-row items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<MyText className="block font-bold text-gray-900" numberOfLines={1}>
|
||||
{snippet.snippetCode}
|
||||
</MyText>
|
||||
</div>
|
||||
<div className="flex flex-row items-center">
|
||||
<span className={`rounded-full px-2 py-1 ${isExpired ? 'bg-red-100' : 'bg-green-100'}`}>
|
||||
<MyText className={`text-xs font-medium ${isExpired ? 'text-red-700' : 'text-green-700'}`}>
|
||||
{isExpired ? 'Expired' : 'Active'}
|
||||
</MyText>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-row items-center justify-between">
|
||||
<div className="flex flex-row items-center">
|
||||
<button
|
||||
onClick={() => {
|
||||
const snippetProducts = products.filter((p) => snippet.skuIds.includes(p.id))
|
||||
setDialogProducts(snippetProducts)
|
||||
setDialogOpen(true)
|
||||
}}
|
||||
className="mr-4 flex flex-row items-center"
|
||||
>
|
||||
<ShoppingBag size={14} color="#94A3B8" />
|
||||
<MyText className="ml-1 text-xs font-medium text-blue-600 underline">
|
||||
{snippet.skuIds.length} products
|
||||
</MyText>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
if (navigator.share) {
|
||||
await navigator.share({ text: snippet.accessUrl })
|
||||
} else {
|
||||
await navigator.clipboard.writeText(snippet.accessUrl)
|
||||
window.alert('Link copied to clipboard')
|
||||
}
|
||||
} catch (err) {
|
||||
ErrorToast('Failed to share link')
|
||||
}
|
||||
}}
|
||||
className="flex flex-row items-center"
|
||||
>
|
||||
<Link2 size={14} color={theme.colors.brand500} />
|
||||
<MyText className="ml-1 text-xs font-medium text-brand-600">
|
||||
Share
|
||||
</MyText>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{snippet.validTill && (
|
||||
<span className="flex flex-row items-center">
|
||||
<Clock size={14} color="#94A3B8" />
|
||||
<MyText className="ml-1 text-xs font-medium text-gray-600">
|
||||
Expires {dayjs(snippet.validTill).format('MMM DD')}
|
||||
</MyText>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{snippet.createdAt && (
|
||||
<div className="mt-2 border-t border-gray-200 pt-2">
|
||||
<MyText className="block text-xs text-gray-500">
|
||||
Created {dayjs(snippet.createdAt).format('MMM DD, YYYY')}
|
||||
</MyText>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Products Section */}
|
||||
<div className="mb-8">
|
||||
<div className="mb-4 flex flex-row items-center justify-between">
|
||||
|
|
@ -207,33 +103,6 @@ function SlotDetails() {
|
|||
<Pencil size={24} color="white" />
|
||||
</button>
|
||||
|
||||
<BottomDialog open={dialogOpen} onClose={() => setDialogOpen(false)}>
|
||||
<div className="py-4">
|
||||
<MyText className="mb-4 block text-center text-lg font-semibold">Snippet Products</MyText>
|
||||
<div className="max-h-80 overflow-y-auto">
|
||||
{dialogProducts.length === 0 ? (
|
||||
<div className="items-center px-4 py-8 text-center">
|
||||
<MyText className="block text-center text-gray-500">
|
||||
No products found for this snippet
|
||||
</MyText>
|
||||
</div>
|
||||
) : (
|
||||
dialogProducts.map((product) => (
|
||||
<div key={product.id} className="border-b border-gray-100 px-4 py-3">
|
||||
<MyText className="block text-base font-medium text-gray-900">
|
||||
{product.name}
|
||||
</MyText>
|
||||
{product.shortDescription && (
|
||||
<MyText className="mt-1 block text-sm text-gray-600">
|
||||
{product.shortDescription}
|
||||
</MyText>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</BottomDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import {
|
|||
TriangleAlert,
|
||||
ShoppingBag,
|
||||
TicketPercent,
|
||||
Code2,
|
||||
Store,
|
||||
Users,
|
||||
Megaphone,
|
||||
|
|
@ -37,7 +36,6 @@ const SCREEN_TITLES: Record<string, string> = {
|
|||
complaints: 'Complaints',
|
||||
orders: 'Manage Orders',
|
||||
coupons: 'Coupons',
|
||||
'vendor-snippets': 'Vendor Snippets',
|
||||
stores: 'Stores',
|
||||
users: 'User Management',
|
||||
notifications: 'Send Notifications',
|
||||
|
|
@ -63,7 +61,6 @@ const SIDEBAR_ENTRIES: SidebarEntry[] = [
|
|||
{ label: 'Complaints', to: '/dashboard/complaints', icon: <TriangleAlert size={22} /> },
|
||||
{ label: 'Manage Orders', to: '/dashboard/orders', icon: <ShoppingBag size={22} /> },
|
||||
{ label: 'Coupons', to: '/dashboard/coupons', icon: <TicketPercent size={22} /> },
|
||||
{ label: 'Vendor Snippets', to: '/dashboard/vendor-snippets', icon: <Code2 size={22} /> },
|
||||
{ label: 'Stores', to: '/dashboard/stores', icon: <Store size={22} /> },
|
||||
{ label: 'User Management', to: '/dashboard/users', icon: <Users size={22} /> },
|
||||
{ label: 'Send Notifications', to: '/dashboard/notifications', icon: <Megaphone size={22} /> },
|
||||
|
|
|
|||
|
|
@ -1,421 +0,0 @@
|
|||
import React, { useState } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { AppContainer, p as MyText, div as MyTouchableOpacity } from 'web-components'
|
||||
import { useManualRefresh, useMarkDataFetchers } from '@/lib/refresh-context'
|
||||
import { theme } from '@/lib/theme'
|
||||
import { trpc, getTrpcClient } from '@/lib/trpc-client'
|
||||
import { Fingerprint, CalendarCheck, ShoppingBag, Link2, ChevronRight, Plus, Code2 } from 'lucide-react'
|
||||
import dayjs from 'dayjs'
|
||||
import VendorSnippetForm from '../components/VendorSnippetForm'
|
||||
import SnippetOrdersView from '../components/SnippetOrdersView'
|
||||
import { SnippetMenu } from '../components/SnippetMenu'
|
||||
import { ProductListDialog } from '../components/ProductListDialog'
|
||||
import type {
|
||||
VendorSnippet,
|
||||
VendorSnippetProduct,
|
||||
VendorSnippetForm as VendorSnippetFormType,
|
||||
} from '@/types/vendor-snippets'
|
||||
|
||||
export const Route = createFileRoute('/dashboard/vendor-snippets')({
|
||||
component: VendorSnippets,
|
||||
})
|
||||
|
||||
const SnippetItem = ({
|
||||
snippet,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onViewOrders,
|
||||
onViewProducts,
|
||||
index,
|
||||
}: {
|
||||
snippet: VendorSnippet
|
||||
onEdit: (snippet: VendorSnippet) => void
|
||||
onDelete: (id: number) => void
|
||||
onViewOrders: (snippetCode: string) => void
|
||||
onViewProducts: (products: VendorSnippetProduct[]) => void
|
||||
index: number
|
||||
}) => {
|
||||
|
||||
const isExpired =
|
||||
snippet.validTill && dayjs(snippet.validTill).isBefore(dayjs())
|
||||
|
||||
const handleCopyLink = async () => {
|
||||
try {
|
||||
if (!snippet.accessUrl) {
|
||||
window.alert('Error: No link available')
|
||||
return
|
||||
}
|
||||
if (typeof navigator.share === 'function') {
|
||||
await navigator.share({ text: snippet.accessUrl })
|
||||
} else {
|
||||
await navigator.clipboard.writeText(snippet.accessUrl)
|
||||
window.alert('Link copied to clipboard')
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error?.name === 'AbortError') return
|
||||
window.alert('Error: Failed to share link')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="p-6">
|
||||
<div className="mb-6 flex-row flex items-start justify-between">
|
||||
<div className="flex-row flex flex-1 items-center">
|
||||
<div
|
||||
className="mr-4 flex h-12 w-12 items-center justify-center rounded-2xl"
|
||||
style={{ backgroundColor: theme.colors.brand50 }}
|
||||
>
|
||||
<Fingerprint
|
||||
size={24}
|
||||
color={theme.colors.brand600}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<MyText
|
||||
className="text-[10px] font-black uppercase tracking-widest text-slate-400"
|
||||
>
|
||||
Identifier
|
||||
</MyText>
|
||||
<MyText
|
||||
className="text-xl font-black text-slate-900"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{snippet.snippetCode}
|
||||
</MyText>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-row flex items-center">
|
||||
<div
|
||||
className="mr-2 flex-row flex items-center rounded-full px-3 py-1.5"
|
||||
style={{ backgroundColor: isExpired ? '#FFF1F2' : '#F0FDF4' }}
|
||||
>
|
||||
<span
|
||||
className="mr-2 h-1.5 w-1.5 rounded-full"
|
||||
style={{ backgroundColor: isExpired ? '#E11D48' : '#10B981' }}
|
||||
/>
|
||||
<MyText
|
||||
className="text-[10px] font-black uppercase tracking-tighter"
|
||||
style={{ color: isExpired ? '#E11D48' : '#10B981' }}
|
||||
>
|
||||
{isExpired ? 'Expired' : 'Active'}
|
||||
</MyText>
|
||||
</div>
|
||||
<SnippetMenu
|
||||
snippet={snippet}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onViewOrders={onViewOrders}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="mb-6 flex-row flex items-center rounded-3xl border border-slate-100 bg-slate-50 p-4"
|
||||
>
|
||||
<div
|
||||
className="flex h-10 w-10 items-center justify-center rounded-2xl bg-white shadow-sm"
|
||||
>
|
||||
<CalendarCheck size={20} color="#64748B" />
|
||||
</div>
|
||||
<div className="ml-4 flex-1">
|
||||
{snippet.isPermanent ? (
|
||||
<>
|
||||
<MyText className="text-sm font-extrabold text-slate-900">
|
||||
Permanent
|
||||
</MyText>
|
||||
<MyText className="text-[10px] font-bold uppercase text-slate-500">
|
||||
Always Active
|
||||
</MyText>
|
||||
</>
|
||||
) : snippet.slot?.deliveryTime ? (
|
||||
<>
|
||||
<MyText className="text-sm font-extrabold text-slate-900">
|
||||
{dayjs(snippet.slot.deliveryTime).format('ddd, MMM DD')}
|
||||
</MyText>
|
||||
<MyText className="text-[10px] font-bold uppercase text-slate-500">
|
||||
Time: {dayjs(snippet.slot.deliveryTime).format('hh:mm A')}
|
||||
</MyText>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<MyText className="text-sm font-extrabold text-slate-900">
|
||||
Schedule Pending
|
||||
</MyText>
|
||||
<MyText className="text-[10px] font-bold uppercase text-slate-500">
|
||||
N/A
|
||||
</MyText>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{snippet.validTill && (
|
||||
<div className="items-end">
|
||||
<MyText className="text-[9px] font-bold uppercase text-slate-400">
|
||||
Expires
|
||||
</MyText>
|
||||
<MyText
|
||||
className="text-xs font-black"
|
||||
style={{ color: isExpired ? '#E11D48' : '#64748B' }}
|
||||
>
|
||||
{dayjs(snippet.validTill).format('MMM DD')}
|
||||
</MyText>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-row flex items-center justify-between">
|
||||
<div className="flex-row flex items-center">
|
||||
<MyTouchableOpacity
|
||||
onClick={() => onViewProducts(snippet.products)}
|
||||
className="mr-4 flex-row items-center"
|
||||
>
|
||||
<ShoppingBag size={14} color="#94A3B8" />
|
||||
<MyText className="ml-1.5 text-xs font-bold text-slate-500">
|
||||
{snippet.skuIds.length} Items
|
||||
</MyText>
|
||||
<ChevronRight size={14} color="#94A3B8" />
|
||||
</MyTouchableOpacity>
|
||||
<MyTouchableOpacity
|
||||
onClick={handleCopyLink}
|
||||
className="flex-row items-center"
|
||||
>
|
||||
<Link2
|
||||
size={16}
|
||||
color={theme.colors.brand500}
|
||||
/>
|
||||
<MyText
|
||||
className="ml-1 text-xs font-black"
|
||||
style={{ color: theme.colors.brand600 }}
|
||||
>
|
||||
Share
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</div>
|
||||
|
||||
<MyTouchableOpacity
|
||||
onClick={() => {}}
|
||||
activeOpacity={0.7}
|
||||
className="flex-row items-center"
|
||||
>
|
||||
<MyText
|
||||
className="text-xs font-black uppercase tracking-widest text-slate-900"
|
||||
>
|
||||
View Slot
|
||||
</MyText>
|
||||
<ChevronRight size={16} color="#000" />
|
||||
</MyTouchableOpacity>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function VendorSnippets() {
|
||||
const {
|
||||
data: snippets,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = trpc.admin.vendorSnippets.getAll.useQuery()
|
||||
|
||||
const createSnippet = trpc.admin.vendorSnippets.create.useMutation()
|
||||
const updateSnippet = trpc.admin.vendorSnippets.update.useMutation()
|
||||
const deleteSnippet = trpc.admin.vendorSnippets.delete.useMutation()
|
||||
|
||||
void createSnippet
|
||||
void updateSnippet
|
||||
|
||||
const [showCreateForm, setShowCreateForm] = useState(false)
|
||||
const [editingSnippet, setEditingSnippet] =
|
||||
useState<VendorSnippetFormType | null>(null)
|
||||
const [showOrdersView, setShowOrdersView] = useState(false)
|
||||
const [ordersData, setOrdersData] = useState<any>(null)
|
||||
const [showProductList, setShowProductList] = useState(false)
|
||||
const [selectedProducts, setSelectedProducts] = useState<VendorSnippetProduct[] | null>(null)
|
||||
|
||||
useManualRefresh(() => {
|
||||
void refetch()
|
||||
})
|
||||
|
||||
useMarkDataFetchers(() => {
|
||||
refetch()
|
||||
})
|
||||
|
||||
const handleCreate = () => {
|
||||
setShowCreateForm(true)
|
||||
setEditingSnippet(null)
|
||||
}
|
||||
|
||||
const handleViewProducts = (products: VendorSnippetProduct[]) => {
|
||||
setSelectedProducts(products)
|
||||
setShowProductList(true)
|
||||
}
|
||||
|
||||
const handleEdit = (snippet: VendorSnippet) => {
|
||||
const formSnippet: VendorSnippetFormType = {
|
||||
id: snippet.id,
|
||||
snippetCode: snippet.snippetCode,
|
||||
slotId: snippet.slotId || 0,
|
||||
isPermanent: snippet.isPermanent,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill,
|
||||
createdAt: snippet.createdAt,
|
||||
}
|
||||
setEditingSnippet(formSnippet)
|
||||
setShowCreateForm(true)
|
||||
}
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
deleteSnippet.mutate(
|
||||
{ id },
|
||||
{
|
||||
onSuccess: () => {
|
||||
refetch()
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const handleViewOrders = async (snippetCode: string) => {
|
||||
try {
|
||||
const trpcClient = getTrpcClient()
|
||||
const result =
|
||||
await trpcClient.admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode,
|
||||
})
|
||||
if (result.success) {
|
||||
setOrdersData({
|
||||
orders: result.data,
|
||||
snippetCode: snippetCode,
|
||||
})
|
||||
setShowOrdersView(true)
|
||||
} else {
|
||||
window.alert('Error: Failed to fetch orders')
|
||||
}
|
||||
} catch (error: any) {
|
||||
window.alert(`Error: ${error.message || 'Failed to fetch orders'}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<MyText className="text-gray-600">Loading vendor snippets...</MyText>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<AppContainer>
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<MyText className="text-red-600">Error loading snippets</MyText>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
||||
if (showOrdersView && ordersData) {
|
||||
return (
|
||||
<SnippetOrdersView
|
||||
orders={ordersData.orders}
|
||||
snippetCode={ordersData.snippetCode}
|
||||
onClose={() => {
|
||||
setShowOrdersView(false)
|
||||
setOrdersData(null)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (showCreateForm) {
|
||||
return (
|
||||
<VendorSnippetForm
|
||||
snippet={editingSnippet}
|
||||
onClose={() => {
|
||||
setShowCreateForm(false)
|
||||
setEditingSnippet(null)
|
||||
}}
|
||||
onSuccess={() => {
|
||||
setShowCreateForm(false)
|
||||
setEditingSnippet(null)
|
||||
refetch()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppContainer>
|
||||
<div className="h-full flex-1 bg-white">
|
||||
<div
|
||||
className="flex-1 pb-32 pt-2"
|
||||
>
|
||||
{snippets && snippets.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center py-20">
|
||||
<div
|
||||
className="mb-6 flex h-24 w-24 items-center justify-center rounded-full bg-slate-50"
|
||||
>
|
||||
<Code2 size={48} color="#94A3B8" />
|
||||
</div>
|
||||
<MyText
|
||||
className="text-xl font-black tracking-tight text-slate-900"
|
||||
>
|
||||
No Snippets Yet
|
||||
</MyText>
|
||||
<MyText
|
||||
className="mt-2 px-8 text-center font-medium text-slate-500"
|
||||
>
|
||||
Start by creating your first vendor identifier using the
|
||||
button below.
|
||||
</MyText>
|
||||
</div>
|
||||
) : (
|
||||
snippets?.map((snippet, index) => (
|
||||
<React.Fragment key={snippet.id}>
|
||||
<SnippetItem
|
||||
snippet={snippet}
|
||||
index={index}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onViewOrders={handleViewOrders}
|
||||
onViewProducts={handleViewProducts}
|
||||
/>
|
||||
{index < snippets.length - 1 && (
|
||||
<div className="h-px w-full bg-slate-200" />
|
||||
)}
|
||||
</React.Fragment>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</AppContainer>
|
||||
<MyTouchableOpacity
|
||||
onClick={handleCreate}
|
||||
activeOpacity={0.95}
|
||||
className="fixed bottom-8 right-6 z-50 shadow-2xl"
|
||||
aria-label="Create vendor snippet"
|
||||
>
|
||||
<span
|
||||
className="flex h-16 w-16 items-center justify-center shadow-lg"
|
||||
style={{
|
||||
borderRadius: 24,
|
||||
background: 'linear-gradient(135deg, #1570EF, #194185)',
|
||||
}}
|
||||
>
|
||||
<Plus size={32} color="white" />
|
||||
</span>
|
||||
</MyTouchableOpacity>
|
||||
<ProductListDialog
|
||||
open={showProductList}
|
||||
onClose={() => setShowProductList(false)}
|
||||
products={selectedProducts || []}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
import type { IdName } from '@packages/shared';
|
||||
import type { AdminVendorSnippetInput } from '@packages/shared'
|
||||
|
||||
export type VendorSnippetProduct = IdName;
|
||||
|
||||
export interface VendorSnippet {
|
||||
id: number;
|
||||
snippetCode: string;
|
||||
slotId: number | null;
|
||||
isPermanent: boolean;
|
||||
skuIds: number[];
|
||||
products: VendorSnippetProduct[];
|
||||
validTill: string | null;
|
||||
createdAt: string;
|
||||
accessUrl?: string;
|
||||
slot?: {
|
||||
id: number;
|
||||
deliveryTime: string;
|
||||
freezeTime: string;
|
||||
isActive: boolean;
|
||||
deliverySequence?: unknown;
|
||||
isFlash?: boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
// Vendor-snippet form row — anchored to the shared input (wire validTill);
|
||||
// form requires slotId and carries the serialized createdAt.
|
||||
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId'> & {
|
||||
id: number;
|
||||
slotId: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -252,11 +252,11 @@ Apply these to every procedure in the groups below. The row is the expected resu
|
|||
|
||||
| ID | Group | Procedures | Expected |
|
||||
| --- | --- | --- | --- |
|
||||
| AUTH-01 | public | `common.healthCheck`, `common.listRegions`, `common.checkLocationInPolygon`, `common.resolveRegionByLocation`, `common.resolveBound`, `common.regionSettings`, `common.activeBound`, `common.essentialConsts`, `user.auth.*` public, `admin.staffUser.login`, `superadmin.auth.login`, `vendorSnippets` public reads | succeeds without token |
|
||||
| AUTH-01 | public | `common.healthCheck`, `common.listRegions`, `common.checkLocationInPolygon`, `common.resolveRegionByLocation`, `common.resolveBound`, `common.regionSettings`, `common.activeBound`, `common.essentialConsts`, `user.auth.*` public, `admin.staffUser.login`, `superadmin.auth.login` | succeeds without token |
|
||||
| AUTH-02 | user protected | every `user.*` protected procedure except public ones | 401 UNAUTHORIZED |
|
||||
| AUTH-03 | admin/staff reads | every `admin.*` `protectedProcedure` read | user token may pass (current gap); no token 401; staff passes |
|
||||
| AUTH-04 | admin/staff writes | every `admin.*` `protectedProcedure` mutation | user token may pass today (current gap); no token 401; staff passes |
|
||||
| AUTH-05 | staff-only | `admin.banner.createBanner`, `admin.product.createProduct`, `admin.product.createGroup`, `admin.product.createProductTag`, `admin.store.createStore`, `admin.staffUser.me`, `admin.staffUser.sendAdminNotification`, `admin.vendorSnippets.create`, every `admin.region.*` | no token/user token/superadmin 401; staff passes |
|
||||
| AUTH-05 | staff-only | `admin.banner.createBanner`, `admin.product.createProduct`, `admin.product.createGroup`, `admin.product.createProductTag`, `admin.store.createStore`, `admin.staffUser.me`, `admin.staffUser.sendAdminNotification`, every `admin.region.*` | no token/user token/superadmin 401; staff passes |
|
||||
| AUTH-06 | authenticated-any | `common.generateUploadUrls` | user, staff and superadmin pass; anonymous 401 |
|
||||
| AUTH-07 | superadmin-only | every `superadmin.*` procedure | user/staff 401; superadmin passes |
|
||||
| AUTH-08 | cross-principal | staff token on `user.order.getOrders` | rejected |
|
||||
|
|
@ -404,7 +404,7 @@ availability ${assetsDomain}regions/${regionId}/av-${availability_version_n
|
|||
| CACHE-73 | cache | capacity restored | version increments; slot returns |
|
||||
| CACHE-74 | edge | cross-region slot | absent |
|
||||
| CACHE-75 | edge | slot with no products | present with empty products |
|
||||
| CACHE-76 | edge | unknown vendor snippet/group ids | slot still created or 400 per DB validation; assert current |
|
||||
| CACHE-76 | edge | unknown group ids | silently normalised to [] |
|
||||
|
||||
### 4.5 availability.json
|
||||
|
||||
|
|
@ -1284,17 +1284,15 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
|
|||
| --- | --- | --- | --- |
|
||||
| ASLOT-01 | happy | getAll | ≤20 slots, region only |
|
||||
| ASLOT-02 | edge | >20 slots | cap 20 |
|
||||
| ASLOT-03 | happy | create slot | slot + products/snippets/groups |
|
||||
| ASLOT-03 | happy | create slot | slot + products/groups |
|
||||
| ASLOT-04 | error | missing times | 400 |
|
||||
| ASLOT-05 | edge | invalid date strings | current DB/parse behavior |
|
||||
| ASLOT-06 | edge | no skus | empty slot |
|
||||
| ASLOT-07 | error | invalid sku | DB/validation error |
|
||||
| ASLOT-08 | edge | vendor snippets | created/access URL |
|
||||
| ASLOT-09 | edge | duplicate vendor snippet name? | assert current |
|
||||
| ASLOT-10 | cache | create | slots version sync |
|
||||
| ASLOT-11 | happy | getSlotById | slot/snippets/accessUrl |
|
||||
| ASLOT-11 | happy | getSlotById | slot + products |
|
||||
| ASLOT-12 | error | unknown | 404 |
|
||||
| ASLOT-13 | happy | update slot | times/products/snippets |
|
||||
| ASLOT-13 | happy | update slot | times/products |
|
||||
| ASLOT-14 | error | unknown | current catch masks to 500 `Unable to Update Slot` |
|
||||
| ASLOT-15 | cache | update | slots version sync |
|
||||
| ASLOT-16 | happy | getDeliverySequence | sequence map |
|
||||
|
|
@ -1362,45 +1360,6 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
|
|||
| AUSER-25 | edge | user token | current gap |
|
||||
| AUSER-26 | edge | cross-region user | not found/empty |
|
||||
|
||||
### 7.11 `admin.vendorSnippets`
|
||||
|
||||
| ID | Type | Case | Assert |
|
||||
| --- | --- | --- | --- |
|
||||
| AVEND-01 | happy | create with slot/skus | snippet |
|
||||
| AVEND-02 | error | missing code | BAD_REQUEST |
|
||||
| AVEND-03 | error | no skus | BAD_REQUEST |
|
||||
| AVEND-04 | error | invalid slot | error |
|
||||
| AVEND-05 | error | invalid/foreign sku | error |
|
||||
| AVEND-06 | error | duplicate code | error |
|
||||
| AVEND-07 | edge | no slot | allowed; orders endpoint later errors |
|
||||
| AVEND-08 | edge | validTill/isPermanent | stored |
|
||||
| AVEND-09 | happy | getAll | snippets + products/accessUrl |
|
||||
| AVEND-10 | edge | empty | [] |
|
||||
| AVEND-11 | happy | update | fields/slot/skus/code |
|
||||
| AVEND-12 | error | unknown | not found |
|
||||
| AVEND-13 | error | invalid slot/sku | error |
|
||||
| AVEND-14 | error | duplicate code | error |
|
||||
| AVEND-15 | happy | delete | success |
|
||||
| AVEND-16 | error | unknown | error |
|
||||
| AVEND-17 | happy | getOrdersBySnippet | orders filtered to snippet SKUs |
|
||||
| AVEND-18 | error | unknown code | error |
|
||||
| AVEND-19 | error | expired | error |
|
||||
| AVEND-20 | error | no slot | `not associated with a slot` |
|
||||
| AVEND-21 | edge | cancelled orders | excluded |
|
||||
| AVEND-22 | edge | orders without snippet SKUs | excluded |
|
||||
| AVEND-23 | edge | no customer name | empty string |
|
||||
| AVEND-24 | edge | public | no auth needed |
|
||||
| AVEND-25 | happy | getUpcomingSlots | slots after now-3h |
|
||||
| AVEND-26 | edge | no slots | [] |
|
||||
| AVEND-27 | happy | getOrdersBySnippetAndSlot | filtered by slot |
|
||||
| AVEND-28 | error | unknown snippet/slot | error |
|
||||
| AVEND-29 | happy | updateOrderItemPackaging | is_packaged changes |
|
||||
| AVEND-30 | error | unknown item | error |
|
||||
| AVEND-31 | edge | public packaging mutation | current no auth — security gap |
|
||||
| AVEND-32 | edge | cross-region snippet | public lookup global; assert |
|
||||
|
||||
---
|
||||
|
||||
## 8. Superadmin router
|
||||
|
||||
### 8.1 `superadmin.auth`
|
||||
|
|
@ -1667,14 +1626,13 @@ data. Minimum matrix:
|
|||
|
||||
| ID | Type | Case | Assert |
|
||||
| --- | --- | --- | --- |
|
||||
| ISO-01 | invariant | admin store/product/slot/user/order/banner/tag/coupon/vendor reads | only staff region |
|
||||
| ISO-01 | invariant | admin store/product/slot/user/order/banner/tag/coupon reads | only staff region |
|
||||
| ISO-02 | invariant | user product/slot/store/cache reads | only requested region |
|
||||
| ISO-03 | invariant | address/store/product/slot/order writes with foreign region id | reject or not visible |
|
||||
| ISO-04 | invariant | cache files | no foreign ids |
|
||||
| ISO-05 | invariant | notifications | token follows address region, not browsing region |
|
||||
| ISO-06 | invariant | global product/store | visible in every region’s cache |
|
||||
| ISO-07 | invariant | superadmin complaint/products | explicitly global |
|
||||
| ISO-08 | invariant | vendor public links | global lookup by code, expected |
|
||||
|
||||
### 11.2 Transactions and partial failure
|
||||
|
||||
|
|
@ -1869,14 +1827,6 @@ and side-effect tests. Use this table as the completion gate.
|
|||
| admin.user | sendNotification | AUSER-15..19, NOTIF-01..06 |
|
||||
| admin.user | getUserIncidents | AUSER-20..21 |
|
||||
| admin.user | addUserIncident | AUSER-22..26 |
|
||||
| admin.vendorSnippets | create | AVEND-01..08 |
|
||||
| admin.vendorSnippets | getAll | AVEND-09..10 |
|
||||
| admin.vendorSnippets | update | AVEND-11..14 |
|
||||
| admin.vendorSnippets | delete | AVEND-15..16 |
|
||||
| admin.vendorSnippets | getOrdersBySnippet | AVEND-17..24 |
|
||||
| admin.vendorSnippets | getUpcomingSlots | AVEND-25..26 |
|
||||
| admin.vendorSnippets | getOrdersBySnippetAndSlot | AVEND-27..28 |
|
||||
| admin.vendorSnippets | updateOrderItemPackaging | AVEND-29..32 |
|
||||
| superadmin.auth | login | SAUTH-01..04 |
|
||||
| superadmin.auth | me | SAUTH-05..09 |
|
||||
| superadmin.const | getGlobalConstants | SCONST-01 |
|
||||
|
|
@ -1939,7 +1889,6 @@ These are intentionally written as “current” cases until the underlying defe
|
|||
7. `placeOrder` has no idempotency key and no quantity upper bound.
|
||||
8. Empty `selectedItems` falls through to a raw DB error.
|
||||
9. A user can raise a complaint against another user’s order id.
|
||||
10. Vendor snippet packaging endpoints and order lookup are public by design; treat as a security review item.
|
||||
11. Suspended-user handling in `createContext` swallows the `TRPCError`, so requests look anonymous rather than 403.
|
||||
12. `getOrderById`/`cancelOrder`/`updateUserNotes` accept only numeric-string ids; `ORD` display ids fail.
|
||||
13. Cart/checkout area identity uses address coordinates; a stale client `regionId` must not win.
|
||||
|
|
@ -1959,7 +1908,7 @@ These are intentionally written as “current” cases until the underlying defe
|
|||
4. User auth/address/cart.
|
||||
5. User order + product + coupon.
|
||||
6. Admin product/store/slot/banner/tag.
|
||||
7. Admin order/coupon/user/vendor.
|
||||
7. Admin order/coupon/user.
|
||||
8. Superadmin.
|
||||
9. Uploads/S3.
|
||||
10. Cache invariants + concurrency + cross-region isolation.
|
||||
|
|
|
|||
|
|
@ -138,7 +138,6 @@ const statements: string[] = [
|
|||
`DELETE FROM notif_creds WHERE user_id IN (${TEST_USERS}) OR region_id IN (${TEST_REGIONS});`,
|
||||
`DELETE FROM unlogged_user_tokens WHERE region_id IN (${TEST_REGIONS});`,
|
||||
`DELETE FROM staff_notif_creds WHERE staff_user_id IN (${TEST_STAFF});`,
|
||||
`DELETE FROM vendor_snippets WHERE region_id IN (${TEST_REGIONS}) OR created_at >= ${S};`,
|
||||
`DELETE FROM home_banners WHERE region_id IN (${TEST_REGIONS}) OR created_at >= ${S};`,
|
||||
`DELETE FROM product_tag_info WHERE region_id IN (${TEST_REGIONS}) OR created_at >= ${S};`,
|
||||
`DELETE FROM product_group_info WHERE region_id IN (${TEST_REGIONS}) OR created_at >= ${S};`,
|
||||
|
|
|
|||
|
|
@ -59,8 +59,6 @@ export type {
|
|||
AdminDeliverySlot,
|
||||
AdminSlotProductSummary,
|
||||
AdminSlotWithProducts,
|
||||
AdminSlotWithProductsAndSnippets,
|
||||
AdminSlotWithProductsAndSnippetsBase,
|
||||
AdminSlotsResult,
|
||||
AdminSlotsListResult,
|
||||
AdminSlotResult,
|
||||
|
|
@ -71,20 +69,6 @@ export type {
|
|||
AdminDeliverySequenceResult,
|
||||
AdminUpdateDeliverySequenceResult,
|
||||
AdminUpdateSlotCapacityResult,
|
||||
AdminVendorSnippet,
|
||||
AdminVendorSnippetWithAccess,
|
||||
AdminVendorSnippetWithSlot,
|
||||
AdminVendorSnippetProduct,
|
||||
AdminVendorSnippetWithProducts,
|
||||
AdminVendorSnippetInput,
|
||||
AdminVendorSnippetDeleteResult,
|
||||
AdminVendorSnippetOrderProduct,
|
||||
AdminVendorSnippetOrderSummary,
|
||||
AdminVendorSnippetOrdersResult,
|
||||
AdminVendorSnippetOrdersWithSlotResult,
|
||||
AdminVendorOrderSummary,
|
||||
AdminUpcomingSlotsResult,
|
||||
AdminVendorUpdatePackagingResult,
|
||||
UserAddress,
|
||||
UserAddressResponse,
|
||||
UserAddressesResponse,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { refreshGenKv } from '@/src/lib/gen-store'
|
|||
import { ensureWorkerInit } from '@/src/lib/worker-init'
|
||||
|
||||
|
||||
const CRON_TURN_OFF_FLASH_DELIVERY = '0 16 * * *' // 9:30 PM IST
|
||||
const CRON_TURN_OFF_FLASH_DELIVERY = '0 15 * * *' // 8:30 PM IST
|
||||
const CRON_TURN_ON_FLASH_DELIVERY = '0 1 * * *' // 6:30 PM IST
|
||||
|
||||
export async function runFlashDeliveryToggleCron(params: {
|
||||
|
|
|
|||
|
|
@ -132,18 +132,6 @@ export {
|
|||
getNotifTokensByUserIds,
|
||||
getUserIncidentsWithRelations,
|
||||
createUserIncident,
|
||||
// Admin - Vendor Snippets
|
||||
checkVendorSnippetExists,
|
||||
getVendorSnippetById,
|
||||
getVendorSnippetByCode,
|
||||
getAllVendorSnippets,
|
||||
createVendorSnippet,
|
||||
updateVendorSnippet,
|
||||
deleteVendorSnippet,
|
||||
getProductsByIds,
|
||||
getVendorSlotById,
|
||||
getVendorOrdersBySlotId,
|
||||
updateVendorOrderItemPackaging,
|
||||
// User - Address
|
||||
getUserDefaultAddress,
|
||||
getUserAddresses,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import { router } from '@/src/trpc/trpc-index'
|
|||
import { complaintRouter } from '@/src/trpc/apis/admin-apis/apis/complaint'
|
||||
import { couponRouter } from '@/src/trpc/apis/admin-apis/apis/coupon'
|
||||
import { orderRouter } from '@/src/trpc/apis/admin-apis/apis/order'
|
||||
import { vendorSnippetsRouter } from '@/src/trpc/apis/admin-apis/apis/vendor-snippets'
|
||||
import { slotsRouter } from '@/src/trpc/apis/admin-apis/apis/slots'
|
||||
import { productRouter } from '@/src/trpc/apis/admin-apis/apis/product'
|
||||
import { staffUserRouter } from '@/src/trpc/apis/admin-apis/apis/staff-user'
|
||||
|
|
@ -16,7 +15,6 @@ export const adminRouter = router({
|
|||
complaint: complaintRouter,
|
||||
coupon: couponRouter,
|
||||
order: orderRouter,
|
||||
vendorSnippets: vendorSnippetsRouter,
|
||||
slots: slotsRouter,
|
||||
product: productRouter,
|
||||
staffUser: staffUserRouter,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { router, protectedProcedure } from "@/src/trpc/trpc-index"
|
|||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { ApiError } from "@/src/lib/api-error"
|
||||
import { getAppUrl } from "@/src/lib/env-exporter"
|
||||
// import redisClient from "@/src/lib/redis-client"
|
||||
// import { getSlotSequenceKey } from "@/src/lib/redisKeyGetters"
|
||||
import { createSlotsCacheFile } from '@/src/lib/cloud_cache'
|
||||
|
|
@ -35,12 +34,6 @@ const createSlotSchema = z.object({
|
|||
freezeTime: z.string(),
|
||||
isActive: z.boolean().optional(),
|
||||
skuIds: z.array(z.number()).optional(),
|
||||
vendorSnippets: z.array(z.object({
|
||||
name: z.string().min(1),
|
||||
skuIds: z.array(z.number().int().positive()).min(1),
|
||||
validTill: z.string().optional(),
|
||||
groupIds: z.array(z.number()).optional(),
|
||||
})).optional(),
|
||||
groupIds: z.array(z.number()).optional(),
|
||||
});
|
||||
|
||||
|
|
@ -54,12 +47,6 @@ const updateSlotSchema = z.object({
|
|||
freezeTime: z.string(),
|
||||
isActive: z.boolean().optional(),
|
||||
skuIds: z.array(z.number()).optional(),
|
||||
vendorSnippets: z.array(z.object({
|
||||
name: z.string().min(1),
|
||||
skuIds: z.array(z.number().int().positive()).min(1),
|
||||
validTill: z.string().optional(),
|
||||
groupIds: z.array(z.number()).optional(),
|
||||
})).optional(),
|
||||
groupIds: z.array(z.number()).optional(),
|
||||
});
|
||||
|
||||
|
|
@ -97,7 +84,7 @@ export const slotsRouter = router({
|
|||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
|
||||
}
|
||||
|
||||
const { deliveryTime, freezeTime, isActive, skuIds, vendorSnippets: snippets, groupIds } = input;
|
||||
const { deliveryTime, freezeTime, isActive, skuIds, groupIds } = input;
|
||||
|
||||
// Validate required fields
|
||||
if (!deliveryTime || !freezeTime) {
|
||||
|
|
@ -109,13 +96,6 @@ export const slotsRouter = router({
|
|||
freezeTime,
|
||||
isActive,
|
||||
skuIds,
|
||||
// Complete SlotSnippetInput payloads — groupIds unused by sqlite but
|
||||
// always sent; absent validTill becomes null.
|
||||
vendorSnippets: snippets?.map((snippet) => ({
|
||||
...snippet,
|
||||
groupIds: snippet.groupIds ?? [],
|
||||
validTill: snippet.validTill ?? null,
|
||||
})),
|
||||
groupIds,
|
||||
}, ctx.staffUser.regionId)
|
||||
|
||||
|
|
@ -150,13 +130,7 @@ export const slotsRouter = router({
|
|||
}
|
||||
|
||||
return {
|
||||
slot: {
|
||||
...slot,
|
||||
vendorSnippets: slot.vendorSnippets.map(snippet => ({
|
||||
...snippet,
|
||||
accessUrl: `${getAppUrl()}/vendor-order-list?id=${snippet.snippetCode}`,
|
||||
})),
|
||||
},
|
||||
slot,
|
||||
}
|
||||
}),
|
||||
|
||||
|
|
@ -167,7 +141,7 @@ export const slotsRouter = router({
|
|||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
|
||||
}
|
||||
try{
|
||||
const { id, deliveryTime, freezeTime, isActive, skuIds, vendorSnippets: snippets, groupIds } = input;
|
||||
const { id, deliveryTime, freezeTime, isActive, skuIds, groupIds } = input;
|
||||
|
||||
if (!deliveryTime || !freezeTime) {
|
||||
throw new ApiError("Delivery time and orders close time are required", 400);
|
||||
|
|
@ -179,13 +153,6 @@ export const slotsRouter = router({
|
|||
freezeTime,
|
||||
isActive,
|
||||
skuIds,
|
||||
// Complete SlotSnippetInput payloads — groupIds unused by sqlite but
|
||||
// always sent; absent validTill becomes null.
|
||||
vendorSnippets: snippets?.map((snippet) => ({
|
||||
...snippet,
|
||||
groupIds: snippet.groupIds ?? [],
|
||||
validTill: snippet.validTill ?? null,
|
||||
})),
|
||||
groupIds,
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1,388 +0,0 @@
|
|||
import { router, publicProcedure, protectedProcedure, staffProcedure } from '@/src/trpc/trpc-index'
|
||||
import { z } from 'zod'
|
||||
import dayjs from 'dayjs'
|
||||
import { getAppUrl } from '@/src/lib/env-exporter'
|
||||
import {
|
||||
checkVendorSnippetExists as checkVendorSnippetExistsInDb,
|
||||
getVendorSnippetById as getVendorSnippetByIdInDb,
|
||||
getVendorSnippetByCode as getVendorSnippetByCodeInDb,
|
||||
getAllVendorSnippets as getAllVendorSnippetsInDb,
|
||||
createVendorSnippet as createVendorSnippetInDb,
|
||||
updateVendorSnippet as updateVendorSnippetInDb,
|
||||
deleteVendorSnippet as deleteVendorSnippetInDb,
|
||||
getProductsByIds as getProductsByIdsInDb,
|
||||
getVendorSlotById as getVendorSlotByIdInDb,
|
||||
getVendorOrdersBySlotId as getVendorOrdersBySlotIdInDb,
|
||||
updateVendorOrderItemPackaging as updateVendorOrderItemPackagingInDb,
|
||||
getSlotsAfterDate as getSlotsAfterDateInDb,
|
||||
composeSkuName,
|
||||
composeUnitNotation,
|
||||
} from '@/src/dbService'
|
||||
import type {
|
||||
AdminVendorSnippet,
|
||||
AdminVendorSnippetWithProducts,
|
||||
AdminVendorSnippetDeleteResult,
|
||||
AdminVendorSnippetOrdersResult,
|
||||
AdminVendorSnippetOrdersWithSlotResult,
|
||||
AdminUpcomingSlotsResult,
|
||||
AdminVendorUpdatePackagingResult,
|
||||
} from '@packages/shared'
|
||||
|
||||
const createSnippetSchema = z.object({
|
||||
snippetCode: z.string().min(1, "Snippet code is required"),
|
||||
slotId: z.number().optional(),
|
||||
skuIds: z.array(z.number().int().positive()).min(1, "At least one product is required"),
|
||||
validTill: z.string().optional(),
|
||||
isPermanent: z.boolean().default(false)
|
||||
});
|
||||
|
||||
const updateSnippetSchema = z.object({
|
||||
id: z.number().int().positive(),
|
||||
updates: createSnippetSchema.partial().extend({
|
||||
snippetCode: z.string().min(1).optional(),
|
||||
skuIds: z.array(z.number().int().positive()).optional(),
|
||||
isPermanent: z.boolean().default(false)
|
||||
}),
|
||||
});
|
||||
|
||||
export const vendorSnippetsRouter = router({
|
||||
create: staffProcedure
|
||||
.input(createSnippetSchema)
|
||||
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippet> => {
|
||||
const { snippetCode, slotId, skuIds, validTill, isPermanent } = input;
|
||||
|
||||
// Get staff user ID from auth middleware
|
||||
const staffUserId = ctx.staffUser?.id;
|
||||
if (!staffUserId) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
if(slotId) {
|
||||
const slot = await getVendorSlotByIdInDb(ctx.staffUser!.regionId, slotId)
|
||||
if (!slot) {
|
||||
throw new Error("Invalid slot ID")
|
||||
}
|
||||
}
|
||||
|
||||
const products = await getProductsByIdsInDb(ctx.staffUser!.regionId, skuIds)
|
||||
if (products.length !== skuIds.length) {
|
||||
throw new Error("One or more invalid product IDs")
|
||||
}
|
||||
|
||||
const existingSnippet = await checkVendorSnippetExistsInDb(snippetCode)
|
||||
if (existingSnippet) {
|
||||
throw new Error("Snippet code already exists")
|
||||
}
|
||||
|
||||
const result = await createVendorSnippetInDb({
|
||||
snippetCode,
|
||||
slotId,
|
||||
skuIds,
|
||||
isPermanent,
|
||||
validTill: validTill ? new Date(validTill) : undefined,
|
||||
regionId: ctx.staffUser!.regionId,
|
||||
})
|
||||
|
||||
return result
|
||||
}),
|
||||
|
||||
getAll: protectedProcedure
|
||||
.query(async ({ ctx }): Promise<AdminVendorSnippetWithProducts[]> => {
|
||||
console.log('from the vendor snipptes methods')
|
||||
|
||||
try {
|
||||
const result = await getAllVendorSnippetsInDb(ctx.staffUser!.regionId)
|
||||
|
||||
const snippetsWithProducts = await Promise.all(
|
||||
result.map(async (snippet) => {
|
||||
const products = await getProductsByIdsInDb(ctx.staffUser!.regionId, snippet.skuIds)
|
||||
|
||||
return {
|
||||
...snippet,
|
||||
accessUrl: `${getAppUrl()}/vendor-order-list?id=${snippet.snippetCode}`,
|
||||
products,
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
return snippetsWithProducts
|
||||
}
|
||||
catch(e) {
|
||||
console.log(e)
|
||||
}
|
||||
return []
|
||||
}),
|
||||
|
||||
update: protectedProcedure
|
||||
.input(updateSnippetSchema)
|
||||
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippet> => {
|
||||
const { id, updates } = input;
|
||||
|
||||
const existingSnippet = await getVendorSnippetByIdInDb(ctx.staffUser!.regionId, id)
|
||||
if (!existingSnippet) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
}
|
||||
|
||||
if (updates.slotId) {
|
||||
const slot = await getVendorSlotByIdInDb(ctx.staffUser!.regionId, updates.slotId)
|
||||
if (!slot) {
|
||||
throw new Error('Invalid slot ID')
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.skuIds) {
|
||||
const products = await getProductsByIdsInDb(ctx.staffUser!.regionId, updates.skuIds)
|
||||
if (products.length !== updates.skuIds.length) {
|
||||
throw new Error('One or more invalid product IDs')
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.snippetCode && updates.snippetCode !== existingSnippet.snippetCode) {
|
||||
const duplicateSnippet = await checkVendorSnippetExistsInDb(updates.snippetCode)
|
||||
if (duplicateSnippet) {
|
||||
throw new Error('Snippet code already exists')
|
||||
}
|
||||
}
|
||||
|
||||
const updateData = {
|
||||
...updates,
|
||||
validTill: updates.validTill !== undefined
|
||||
? (updates.validTill ? new Date(updates.validTill) : null)
|
||||
: undefined,
|
||||
}
|
||||
|
||||
const result = await updateVendorSnippetInDb(ctx.staffUser!.regionId, id, updateData)
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Failed to update vendor snippet')
|
||||
}
|
||||
|
||||
return result
|
||||
}),
|
||||
|
||||
delete: protectedProcedure
|
||||
.input(z.object({ id: z.number().int().positive() }))
|
||||
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippetDeleteResult> => {
|
||||
const { id } = input;
|
||||
|
||||
const result = await deleteVendorSnippetInDb(ctx.staffUser!.regionId, id)
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
}
|
||||
|
||||
return { message: 'Vendor snippet deleted successfully' }
|
||||
}),
|
||||
|
||||
getOrdersBySnippet: publicProcedure
|
||||
.input(z.object({
|
||||
snippetCode: z.string().min(1, "Snippet code is required")
|
||||
}))
|
||||
.query(async ({ input }): Promise<AdminVendorSnippetOrdersResult> => {
|
||||
const { snippetCode } = input;
|
||||
|
||||
// Public vendor link: no staff region available, lookup stays global.
|
||||
const snippet = await getVendorSnippetByCodeInDb(null, snippetCode)
|
||||
|
||||
if (!snippet) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
}
|
||||
|
||||
if (snippet.validTill && new Date(snippet.validTill) < new Date()) {
|
||||
throw new Error('Vendor snippet has expired')
|
||||
}
|
||||
|
||||
if (!snippet.slotId) {
|
||||
throw new Error('Vendor snippet not associated with a slot')
|
||||
}
|
||||
|
||||
const matchingOrders = await getVendorOrdersBySlotIdInDb(null, snippet.slotId)
|
||||
|
||||
// Filter orders that contain at least one of the snippet's products
|
||||
const filteredOrders = matchingOrders.filter(order => {
|
||||
const status = order.orderStatus;
|
||||
if (status[0].isCancelled) return false;
|
||||
const orderProductIds = order.orderItems.map(item => item.skuId);
|
||||
return snippet.skuIds.some(productId => orderProductIds.includes(productId));
|
||||
});
|
||||
|
||||
// Format the response
|
||||
const formattedOrders = filteredOrders.map(order => {
|
||||
// Filter orderItems to only include products attached to the snippet
|
||||
const attachedOrderItems = order.orderItems.filter(item =>
|
||||
snippet.skuIds.includes(item.skuId)
|
||||
);
|
||||
|
||||
const products = attachedOrderItems.map(item => ({
|
||||
orderItemId: item.id,
|
||||
productId: item.skuId,
|
||||
productName: composeSkuName(item.sku?.product?.name || 'Unknown', item.sku?.features || []),
|
||||
quantity: parseFloat(item.quantity),
|
||||
productSize: 1,
|
||||
price: parseFloat((item.price ?? 0).toString()),
|
||||
unit: composeUnitNotation(item.sku?.features || []) || 'unit',
|
||||
subtotal: parseFloat((item.price ?? 0).toString()) * parseFloat(item.quantity),
|
||||
is_packaged: item.is_packaged,
|
||||
is_package_verified: item.is_package_verified,
|
||||
}));
|
||||
|
||||
const orderTotal = products.reduce((sum, p) => sum + p.subtotal, 0);
|
||||
|
||||
return {
|
||||
orderId: `ORD${order.id}`,
|
||||
orderDate: order.createdAt ? order.createdAt.toISOString() : new Date(0).toISOString(),
|
||||
customerName: order.user.name || '',
|
||||
totalAmount: orderTotal,
|
||||
slotInfo: order.slot ? {
|
||||
time: order.slot.deliveryTime ? order.slot.deliveryTime.toISOString() : new Date(0).toISOString(),
|
||||
sequence: order.slot.deliverySequence,
|
||||
} : null,
|
||||
products,
|
||||
matchedProducts: snippet.skuIds, // All snippet products are considered matched
|
||||
snippetCode: snippet.snippetCode,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: formattedOrders,
|
||||
snippet: {
|
||||
id: snippet.id,
|
||||
snippetCode: snippet.snippetCode,
|
||||
slotId: snippet.slotId,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill?.toISOString(),
|
||||
createdAt: snippet.createdAt.toISOString(),
|
||||
isPermanent: snippet.isPermanent,
|
||||
},
|
||||
}
|
||||
}),
|
||||
|
||||
getUpcomingSlots: publicProcedure
|
||||
.query(async (): Promise<AdminUpcomingSlotsResult> => {
|
||||
const threeHoursAgo = dayjs().subtract(3, 'hour').toDate();
|
||||
// Public vendor link: no staff region available, stays global.
|
||||
const slots = await getSlotsAfterDateInDb(null, threeHoursAgo)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: slots.map(slot => ({
|
||||
id: slot.id,
|
||||
deliveryTime: slot.deliveryTime.toISOString(),
|
||||
freezeTime: slot.freezeTime.toISOString(),
|
||||
deliverySequence: slot.deliverySequence,
|
||||
})),
|
||||
}
|
||||
}),
|
||||
|
||||
getOrdersBySnippetAndSlot: publicProcedure
|
||||
.input(z.object({
|
||||
snippetCode: z.string().min(1, "Snippet code is required"),
|
||||
slotId: z.number().int().positive("Valid slot ID is required"),
|
||||
}))
|
||||
.query(async ({ input }): Promise<AdminVendorSnippetOrdersWithSlotResult> => {
|
||||
const { snippetCode, slotId } = input;
|
||||
|
||||
// Public vendor link: no staff region available, lookups stay global.
|
||||
const snippet = await getVendorSnippetByCodeInDb(null, snippetCode)
|
||||
const slot = await getVendorSlotByIdInDb(null, slotId)
|
||||
|
||||
if (!snippet) {
|
||||
throw new Error('Vendor snippet not found')
|
||||
}
|
||||
|
||||
if (!slot) {
|
||||
throw new Error('Slot not found')
|
||||
}
|
||||
|
||||
const matchingOrders = await getVendorOrdersBySlotIdInDb(null, slotId)
|
||||
|
||||
// Filter orders that contain at least one of the snippet's products
|
||||
const filteredOrders = matchingOrders.filter(order => {
|
||||
const status = order.orderStatus;
|
||||
if (status[0]?.isCancelled) return false;
|
||||
const orderProductIds = order.orderItems.map(item => item.skuId);
|
||||
return snippet.skuIds.some(productId => orderProductIds.includes(productId));
|
||||
});
|
||||
|
||||
// Format the response
|
||||
const formattedOrders = filteredOrders.map(order => {
|
||||
// Filter orderItems to only include products attached to the snippet
|
||||
const attachedOrderItems = order.orderItems.filter(item =>
|
||||
snippet.skuIds.includes(item.skuId)
|
||||
);
|
||||
|
||||
const products = attachedOrderItems.map(item => ({
|
||||
orderItemId: item.id,
|
||||
productId: item.skuId,
|
||||
productName: composeSkuName(item.sku?.product?.name || 'Unknown', item.sku?.features || []),
|
||||
quantity: parseFloat(item.quantity),
|
||||
price: parseFloat((item.price ?? 0).toString()),
|
||||
unit: composeUnitNotation(item.sku?.features || []) || 'unit',
|
||||
subtotal: parseFloat((item.price ?? 0).toString()) * parseFloat(item.quantity),
|
||||
productSize: 1,
|
||||
is_packaged: item.is_packaged,
|
||||
is_package_verified: item.is_package_verified,
|
||||
}));
|
||||
|
||||
const orderTotal = products.reduce((sum, p) => sum + p.subtotal, 0);
|
||||
|
||||
return {
|
||||
orderId: `ORD${order.id}`,
|
||||
orderDate: order.createdAt ? order.createdAt.toISOString() : new Date(0).toISOString(),
|
||||
customerName: order.user.name || '',
|
||||
totalAmount: orderTotal,
|
||||
slotInfo: order.slot ? {
|
||||
time: order.slot.deliveryTime ? order.slot.deliveryTime.toISOString() : new Date(0).toISOString(),
|
||||
sequence: order.slot.deliverySequence,
|
||||
} : null,
|
||||
products,
|
||||
matchedProducts: snippet.skuIds,
|
||||
snippetCode: snippet.snippetCode,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: formattedOrders,
|
||||
snippet: {
|
||||
id: snippet.id,
|
||||
snippetCode: snippet.snippetCode,
|
||||
slotId: snippet.slotId,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill?.toISOString(),
|
||||
createdAt: snippet.createdAt ? snippet.createdAt.toISOString() : new Date(0).toISOString(),
|
||||
isPermanent: snippet.isPermanent,
|
||||
},
|
||||
selectedSlot: {
|
||||
id: slot.id,
|
||||
deliveryTime: slot.deliveryTime ? slot.deliveryTime.toISOString() : new Date(0).toISOString(),
|
||||
freezeTime: slot.freezeTime ? slot.freezeTime.toISOString() : new Date(0).toISOString(),
|
||||
deliverySequence: slot.deliverySequence,
|
||||
},
|
||||
}
|
||||
}),
|
||||
|
||||
updateOrderItemPackaging: publicProcedure
|
||||
.input(z.object({
|
||||
orderItemId: z.number().int().positive("Valid order item ID required"),
|
||||
is_packaged: z.boolean()
|
||||
}))
|
||||
.mutation(async ({ input, ctx }): Promise<AdminVendorUpdatePackagingResult> => {
|
||||
const { orderItemId, is_packaged } = input;
|
||||
|
||||
// Get staff user ID from auth middleware
|
||||
// const staffUserId = ctx.staffUser?.id;
|
||||
// if (!staffUserId) {
|
||||
// throw new Error("Unauthorized");
|
||||
// }
|
||||
|
||||
const result = await updateVendorOrderItemPackagingInDb(orderItemId, is_packaged)
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.message)
|
||||
}
|
||||
|
||||
return result
|
||||
}),
|
||||
});
|
||||
|
|
@ -52,10 +52,10 @@ export const complaintRouter = router({
|
|||
// list. A queue failure is logged and never fails the complaint.
|
||||
try {
|
||||
const text = complaintBody.trim()
|
||||
const snippet = text.length > 80 ? `${text.slice(0, 77)}…` : text
|
||||
const preview = text.length > 80 ? `${text.slice(0, 77)}…` : text
|
||||
await notifyRegionAdmins(complaint.regionId, {
|
||||
title: '📩 New Complaint',
|
||||
body: orderIdNum ? `Order #${orderIdNum} • ${snippet}` : snippet,
|
||||
body: orderIdNum ? `Order #${orderIdNum} • ${preview}` : preview,
|
||||
orderId: orderIdNum,
|
||||
complaintId: complaint.id,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -135,8 +135,8 @@ These are properties of this seeded local D1, not of the contract. Pin them as
|
|||
|
||||
The suite writes into the **local** D1 (`freshyo-dev`), not a throwaway DB. After
|
||||
a run it leaves test regions/bounds, ~300 stores, ~300 products and their SKUs,
|
||||
tags, groups, slots, staff, users, orders, coupons, banners, snippets and
|
||||
`global_consts` probes behind. It also bumps the versioned cache files and the KV
|
||||
tags, groups, slots, staff, users, orders, coupons, banners and `global_consts`
|
||||
probes behind. It also bumps the versioned cache files and the KV
|
||||
mirror. Clean up after a full run (or before handing the DB to someone).
|
||||
|
||||
> Local only. Never point this at `wrangler.prod.toml`, `--remote`, or a shared
|
||||
|
|
|
|||
|
|
@ -44,7 +44,6 @@ interface SlotInput {
|
|||
freezeTime?: string
|
||||
isActive?: boolean
|
||||
skuIds?: number[]
|
||||
vendorSnippets?: Array<{ name: string; skuIds: number[]; validTill?: string }>
|
||||
groupIds?: number[]
|
||||
}
|
||||
|
||||
|
|
@ -54,7 +53,6 @@ async function createSlotAt(admin: ApiClient, input: SlotInput = {}): Promise<an
|
|||
freezeTime: input.freezeTime ?? hoursFromNow(2),
|
||||
...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
|
||||
...(input.skuIds !== undefined ? { skuIds: input.skuIds } : {}),
|
||||
...(input.vendorSnippets !== undefined ? { vendorSnippets: input.vendorSnippets } : {}),
|
||||
...(input.groupIds !== undefined ? { groupIds: input.groupIds } : {}),
|
||||
} as any)
|
||||
}
|
||||
|
|
@ -148,10 +146,9 @@ describe('admin.slots.getAll (ASLOT-01..02)', () => {
|
|||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.slots.createSlot (ASLOT-03..09)', () => {
|
||||
it('ASLOT-03: createSlot returns the slot, its products and vendor snippets', async () => {
|
||||
it('ASLOT-03: createSlot returns the slot and its products', async () => {
|
||||
const admin = await staffClient()
|
||||
const product = await catalogProduct()
|
||||
const snippetName = `E2E SNIP ${uniqueSuffix()}`
|
||||
const deliveryTime = hoursFromNow(5)
|
||||
const freezeTime = hoursFromNow(4)
|
||||
|
||||
|
|
@ -159,7 +156,6 @@ describe('admin.slots.createSlot (ASLOT-03..09)', () => {
|
|||
deliveryTime,
|
||||
freezeTime,
|
||||
skuIds: [product.skuId],
|
||||
vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }],
|
||||
groupIds: [],
|
||||
})
|
||||
|
||||
|
|
@ -169,18 +165,9 @@ describe('admin.slots.createSlot (ASLOT-03..09)', () => {
|
|||
)
|
||||
expect(res.slot.deliveryTime).toBe(deliveryTime)
|
||||
expect(res.slot.freezeTime).toBe(freezeTime)
|
||||
expect(res.createdSnippets).toHaveLength(1)
|
||||
expect(res.createdSnippets[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
snippetCode: snippetName,
|
||||
slotId: res.slot.id,
|
||||
skuIds: [product.skuId],
|
||||
})
|
||||
)
|
||||
|
||||
const detail: any = await admin.admin.slots.getSlotById.query({ id: res.slot.id })
|
||||
expect(detail.slot.products.map((p: any) => Number(p.id))).toContain(product.skuId)
|
||||
expect(detail.slot.vendorSnippets.map((s: any) => s.snippetCode)).toContain(snippetName)
|
||||
})
|
||||
|
||||
it('ASLOT-04: missing/empty delivery times are 400', async () => {
|
||||
|
|
@ -213,8 +200,6 @@ describe('admin.slots.createSlot (ASLOT-03..09)', () => {
|
|||
deliveryTime: FAR_FUTURE,
|
||||
freezeTime: FAR_FUTURE_FREEZE,
|
||||
})
|
||||
expect(res.createdSnippets).toEqual([])
|
||||
|
||||
const detail: any = await admin.admin.slots.getSlotById.query({ id: res.slot.id })
|
||||
expect(detail.slot.products).toEqual([])
|
||||
})
|
||||
|
|
@ -233,67 +218,13 @@ describe('admin.slots.createSlot (ASLOT-03..09)', () => {
|
|||
)
|
||||
})
|
||||
|
||||
it('ASLOT-08: a vendor snippet created with the slot carries an access URL', async () => {
|
||||
it('ASLOT-11: getSlotById returns the slot and its products', async () => {
|
||||
const admin = await staffClient()
|
||||
const product = await catalogProduct()
|
||||
const snippetName = `E2E SNIP ${uniqueSuffix()}`
|
||||
|
||||
const res: any = await createSlotAt(admin, {
|
||||
deliveryTime: FAR_FUTURE,
|
||||
freezeTime: FAR_FUTURE_FREEZE,
|
||||
skuIds: [product.skuId],
|
||||
vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }],
|
||||
})
|
||||
|
||||
const detail: any = await admin.admin.slots.getSlotById.query({ id: res.slot.id })
|
||||
const snippet = detail.slot.vendorSnippets.find((s: any) => s.snippetCode === snippetName)
|
||||
expect(snippet).toBeTruthy()
|
||||
expect(snippet.accessUrl).toContain('/vendor-order-list?id=')
|
||||
expect(snippet.accessUrl).toContain(snippetName)
|
||||
})
|
||||
|
||||
it('ASLOT-09 (current): a duplicate vendor snippet code fails the create with a 500', async () => {
|
||||
// Snippet codes are globally unique (checked with no region filter), and the
|
||||
// failure is a raw Error inside the transaction, so it flattens to 500.
|
||||
const admin = await staffClient()
|
||||
const product = await catalogProduct()
|
||||
const snippetName = `E2E DUP ${uniqueSuffix()}`
|
||||
|
||||
await createSlotAt(admin, {
|
||||
deliveryTime: FAR_FUTURE,
|
||||
freezeTime: FAR_FUTURE_FREEZE,
|
||||
skuIds: [product.skuId],
|
||||
vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }],
|
||||
})
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
createSlotAt(admin, {
|
||||
deliveryTime: hoursFromNow(6),
|
||||
freezeTime: hoursFromNow(5),
|
||||
skuIds: [product.skuId],
|
||||
vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }],
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'already exists'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* getSlotById */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.slots.getSlotById (ASLOT-11..12)', () => {
|
||||
it('ASLOT-11: getSlotById returns slot, products and snippet access URLs', async () => {
|
||||
const admin = await staffClient()
|
||||
const product = await catalogProduct()
|
||||
const snippetName = `E2E GET ${uniqueSuffix()}`
|
||||
const created: any = await createSlotAt(admin, {
|
||||
deliveryTime: FAR_FUTURE,
|
||||
freezeTime: FAR_FUTURE_FREEZE,
|
||||
skuIds: [product.skuId],
|
||||
vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }],
|
||||
})
|
||||
|
||||
const res: any = await admin.admin.slots.getSlotById.query({ id: created.slot.id })
|
||||
|
|
@ -301,14 +232,12 @@ describe('admin.slots.getSlotById (ASLOT-11..12)', () => {
|
|||
expect(res.slot.isActive).toBe(true)
|
||||
expect(Array.isArray(res.slot.deliverySequence)).toBe(true)
|
||||
expect(Array.isArray(res.slot.products)).toBe(true)
|
||||
expect(Array.isArray(res.slot.vendorSnippets)).toBe(true)
|
||||
|
||||
const productSummary = res.slot.products.find((p: any) => Number(p.id) === product.skuId)
|
||||
expect(productSummary).toBeTruthy()
|
||||
expect(typeof productSummary.name).toBe('string')
|
||||
expect(typeof productSummary.skuName).toBe('string')
|
||||
expect(Array.isArray(productSummary.features)).toBe(true)
|
||||
expect(res.slot.vendorSnippets[0].accessUrl).toContain('vendor-order-list?id=')
|
||||
})
|
||||
|
||||
it('ASLOT-12: an unknown slot id is 404', async () => {
|
||||
|
|
@ -326,7 +255,7 @@ describe('admin.slots.getSlotById (ASLOT-11..12)', () => {
|
|||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.slots.updateSlot (ASLOT-13..14)', () => {
|
||||
it('ASLOT-13: updateSlot changes times, products and adds snippets', async () => {
|
||||
it('ASLOT-13: updateSlot changes times and products', async () => {
|
||||
const admin = await staffClient()
|
||||
const product = await catalogProduct()
|
||||
const created: any = await createSlotAt(admin, {
|
||||
|
|
@ -337,24 +266,21 @@ describe('admin.slots.updateSlot (ASLOT-13..14)', () => {
|
|||
|
||||
const newDelivery = hoursFromNow(9)
|
||||
const newFreeze = hoursFromNow(8)
|
||||
const snippetName = `E2E UPD ${uniqueSuffix()}`
|
||||
|
||||
const res: any = await admin.admin.slots.updateSlot.mutate({
|
||||
id: created.slot.id,
|
||||
deliveryTime: newDelivery,
|
||||
freezeTime: newFreeze,
|
||||
skuIds: [product.skuId],
|
||||
vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }],
|
||||
isActive: true,
|
||||
})
|
||||
|
||||
expect(res.message).toBe('Slot updated successfully')
|
||||
expect(res.slot.deliveryTime).toBe(newDelivery)
|
||||
expect(res.slot.freezeTime).toBe(newFreeze)
|
||||
expect(res.createdSnippets.map((s: any) => s.snippetCode)).toContain(snippetName)
|
||||
|
||||
const detail: any = await admin.admin.slots.getSlotById.query({ id: created.slot.id })
|
||||
expect(detail.slot.vendorSnippets.map((s: any) => s.snippetCode)).toContain(snippetName)
|
||||
expect(detail.slot.id).toBe(created.slot.id)
|
||||
})
|
||||
|
||||
it('ASLOT-14 (current): an unknown slot is masked as 500 “Unable to Update Slot”', async () => {
|
||||
|
|
|
|||
|
|
@ -1,805 +0,0 @@
|
|||
/**
|
||||
* AVEND-01..32 — `admin.vendorSnippets` (catalogue §7.11).
|
||||
*
|
||||
* `create` is `staffProcedure`; `getAll`/`update`/`delete` are
|
||||
* `protectedProcedure`. The vendor link endpoints — `getOrdersBySnippet`,
|
||||
* `getUpcomingSlots`, `getOrdersBySnippetAndSlot` and (notably) the
|
||||
* `updateOrderItemPackaging` mutation — are `publicProcedure` by design and do a
|
||||
* GLOBAL lookup (`regionId = null`), which is the security-review item in §13
|
||||
* #10. Raw `Error`s thrown by the resolvers flatten to 500, so the "not found"
|
||||
* cases assert INTERNAL_SERVER_ERROR, not 404.
|
||||
*/
|
||||
|
||||
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
|
||||
import { anonClient, staffClient } from '../helpers/sessions'
|
||||
import {
|
||||
PASSWORD,
|
||||
createAddress,
|
||||
createFutureSlot,
|
||||
createProduct,
|
||||
createStore,
|
||||
placeOrder,
|
||||
registerThrowawayUser,
|
||||
type CreatedProduct,
|
||||
} from '../helpers/fixtures'
|
||||
import { TEST_OTHER_REGION_ID } from '../helpers/env'
|
||||
|
||||
jest.setTimeout(300_000)
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Helpers */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
interface SnippetInput {
|
||||
snippetCode?: string
|
||||
slotId?: number
|
||||
skuIds?: number[]
|
||||
validTill?: string
|
||||
isPermanent?: boolean
|
||||
}
|
||||
|
||||
async function createSnippet(admin: ApiClient, input: SnippetInput): Promise<any> {
|
||||
return admin.admin.vendorSnippets.create.mutate({
|
||||
snippetCode: input.snippetCode ?? `E2E VS ${uniqueSuffix()}`,
|
||||
skuIds: input.skuIds ?? [],
|
||||
...(input.slotId !== undefined ? { slotId: input.slotId } : {}),
|
||||
...(input.validTill !== undefined ? { validTill: input.validTill } : {}),
|
||||
...(input.isPermanent !== undefined ? { isPermanent: input.isPermanent } : {}),
|
||||
} as any)
|
||||
}
|
||||
|
||||
/** A region-1 store + product + future slot for snippet creation. */
|
||||
let catalogPromise: Promise<{ product: CreatedProduct; slotId: number }> | null = null
|
||||
function catalog(): Promise<{ product: CreatedProduct; slotId: number }> {
|
||||
catalogPromise ??= (async () => {
|
||||
const store = await createStore()
|
||||
const product = await createProduct({ storeId: store.storeId, price: 175 })
|
||||
const slot = await createFutureSlot([product.skuId])
|
||||
return { product, slotId: slot.slotId }
|
||||
})()
|
||||
return catalogPromise
|
||||
}
|
||||
|
||||
async function createRegionStaff(regionId: number): Promise<ApiClient> {
|
||||
const { superadminClient } = await import('../helpers/sessions')
|
||||
const superadmin = await superadminClient()
|
||||
const roles: any = await superadmin.superadmin.staff.roles.query()
|
||||
const roleId = Number(roles.roles.find((r: any) => r.name === 'admin')?.id ?? roles.roles[0].id)
|
||||
const name = `e2e_avend_${uniqueSuffix()}`
|
||||
await superadmin.superadmin.staff.create.mutate({ name, password: PASSWORD, roleId, regionId })
|
||||
const login: any = await apiClient().admin.staffUser.login.mutate({ name, password: PASSWORD })
|
||||
return apiClient(login.token)
|
||||
}
|
||||
|
||||
interface ForeignRegion {
|
||||
client: ApiClient
|
||||
skuId: number
|
||||
slotId: number
|
||||
}
|
||||
|
||||
/** A private region with its own store/product/slot (snippets live there). */
|
||||
let foreignPromise: Promise<ForeignRegion> | null = null
|
||||
function foreignRegion(): Promise<ForeignRegion> {
|
||||
foreignPromise ??= (async () => {
|
||||
const client = await createRegionStaff(TEST_OTHER_REGION_ID)
|
||||
const storeRes: any = await client.admin.store.createStore.mutate({
|
||||
name: `E2E Foreign Store ${uniqueSuffix()}`,
|
||||
})
|
||||
const storeId = Number(storeRes.store.id)
|
||||
const productRes: any = await client.admin.product.createProduct.mutate({
|
||||
name: `E2E Foreign Product ${uniqueSuffix()}`,
|
||||
shortDescription: 'foreign region product',
|
||||
storeId,
|
||||
productType: 'item',
|
||||
skus: [
|
||||
{
|
||||
name: '1pc',
|
||||
price: 200,
|
||||
marketPrice: 250,
|
||||
images: [],
|
||||
isFlashAvailable: false,
|
||||
flashPrice: null,
|
||||
isOutOfStock: false,
|
||||
isOffer: false,
|
||||
isComboOnly: false,
|
||||
isSuspended: false,
|
||||
features: [{ featureName: 'quantity', featureValue: '1pc' }],
|
||||
},
|
||||
],
|
||||
} as any)
|
||||
const skuId = Number(productRes.product.skus[0].id)
|
||||
const slotRes: any = await client.admin.slots.createSlot.mutate({
|
||||
deliveryTime: new Date(Date.now() + 4 * 3_600_000).toISOString(),
|
||||
freezeTime: new Date(Date.now() + 3 * 3_600_000).toISOString(),
|
||||
skuIds: [skuId],
|
||||
})
|
||||
return { client, skuId, slotId: Number(slotRes.slot.id) }
|
||||
})()
|
||||
return foreignPromise
|
||||
}
|
||||
|
||||
interface OrderSetup {
|
||||
snippetCode: string
|
||||
slotId: number
|
||||
product: CreatedProduct
|
||||
user: { name: string; token: string }
|
||||
orderA: any
|
||||
orderB: any
|
||||
orderC: any
|
||||
otherSlotId: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Region-1 store + two products + slot + user/address, with:
|
||||
* orderA = productA on the snippet slot
|
||||
* orderB = productB on the same slot (no snippet SKU)
|
||||
* orderC = productA on the snippet slot, then cancelled
|
||||
*/
|
||||
let orderSetupPromise: Promise<OrderSetup> | null = null
|
||||
function orderSetup(): Promise<OrderSetup> {
|
||||
orderSetupPromise ??= (async () => {
|
||||
const admin = await staffClient()
|
||||
const store = await createStore()
|
||||
const productA = await createProduct({ storeId: store.storeId, price: 111 })
|
||||
const productB = await createProduct({ storeId: store.storeId, price: 222 })
|
||||
const slot = await createFutureSlot([productA.skuId, productB.skuId])
|
||||
const otherSlot = await createFutureSlot([productA.skuId])
|
||||
const user = await registerThrowawayUser()
|
||||
const address = await createAddress(user.token)
|
||||
|
||||
const [orderA] = await placeOrder(user.token, {
|
||||
addressId: address.id,
|
||||
skuId: productA.skuId,
|
||||
slotId: slot.slotId,
|
||||
})
|
||||
const [orderB] = await placeOrder(user.token, {
|
||||
addressId: address.id,
|
||||
skuId: productB.skuId,
|
||||
slotId: slot.slotId,
|
||||
})
|
||||
const [orderC] = await placeOrder(user.token, {
|
||||
addressId: address.id,
|
||||
skuId: productA.skuId,
|
||||
slotId: slot.slotId,
|
||||
})
|
||||
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E ORD ${uniqueSuffix()}`,
|
||||
slotId: slot.slotId,
|
||||
skuIds: [productA.skuId],
|
||||
isPermanent: true,
|
||||
})
|
||||
|
||||
await admin.admin.order.cancelOrder.mutate({
|
||||
orderId: Number(orderC.id),
|
||||
reason: 'E2E AVEND-21 cancellation',
|
||||
})
|
||||
|
||||
return {
|
||||
snippetCode: snippet.snippetCode,
|
||||
slotId: slot.slotId,
|
||||
product: productA,
|
||||
user,
|
||||
orderA,
|
||||
orderB,
|
||||
orderC,
|
||||
otherSlotId: otherSlot.slotId,
|
||||
}
|
||||
})()
|
||||
return orderSetupPromise
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* create */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.vendorSnippets.create (AVEND-01..08)', () => {
|
||||
it('AVEND-01: create with a slot and SKUs returns the snippet', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const code = `E2E VS ${uniqueSuffix()}`
|
||||
|
||||
const snippet: any = await createSnippet(admin, { snippetCode: code, slotId, skuIds: [product.skuId] })
|
||||
|
||||
expect(snippet).toEqual(
|
||||
expect.objectContaining({
|
||||
id: expect.any(Number),
|
||||
snippetCode: code,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
isPermanent: false,
|
||||
validTill: null,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-02: a missing snippet code is BAD_REQUEST', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
await expectTrpcError(
|
||||
() => admin.admin.vendorSnippets.create.mutate({ slotId, skuIds: [product.skuId] } as any),
|
||||
'BAD_REQUEST'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-03: an empty SKU list is BAD_REQUEST', async () => {
|
||||
const admin = await staffClient()
|
||||
const { slotId } = await catalog()
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
admin.admin.vendorSnippets.create.mutate({
|
||||
snippetCode: `E2E VS ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [],
|
||||
}),
|
||||
'BAD_REQUEST'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-04: an unknown slot id is a 500 “Invalid slot ID”', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product } = await catalog()
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
createSnippet(admin, {
|
||||
snippetCode: `E2E VS ${uniqueSuffix()}`,
|
||||
slotId: 999_999_999,
|
||||
skuIds: [product.skuId],
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'Invalid slot ID'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-05: invalid and foreign SKUs are 500s', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
createSnippet(admin, {
|
||||
snippetCode: `E2E VS ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [999_999_999],
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'invalid product'
|
||||
)
|
||||
|
||||
const foreign = await foreignRegion()
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
createSnippet(admin, {
|
||||
snippetCode: `E2E VS ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [foreign.skuId],
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'invalid product'
|
||||
)
|
||||
expect(product.skuId).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('AVEND-06: a duplicate snippet code is a 500', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const code = `E2E DUP ${uniqueSuffix()}`
|
||||
await createSnippet(admin, { snippetCode: code, slotId, skuIds: [product.skuId] })
|
||||
|
||||
await expectTrpcError(
|
||||
() => createSnippet(admin, { snippetCode: code, slotId, skuIds: [product.skuId] }),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'already exists'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-07: a snippet with no slot is allowed but the orders endpoint errors', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product } = await catalog()
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E NOSLOT ${uniqueSuffix()}`,
|
||||
skuIds: [product.skuId],
|
||||
})
|
||||
expect(snippet.slotId).toBeNull()
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: snippet.snippetCode,
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'not associated with a slot'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-08: validTill and isPermanent are stored', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const validTill = new Date(Date.now() + 7 * 24 * 3_600_000).toISOString()
|
||||
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E PERM ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
validTill,
|
||||
isPermanent: true,
|
||||
})
|
||||
expect(snippet.isPermanent).toBe(true)
|
||||
expect(new Date(snippet.validTill).toISOString()).toBe(validTill)
|
||||
|
||||
const list: any = await admin.admin.vendorSnippets.getAll.query()
|
||||
const listed = list.find((entry: any) => entry.id === snippet.id)
|
||||
expect(listed.isPermanent).toBe(true)
|
||||
expect(new Date(listed.validTill).toISOString()).toBe(validTill)
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* getAll */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.vendorSnippets.getAll (AVEND-09..10)', () => {
|
||||
it('AVEND-09: getAll returns snippets with products, slot and access URL', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const code = `E2E ALL ${uniqueSuffix()}`
|
||||
const snippet: any = await createSnippet(admin, { snippetCode: code, slotId, skuIds: [product.skuId] })
|
||||
|
||||
const list: any = await admin.admin.vendorSnippets.getAll.query()
|
||||
const listed = list.find((entry: any) => entry.id === snippet.id)
|
||||
expect(listed).toBeTruthy()
|
||||
expect(listed.accessUrl).toContain('/vendor-order-list?id=')
|
||||
expect(listed.accessUrl).toContain(code)
|
||||
expect(listed.slot).toEqual(expect.objectContaining({ id: slotId }))
|
||||
expect(listed.products).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ id: product.skuId })])
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-10: a region with no snippets returns []', async () => {
|
||||
// A brand-new region has no vendor snippets yet, so getAll is genuinely
|
||||
// empty (the resolver also swallows errors and returns []).
|
||||
const { superadminClient } = await import('../helpers/sessions')
|
||||
const superadmin = await superadminClient()
|
||||
const created: any = await superadmin.superadmin.regions.create.mutate({
|
||||
name: `E2E Empty Snippets ${uniqueSuffix()}`,
|
||||
description: 'AVEND-10',
|
||||
center: { lat: 19.1, lng: 80.1 },
|
||||
bounds: [
|
||||
{
|
||||
description: 'b',
|
||||
geojson: {
|
||||
type: 'FeatureCollection',
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: {},
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[80.0, 19.0],
|
||||
[80.2, 19.0],
|
||||
[80.2, 19.2],
|
||||
[80.0, 19.2],
|
||||
[80.0, 19.0],
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
priority: '1',
|
||||
},
|
||||
],
|
||||
})
|
||||
const freshClient = await createRegionStaff(Number(created.id))
|
||||
const list: any = await freshClient.admin.vendorSnippets.getAll.query()
|
||||
expect(list).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* update / delete */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.vendorSnippets.update/delete (AVEND-11..16)', () => {
|
||||
it('AVEND-11: update changes code, slot, SKUs and flags', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E UPD ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
})
|
||||
|
||||
const newCode = `E2E UPD ${uniqueSuffix()}`
|
||||
const updated: any = await admin.admin.vendorSnippets.update.mutate({
|
||||
id: snippet.id,
|
||||
updates: {
|
||||
snippetCode: newCode,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
isPermanent: true,
|
||||
},
|
||||
})
|
||||
expect(updated).toEqual(
|
||||
expect.objectContaining({
|
||||
id: snippet.id,
|
||||
snippetCode: newCode,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
isPermanent: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-12: updating an unknown snippet is a 500', async () => {
|
||||
const admin = await staffClient()
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
admin.admin.vendorSnippets.update.mutate({
|
||||
id: 999_999_999,
|
||||
updates: { snippetCode: 'ghost' },
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'not found'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-13: update with an invalid slot or SKU is a 500', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E UPD ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
})
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
admin.admin.vendorSnippets.update.mutate({
|
||||
id: snippet.id,
|
||||
updates: { slotId: 999_999_999 },
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'Invalid slot ID'
|
||||
)
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
admin.admin.vendorSnippets.update.mutate({
|
||||
id: snippet.id,
|
||||
updates: { skuIds: [999_999_999] },
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'invalid product'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-14: update to a duplicate code is a 500', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const code = `E2E DUPD ${uniqueSuffix()}`
|
||||
await createSnippet(admin, { snippetCode: code, slotId, skuIds: [product.skuId] })
|
||||
const other: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E DUPD2 ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
})
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
admin.admin.vendorSnippets.update.mutate({
|
||||
id: other.id,
|
||||
updates: { snippetCode: code },
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'already exists'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-15: delete removes the snippet', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E DEL ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
})
|
||||
|
||||
const res: any = await admin.admin.vendorSnippets.delete.mutate({ id: snippet.id })
|
||||
expect(res.message).toBe('Vendor snippet deleted successfully')
|
||||
|
||||
const list: any = await admin.admin.vendorSnippets.getAll.query()
|
||||
expect(list.some((entry: any) => entry.id === snippet.id)).toBe(false)
|
||||
})
|
||||
|
||||
it('AVEND-16: deleting an unknown snippet is a 500', async () => {
|
||||
const admin = await staffClient()
|
||||
await expectTrpcError(
|
||||
() => admin.admin.vendorSnippets.delete.mutate({ id: 999_999_999 }),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'not found'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* public vendor link: orders */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.vendorSnippets public order lookups (AVEND-17..28)', () => {
|
||||
it('AVEND-17: getOrdersBySnippet returns only orders with the snippet’s SKUs', async () => {
|
||||
const setup = await orderSetup()
|
||||
const res: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
|
||||
expect(res.success).toBe(true)
|
||||
expect(res.snippet).toEqual(
|
||||
expect.objectContaining({ snippetCode: setup.snippetCode, slotId: setup.slotId })
|
||||
)
|
||||
|
||||
const ids = res.data.map((order: any) => order.orderId)
|
||||
expect(ids).toContain(`ORD${setup.orderA.id}`)
|
||||
// orderB is on the same slot but has no snippet SKU.
|
||||
expect(ids).not.toContain(`ORD${setup.orderB.id}`)
|
||||
|
||||
const orderA = res.data.find((order: any) => order.orderId === `ORD${setup.orderA.id}`)
|
||||
expect(orderA.products.map((p: any) => Number(p.productId))).toEqual([setup.product.skuId])
|
||||
expect(orderA.products[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
orderItemId: expect.any(Number),
|
||||
quantity: expect.any(Number),
|
||||
is_packaged: expect.any(Boolean),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-18: an unknown snippet code is a 500', async () => {
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: `NOPE-${uniqueSuffix()}`,
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'not found'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-19: an expired snippet is a 500', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product, slotId } = await catalog()
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E EXP ${uniqueSuffix()}`,
|
||||
slotId,
|
||||
skuIds: [product.skuId],
|
||||
validTill: new Date(Date.now() - 3_600_000).toISOString(),
|
||||
isPermanent: false,
|
||||
})
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: snippet.snippetCode,
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'expired'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-20: a snippet with no slot is a 500 “not associated with a slot”', async () => {
|
||||
const admin = await staffClient()
|
||||
const { product } = await catalog()
|
||||
const snippet: any = await createSnippet(admin, {
|
||||
snippetCode: `E2E NOSLOT ${uniqueSuffix()}`,
|
||||
skuIds: [product.skuId],
|
||||
})
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: snippet.snippetCode,
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'not associated with a slot'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-21: cancelled orders are excluded', async () => {
|
||||
const setup = await orderSetup()
|
||||
const res: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
const ids = res.data.map((order: any) => order.orderId)
|
||||
expect(ids).not.toContain(`ORD${setup.orderC.id}`)
|
||||
})
|
||||
|
||||
it('AVEND-22: orders without a snippet SKU are excluded', async () => {
|
||||
const setup = await orderSetup()
|
||||
const res: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
const ids = res.data.map((order: any) => order.orderId)
|
||||
expect(ids).toContain(`ORD${setup.orderA.id}`)
|
||||
expect(ids).not.toContain(`ORD${setup.orderB.id}`)
|
||||
})
|
||||
|
||||
it('AVEND-23 (current): customerName falls back to "" only for null-name rows', async () => {
|
||||
// The resolver writes `order.user.name || ''`; every API-registered user has
|
||||
// a non-empty name, so the empty-string branch is only reachable for legacy
|
||||
// rows with a null `users.name`.
|
||||
const setup = await orderSetup()
|
||||
const res: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
const orderA = res.data.find((order: any) => order.orderId === `ORD${setup.orderA.id}`)
|
||||
expect(orderA.customerName).toBe(setup.user.name)
|
||||
expect(orderA.customerName.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('AVEND-24: the vendor order lookup is public (no auth needed)', async () => {
|
||||
const setup = await orderSetup()
|
||||
const res: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
})
|
||||
|
||||
it('AVEND-25: getUpcomingSlots returns slots after now-3h, publicly', async () => {
|
||||
const setup = await orderSetup()
|
||||
const res: any = await anonClient().admin.vendorSnippets.getUpcomingSlots.query()
|
||||
|
||||
expect(res.success).toBe(true)
|
||||
expect(Array.isArray(res.data)).toBe(true)
|
||||
const slot = res.data.find((entry: any) => Number(entry.id) === setup.slotId)
|
||||
expect(slot).toBeTruthy()
|
||||
expect(slot).toEqual(
|
||||
expect.objectContaining({
|
||||
deliveryTime: expect.any(String),
|
||||
freezeTime: expect.any(String),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-26 (current): getUpcomingSlots is global, so the empty case is unreachable here', async () => {
|
||||
// The resolver ignores region entirely (`getSlotsAfterDate(null, now-3h)`),
|
||||
// so a seeded DB always has rows; the pinned contract is the envelope shape.
|
||||
const res: any = await anonClient().admin.vendorSnippets.getUpcomingSlots.query()
|
||||
expect(res.success).toBe(true)
|
||||
expect(res.data.length).toBeGreaterThan(0)
|
||||
for (const slot of res.data) {
|
||||
expect(new Date(slot.deliveryTime).getTime()).toBeGreaterThan(Date.now() - 3 * 3_600_000)
|
||||
}
|
||||
})
|
||||
|
||||
it('AVEND-27: getOrdersBySnippetAndSlot filters by the given slot', async () => {
|
||||
const setup = await orderSetup()
|
||||
const res: any = await anonClient().admin.vendorSnippets.getOrdersBySnippetAndSlot.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
slotId: setup.slotId,
|
||||
})
|
||||
|
||||
expect(res.success).toBe(true)
|
||||
expect(res.selectedSlot.id).toBe(setup.slotId)
|
||||
expect(res.data.map((order: any) => order.orderId)).toContain(`ORD${setup.orderA.id}`)
|
||||
|
||||
// A different, valid slot has no matching orders.
|
||||
const other: any = await anonClient().admin.vendorSnippets.getOrdersBySnippetAndSlot.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
slotId: setup.otherSlotId,
|
||||
})
|
||||
expect(other.data).toEqual([])
|
||||
})
|
||||
|
||||
it('AVEND-28: an unknown snippet or slot is a 500', async () => {
|
||||
const setup = await orderSetup()
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
anonClient().admin.vendorSnippets.getOrdersBySnippetAndSlot.query({
|
||||
snippetCode: `NOPE-${uniqueSuffix()}`,
|
||||
slotId: setup.slotId,
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'not found'
|
||||
)
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
anonClient().admin.vendorSnippets.getOrdersBySnippetAndSlot.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
slotId: 999_999_999,
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'Slot not found'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* public vendor link: packaging */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.vendorSnippets.updateOrderItemPackaging (AVEND-29..31)', () => {
|
||||
it('AVEND-29: updateOrderItemPackaging flips is_packaged', async () => {
|
||||
const setup = await orderSetup()
|
||||
const before: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
const orderA = before.data.find((order: any) => order.orderId === `ORD${setup.orderA.id}`)
|
||||
const orderItemId = Number(orderA.products[0].orderItemId)
|
||||
|
||||
const res: any = await anonClient().admin.vendorSnippets.updateOrderItemPackaging.mutate({
|
||||
orderItemId,
|
||||
is_packaged: true,
|
||||
})
|
||||
expect(res).toEqual(expect.objectContaining({ success: true, orderItemId, is_packaged: true }))
|
||||
|
||||
const after: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
const refreshed = after.data
|
||||
.find((order: any) => order.orderId === `ORD${setup.orderA.id}`)
|
||||
.products.find((p: any) => Number(p.orderItemId) === orderItemId)
|
||||
expect(refreshed.is_packaged).toBe(true)
|
||||
})
|
||||
|
||||
it('AVEND-30: an unknown order item is a 500', async () => {
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
anonClient().admin.vendorSnippets.updateOrderItemPackaging.mutate({
|
||||
orderItemId: 999_999_999,
|
||||
is_packaged: true,
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'Order item not found'
|
||||
)
|
||||
})
|
||||
|
||||
it('AVEND-31 (current): the packaging mutation is public — a security gap', async () => {
|
||||
// `updateOrderItemPackaging` is a `publicProcedure` with the auth check
|
||||
// commented out, and it is callable anonymously (§13 #10).
|
||||
const setup = await orderSetup()
|
||||
const view: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: setup.snippetCode,
|
||||
})
|
||||
const orderA = view.data.find((order: any) => order.orderId === `ORD${setup.orderA.id}`)
|
||||
const orderItemId = Number(orderA.products[0].orderItemId)
|
||||
|
||||
const res: any = await anonClient().admin.vendorSnippets.updateOrderItemPackaging.mutate({
|
||||
orderItemId,
|
||||
is_packaged: true,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
expect(res.is_packaged).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* cross-region */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe('admin.vendorSnippets cross-region (AVEND-32)', () => {
|
||||
it('AVEND-32 (current): the public lookup is global, so another region’s snippet resolves', async () => {
|
||||
const foreign = await foreignRegion()
|
||||
const code = `E2E FOREIGN ${uniqueSuffix()}`
|
||||
const created: any = await foreign.client.admin.vendorSnippets.create.mutate({
|
||||
snippetCode: code,
|
||||
slotId: foreign.slotId,
|
||||
skuIds: [foreign.skuId],
|
||||
isPermanent: true,
|
||||
})
|
||||
|
||||
// Region-1 staff cannot see it...
|
||||
const admin = await staffClient()
|
||||
const list: any = await admin.admin.vendorSnippets.getAll.query()
|
||||
expect(list.some((entry: any) => entry.id === created.id)).toBe(false)
|
||||
|
||||
// ...but the public vendor link resolves it with no region filter.
|
||||
const res: any = await anonClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: code,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
expect(res.snippet.id).toBe(created.id)
|
||||
expect(res.data).toEqual([])
|
||||
})
|
||||
})
|
||||
|
|
@ -121,7 +121,6 @@ const PUBLIC_PROCEDURES: Array<Proc & { input: unknown }> = [
|
|||
{ proc: 'common.activeBound', method: 'GET', input: { regionId: TEST_REGION_ID } },
|
||||
{ proc: 'common.essentialConsts', method: 'GET', input: { boundId: TEST_BOUND_ID } },
|
||||
{ proc: 'user.slots.getSlots', method: 'GET', input: { regionId: TEST_REGION_ID } },
|
||||
{ proc: 'admin.vendorSnippets.getUpcomingSlots', method: 'GET', input: {} },
|
||||
]
|
||||
|
||||
/** §3.2 AUTH-02 — user.* procedures that require a user token. */
|
||||
|
|
@ -152,7 +151,6 @@ const USER_PROTECTED: Proc[] = [
|
|||
|
||||
/** §3.2 AUTH-03 — representative admin reads (protectedProcedure). */
|
||||
const ADMIN_READS: Proc[] = [
|
||||
{ proc: 'admin.vendorSnippets.getAll', method: 'GET' },
|
||||
{ proc: 'admin.staffUser.getStaff', method: 'GET' },
|
||||
{ proc: 'admin.product.getProducts', method: 'GET' },
|
||||
{ proc: 'admin.store.getStores', method: 'GET' },
|
||||
|
|
@ -172,7 +170,6 @@ const ADMIN_WRITES: Proc[] = [
|
|||
{ proc: 'admin.product.updateProduct', method: 'POST' },
|
||||
{ proc: 'admin.store.updateStore', method: 'POST' },
|
||||
{ proc: 'admin.slots.updateSlotCapacity', method: 'POST' },
|
||||
{ proc: 'admin.vendorSnippets.update', method: 'POST' },
|
||||
{ proc: 'admin.complaint.resolve', method: 'POST' },
|
||||
]
|
||||
|
||||
|
|
@ -194,7 +191,6 @@ const STAFF_ONLY_WRITES: Proc[] = [
|
|||
{ proc: 'admin.product.createProductTag', method: 'POST' },
|
||||
{ proc: 'admin.store.createStore', method: 'POST' },
|
||||
{ proc: 'admin.staffUser.sendAdminNotification', method: 'POST' },
|
||||
{ proc: 'admin.vendorSnippets.create', method: 'POST' },
|
||||
{ proc: 'admin.region.updateRegionConstants', method: 'POST' },
|
||||
{ proc: 'admin.region.updateBoundSettings', method: 'POST' },
|
||||
]
|
||||
|
|
@ -570,7 +566,7 @@ describe('authorization matrix (AUTH-01..14)', () => {
|
|||
|
||||
// (current) protectedProcedure accepts a user token, so admin reads are not
|
||||
// staff-only. The observed outcomes vary by resolver:
|
||||
// - vendorSnippets.getAll / staffUser.getStaff don't touch ctx.staffUser -> succeed
|
||||
// - staffUser.getStaff doesn't touch ctx.staffUser -> succeeds
|
||||
// - product/store/user/banner/coupon/complaint dereference ctx.staffUser -> 500
|
||||
// - slots.getAll has an explicit staff check -> 401
|
||||
// - order.getAll returns a result with `data: undefined` on failure
|
||||
|
|
@ -579,7 +575,6 @@ describe('authorization matrix (AUTH-01..14)', () => {
|
|||
const res = await call(entry.proc, entry.method, {}, user.token)
|
||||
userOutcomes[entry.proc] = codeOf(res.body)
|
||||
}
|
||||
expect(userOutcomes['admin.vendorSnippets.getAll']).toBeUndefined()
|
||||
expect(userOutcomes['admin.staffUser.getStaff']).toBeUndefined()
|
||||
expect(userOutcomes['admin.product.getProducts']).toBe('INTERNAL_SERVER_ERROR')
|
||||
expect(userOutcomes['admin.store.getStores']).toBe('INTERNAL_SERVER_ERROR')
|
||||
|
|
|
|||
|
|
@ -7,8 +7,7 @@
|
|||
* immediately; the file is fetched with a short retry for upload propagation.
|
||||
*
|
||||
* Rows pinned `(current)`:
|
||||
* - CACHE-76: an unknown vendor-snippet SKU id is a 500 `Invalid SKU IDs`; an
|
||||
* unknown group id is silently dropped (`groupIds: []`).
|
||||
* - CACHE-76: an unknown group id is silently dropped (`groupIds: []`).
|
||||
*/
|
||||
|
||||
import { expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
|
||||
|
|
@ -34,7 +33,6 @@ interface SlotInput {
|
|||
freezeTime?: string
|
||||
isActive?: boolean
|
||||
skuIds?: number[]
|
||||
vendorSnippets?: Array<{ name: string; skuIds: number[] }>
|
||||
groupIds?: number[]
|
||||
}
|
||||
|
||||
|
|
@ -44,7 +42,6 @@ async function createSlotAt(admin: ApiClient, input: SlotInput = {}): Promise<an
|
|||
freezeTime: input.freezeTime ?? hoursFromNow(2),
|
||||
...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
|
||||
...(input.skuIds !== undefined ? { skuIds: input.skuIds } : {}),
|
||||
...(input.vendorSnippets !== undefined ? { vendorSnippets: input.vendorSnippets } : {}),
|
||||
...(input.groupIds !== undefined ? { groupIds: input.groupIds } : {}),
|
||||
} as any)
|
||||
}
|
||||
|
|
@ -312,20 +309,8 @@ describe('slots.json cross-region + validation (CACHE-74, 76)', () => {
|
|||
expect(findSlot(doc2, slotId)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('(current) CACHE-76: unknown snippet SKU ids are 500; unknown group ids are dropped', async () => {
|
||||
it('(current) CACHE-76: unknown group ids are dropped', async () => {
|
||||
const admin = await staffClient()
|
||||
const snippetName = `E2E UNKNOWN ${uniqueSuffix()}`
|
||||
|
||||
await expectTrpcError(
|
||||
() =>
|
||||
createSlotAt(admin, {
|
||||
deliveryTime: FAR_FUTURE,
|
||||
freezeTime: FAR_FUTURE_FREEZE,
|
||||
vendorSnippets: [{ name: snippetName, skuIds: [999_999_999] }],
|
||||
}),
|
||||
'INTERNAL_SERVER_ERROR',
|
||||
'Invalid SKU'
|
||||
)
|
||||
|
||||
// Unknown group ids pass validation and are silently normalised to [].
|
||||
const created = await createSlotAt(admin, {
|
||||
|
|
|
|||
|
|
@ -60,8 +60,6 @@ interface RegionAFixture {
|
|||
bannerId: number
|
||||
couponId: number
|
||||
couponCode: string
|
||||
snippetId: number
|
||||
snippetCode: string
|
||||
userToken: string
|
||||
userMobile: string
|
||||
userId: number
|
||||
|
|
@ -155,13 +153,6 @@ beforeAll(async () => {
|
|||
imageUrl: `https://assets2.freshyo.in/home-banners/iso-${uniqueSuffix()}.png`,
|
||||
})
|
||||
const coupon = await createCoupon()
|
||||
const snippet: any = await admin.admin.vendorSnippets.create.mutate({
|
||||
snippetCode: `ISO${uniqueSuffix().replace(/[^a-z0-9]/gi, '').toUpperCase()}`,
|
||||
slotId: slot.slotId,
|
||||
skuIds: [product.skuId],
|
||||
isPermanent: true,
|
||||
})
|
||||
|
||||
const user = await registerThrowawayUser()
|
||||
const address = await createAddress(user.token)
|
||||
const orders = await placeOrder(user.token, {
|
||||
|
|
@ -180,8 +171,6 @@ beforeAll(async () => {
|
|||
bannerId: Number(banner.id),
|
||||
couponId: Number(coupon.id),
|
||||
couponCode: coupon.couponCode,
|
||||
snippetId: Number(snippet.id),
|
||||
snippetCode: snippet.snippetCode,
|
||||
userToken: user.token,
|
||||
userMobile: user.mobile,
|
||||
userId: user.userId,
|
||||
|
|
@ -208,9 +197,6 @@ describe('region isolation — admin reads (ISO-01)', () => {
|
|||
const coupons: any = await b.admin.coupon.getAll.query({ search: regionA.couponCode })
|
||||
expect(coupons.coupons.some((c: any) => Number(c.id) === regionA.couponId)).toBe(false)
|
||||
|
||||
const snippets: any = await b.admin.vendorSnippets.getAll.query()
|
||||
expect(snippets.some((s: any) => Number(s.id) === regionA.snippetId)).toBe(false)
|
||||
|
||||
const users: any = await b.admin.user.getAllUsers.query({ search: regionA.userMobile, limit: 50 })
|
||||
expect(users.users.some((u: any) => Number(u.id) === regionA.userId)).toBe(false)
|
||||
|
||||
|
|
@ -421,14 +407,3 @@ describe('region isolation — superadmin global views (ISO-07)', () => {
|
|||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('region isolation — public vendor links (ISO-08)', () => {
|
||||
it('ISO-08: a vendor snippet is looked up globally by code from an anonymous client', async () => {
|
||||
const res: any = await apiClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: regionA.snippetCode,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
expect(res.snippet.snippetCode).toBe(regionA.snippetCode)
|
||||
expect(Number(res.snippet.id)).toBe(regionA.snippetId)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ import { createSlotsCacheFile } from '@/src/lib/cloud_cache'
|
|||
jest.mock('@/src/dbService', () => ({
|
||||
createSlotWithRelations: jest.fn(async () => ({
|
||||
slot: { id: 1 },
|
||||
createdSnippets: [],
|
||||
message: 'Slot created',
|
||||
})),
|
||||
staleSlotsCleanup: jest.fn(async () => 1),
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ TELEGRAM_BOT_TOKEN = "8410461852:AAGXQCwRPFbndqwTgLJh8kYxST4Z0vgh72U"
|
|||
TELEGRAM_CHAT_IDS = "-5075171894"
|
||||
|
||||
[triggers]
|
||||
crons = ["0 16 * * *", "0 1 * * *", "30 20 * * *"]
|
||||
crons = ["0 15 * * *", "0 1 * * *", "30 20 * * *"]
|
||||
# crons = ["* * * * *"]
|
||||
# crons = ["7 18 * * *", "10 18 * * *"]
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import { Link, Outlet, RootRoute, Route, createRouter } from '@tanstack/react-router'
|
||||
import { Suspense } from 'react'
|
||||
import { TanStackRouterDevtools } from '@tanstack/router-devtools'
|
||||
import { z } from 'zod'
|
||||
import { HomeRoute } from './routes/home'
|
||||
import { VendorOrderListRoute } from './routes/vendor-order-list'
|
||||
import { LoginRoute } from './routes/login'
|
||||
import { UserHomeRoute } from './routes/user-home'
|
||||
import { SuperAdminRoute } from './routes/super-admin'
|
||||
|
|
@ -34,19 +32,6 @@ const dashboardRoute = new Route({
|
|||
)
|
||||
})
|
||||
|
||||
const vendorOrderListRoute = new Route({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/vendor-order-list',
|
||||
validateSearch: z.object({
|
||||
id: z.string().optional(),
|
||||
}),
|
||||
component: () => (
|
||||
<Suspense fallback={<p>Loading vendor orders…</p>}>
|
||||
<VendorOrderListRoute />
|
||||
</Suspense>
|
||||
)
|
||||
})
|
||||
|
||||
const loginRoute = new Route({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/login',
|
||||
|
|
@ -163,7 +148,6 @@ const userDetailsRoute = new Route({
|
|||
|
||||
const routeTree = rootRoute.addChildren([
|
||||
dashboardRoute,
|
||||
vendorOrderListRoute,
|
||||
loginRoute,
|
||||
userHomeRoute,
|
||||
superAdminRoute,
|
||||
|
|
@ -193,7 +177,6 @@ declare module '@tanstack/react-router' {
|
|||
|
||||
const navItems = [
|
||||
{ to: '/', label: 'Dashboard', exact: true },
|
||||
{ to: '/vendor-order-list', label: 'Vendor Order List' },
|
||||
{ to: '/user-connect', label: 'User Connect' }
|
||||
] as const
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useMemo, useState } from "react";
|
||||
import { useParams, useNavigate, Link } from "@tanstack/react-router";
|
||||
import { useParams, Link } from "@tanstack/react-router";
|
||||
import dayjs from "dayjs";
|
||||
import { trpc } from "../trpc/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
|
@ -16,7 +16,6 @@ const getStatusBadge = (status?: string) => {
|
|||
|
||||
export function OrderDetailsRoute() {
|
||||
const { id } = useParams({ from: "/manage-orders/order-details/$id" });
|
||||
const navigate = useNavigate();
|
||||
const [incidentComment, setIncidentComment] = useState("");
|
||||
const [negativityScore, setNegativityScore] = useState("");
|
||||
|
||||
|
|
@ -80,12 +79,6 @@ export function OrderDetailsRoute() {
|
|||
<p className="text-xs font-medium text-slate-500">Order Details</p>
|
||||
<h1 className="text-2xl font-semibold text-slate-900">#{order.readableId}</h1>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate({ to: "/vendor-order-list" })}
|
||||
>
|
||||
Back to Orders
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
|
||||
|
|
|
|||
|
|
@ -1,308 +0,0 @@
|
|||
import { useMemo, useState, useEffect } from "react";
|
||||
import { useSearch } from "@tanstack/react-router";
|
||||
import { trpc } from "../trpc/client";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
interface VendorOrder {
|
||||
orderId: string;
|
||||
customerName: string;
|
||||
orderDate: string;
|
||||
totalAmount: string;
|
||||
products: Array<{
|
||||
orderItemId: number;
|
||||
productId: number;
|
||||
productName: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
is_packaged: boolean;
|
||||
is_package_verified: boolean;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface DeliverySlot {
|
||||
id: number;
|
||||
deliveryTime: string;
|
||||
freezeTime: string;
|
||||
deliverySequence: any;
|
||||
}
|
||||
|
||||
export function VendorOrderListRoute() {
|
||||
const { id } = useSearch({ from: "/vendor-order-list" });
|
||||
|
||||
// Fetch snippet info
|
||||
const { data: snippetInfo, isLoading: isLoadingSnippet } = id
|
||||
? trpc.admin.vendorSnippets.getOrdersBySnippet.useQuery({ snippetCode: id })
|
||||
: { data: null, isLoading: false };
|
||||
const snippet = snippetInfo?.snippet;
|
||||
const isPermanent = snippet?.isPermanent;
|
||||
|
||||
const { data: upcomingSlots } =
|
||||
trpc.admin.vendorSnippets.getUpcomingSlots.useQuery(undefined, {
|
||||
enabled: !!id,
|
||||
});
|
||||
|
||||
// State for selected slot
|
||||
const [selectedSlotId, setSelectedSlotId] = useState<number | null>(null);
|
||||
|
||||
// Auto-select first slot when snippets are loaded and isPermanent is true
|
||||
useEffect(() => {
|
||||
if (
|
||||
isPermanent &&
|
||||
upcomingSlots?.data &&
|
||||
upcomingSlots.data.length > 0 &&
|
||||
!selectedSlotId
|
||||
) {
|
||||
setSelectedSlotId(upcomingSlots.data[0].id);
|
||||
}
|
||||
}, [isPermanent, upcomingSlots, selectedSlotId]);
|
||||
|
||||
// Fetch orders based on mode
|
||||
const {
|
||||
data: slotOrdersData,
|
||||
error,
|
||||
isLoading: isLoadingOrders,
|
||||
isFetching,
|
||||
refetch,
|
||||
} = trpc.admin.vendorSnippets.getOrdersBySnippetAndSlot.useQuery(
|
||||
{ snippetCode: id!, slotId: selectedSlotId! },
|
||||
{ enabled: !!id && !!selectedSlotId && isPermanent },
|
||||
);
|
||||
|
||||
const { data: regularOrders } =
|
||||
trpc.admin.vendorSnippets.getOrdersBySnippet.useQuery(
|
||||
{ snippetCode: id! },
|
||||
{ enabled: !!id && !isPermanent },
|
||||
);
|
||||
|
||||
const orders = slotOrdersData?.data || regularOrders?.data || [];
|
||||
const isLoadingCurrent = isPermanent ? isLoadingOrders : isLoadingSnippet;
|
||||
|
||||
const updatePackagingMutation =
|
||||
trpc.admin.vendorSnippets.updateOrderItemPackaging.useMutation();
|
||||
|
||||
const [updatingItems, setUpdatingItems] = useState<Set<number>>(new Set());
|
||||
|
||||
const handlePackagingToggle = async (
|
||||
orderItemId: number,
|
||||
currentValue: boolean,
|
||||
) => {
|
||||
setUpdatingItems((prev) => new Set(prev).add(orderItemId));
|
||||
|
||||
try {
|
||||
await updatePackagingMutation.mutateAsync({
|
||||
orderItemId,
|
||||
is_packaged: !currentValue,
|
||||
});
|
||||
// Refetch data to update the UI
|
||||
refetch();
|
||||
} catch (error) {
|
||||
console.error("Failed to update packaging status:", error);
|
||||
} finally {
|
||||
setUpdatingItems((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(orderItemId);
|
||||
return newSet;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const productSummary = useMemo(() => {
|
||||
const summary: Record<string, { quantity: number; unit: string }> = {};
|
||||
|
||||
orders.forEach((order) => {
|
||||
order.products.forEach((product) => {
|
||||
const key = product.productName;
|
||||
if (!summary[key]) {
|
||||
summary[key] = { quantity: 0, unit: product.unit };
|
||||
}
|
||||
summary[key].quantity += product.quantity * product.productSize;
|
||||
});
|
||||
});
|
||||
|
||||
return Object.entries(summary).map(([name, data]) => ({
|
||||
name,
|
||||
quantity: data.quantity,
|
||||
unit: data.unit,
|
||||
}));
|
||||
}, [orders]);
|
||||
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-4">Summary</h2>
|
||||
<div className="grid gap-2">
|
||||
{productSummary.map((item, index) => (
|
||||
<div key={index} className="flex justify-between text-sm">
|
||||
<span className="text-slate-600">{item.name}:</span>
|
||||
<span className="font-medium text-slate-900">
|
||||
{item.quantity} {item.unit}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-slate-900">
|
||||
Vendor Orders
|
||||
</h2>
|
||||
<p className="text-sm text-slate-500">
|
||||
Track incoming orders and fulfilment progress for vendor partners.
|
||||
{id && <span className="block mt-1 text-xs">Snippet: {id}</span>}
|
||||
</p>
|
||||
</div>
|
||||
{isPermanent && upcomingSlots?.data && (
|
||||
<div className="flex items-center gap-2">
|
||||
<label
|
||||
htmlFor="slot-select"
|
||||
className="text-sm font-medium text-slate-700"
|
||||
>
|
||||
Select Slot:
|
||||
</label>
|
||||
<select
|
||||
id="slot-select"
|
||||
value={selectedSlotId || ""}
|
||||
onChange={(e) => setSelectedSlotId(Number(e.target.value))}
|
||||
className="base-select px-3 py-2 text-sm border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
{upcomingSlots.data.map((slot) => (
|
||||
<option key={slot.id} value={slot.id}>
|
||||
{dayjs(slot.deliveryTime).format("ddd, MMM DD hh:mm A")}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
void refetch();
|
||||
}}
|
||||
disabled={isFetching}
|
||||
>
|
||||
{isFetching ? "Refreshing…" : "Refresh"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
{isLoadingCurrent ? (
|
||||
<div className="rounded-xl border border-slate-100 bg-slate-50 p-6 text-sm text-slate-600">
|
||||
Loading orders…
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="rounded-xl border border-red-200 bg-red-50 p-6 text-sm text-red-600">
|
||||
{error.message ?? "Unable to load vendor orders right now"}
|
||||
</div>
|
||||
) : !id ? (
|
||||
<div className="rounded-xl border border-red-200 bg-red-50 p-6 text-sm text-red-600">
|
||||
No snippet code provided
|
||||
</div>
|
||||
) : orders.length === 0 ? (
|
||||
<div className="rounded-xl border border-slate-100 bg-slate-50 p-6 text-sm text-slate-600">
|
||||
No vendor orders found.
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{orders.map((order) => {
|
||||
const parsedDate = order.orderDate
|
||||
? dayjs(order.orderDate).format("ddd, MMM DD hh:mm A")
|
||||
: "N/A";
|
||||
const badgeClass =
|
||||
"border-slate-200 bg-slate-100 text-slate-600 inline-flex items-center rounded-full border px-3 py-0.5 text-xs font-semibold uppercase";
|
||||
|
||||
return (
|
||||
<article
|
||||
key={order.orderId}
|
||||
className="flex flex-col gap-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm"
|
||||
>
|
||||
<header className="flex items-start justify-between gap-3">
|
||||
<h3 className="text-base font-semibold text-slate-900">
|
||||
{order.orderId}
|
||||
</h3>
|
||||
<span className={badgeClass}>Pending</span>
|
||||
</header>
|
||||
<dl className="grid gap-3 text-sm text-slate-600">
|
||||
<div className="space-y-2">
|
||||
<dt className="text-xs uppercase tracking-wide text-slate-400">
|
||||
Products (Packaging Status)
|
||||
</dt>
|
||||
<dd className="space-y-2">
|
||||
{order.products.map((product) => (
|
||||
<div
|
||||
key={product.orderItemId}
|
||||
className="flex items-center gap-3"
|
||||
>
|
||||
<span className="text-sm font-medium text-slate-900 flex-1">
|
||||
{product.productName}: {product.productSize * product.quantity}{" "}
|
||||
{product.unit}
|
||||
</span>
|
||||
<label
|
||||
htmlFor={`package-${product.orderItemId}`}
|
||||
className={cn(
|
||||
"text-sm font-medium",
|
||||
product.is_packaged
|
||||
? "text-green-700"
|
||||
: "text-slate-600",
|
||||
)}
|
||||
>
|
||||
Packaged
|
||||
{updatingItems.has(product.orderItemId) && (
|
||||
<span className="ml-2 text-xs text-blue-500">
|
||||
(updating...)
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<input
|
||||
type="checkbox"
|
||||
id={`package-${product.orderItemId}`}
|
||||
checked={product.is_packaged}
|
||||
disabled={updatingItems.has(
|
||||
product.orderItemId,
|
||||
)}
|
||||
onChange={() =>
|
||||
handlePackagingToggle(
|
||||
product.orderItemId,
|
||||
product.is_packaged,
|
||||
)
|
||||
}
|
||||
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<dt className="text-xs uppercase tracking-wide text-slate-400">
|
||||
Date
|
||||
</dt>
|
||||
<dd className="font-medium text-slate-900">
|
||||
{parsedDate}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<dt className="text-xs uppercase tracking-wide text-slate-400">
|
||||
Total Amount
|
||||
</dt>
|
||||
<dd className="font-medium text-slate-900">
|
||||
₹{order.totalAmount}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isFetching && !isLoadingCurrent ? (
|
||||
<p className="mt-4 text-xs text-slate-500">Refreshing…</p>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
110
change-log.txt
110
change-log.txt
|
|
@ -526,3 +526,113 @@ visible-count reset lived in a useEffect that ran after paint.
|
|||
- Re-scan after the fixes: 11 -> 3 findings. The 3 left are the documented false
|
||||
positives (tag-strip ScrollView, string totalAmount) and the root lockfile
|
||||
decision.
|
||||
|
||||
[2026-11-02 20:32:28 IST] user-ui tests: stop jest-expo's expo-file-system mock from replacing the shared native shim.
|
||||
|
||||
Running the suite gave 943 failures: every rendered screen died with
|
||||
"Font.isLoaded is not a function" / "type is invalid ... got undefined".
|
||||
Cause: jest-expo's preset (setupFiles) calls jest.mock('expo-file-system',
|
||||
factory). jest.mock is keyed by the *resolved path*, and jest.config.js maps
|
||||
^expo-file-system$ at mocks/native/common.tsx — the same file used for expo-font,
|
||||
expo-image, expo-linear-gradient, react-native-safe-area-context and friends.
|
||||
The preset's factory therefore replaced that whole module, so every import of
|
||||
those packages received expo-file-system's exports. Unrelated to any app code.
|
||||
|
||||
--- apps/user-ui/tests/mocks/native/file-system.ts (new)
|
||||
+ dedicated expo-file-system shim (documentDirectory, getInfoAsync,
|
||||
readAsStringAsync, writeAsStringAsync, deleteAsync + the preset's extra names).
|
||||
--- apps/user-ui/tests/jest.config.js
|
||||
~ ^expo-file-system$ now maps to the dedicated shim instead of common.tsx.
|
||||
--- apps/user-ui/tests/setup.ts
|
||||
~ jest.mock('expo-file-system', () => require('./mocks/native/file-system'))
|
||||
after the preset's registration, so the factory is ours.
|
||||
--- apps/user-ui/tests/mocks/native/common.tsx
|
||||
- expo-file-system exports removed (single source of truth; nothing else used them).
|
||||
~ Correction: the dedicated shim is NOT added to moduleNameMapper. Mapping
|
||||
^expo-file-system$ at it would make setup.ts's jest.mock factory require the
|
||||
mocked path itself (infinite recursion → "Maximum call stack size exceeded").
|
||||
Instead the mapper line is removed and setup.ts overrides the preset's
|
||||
factory with require('./mocks/native/file-system'), which resolves to an
|
||||
unmocked file.
|
||||
- Full suite after the harness fix: 5 failed / 1211 passed (54 suites, 50 pass).
|
||||
The 5 are the known pre-existing ones: REGION-31, AUTH-04, AUTH-19, CART-09,
|
||||
HOME-119. Flash (index/products/checkout) and the new STORE-23..25 pass.
|
||||
|
||||
[2026-11-02 21:34:40 IST] remove the vendor-snippets feature end to end.
|
||||
|
||||
Vendor snippets (the "ils" / vendor_snippets table: a snippet code that grants a
|
||||
vendor a slot-scoped order list and package marking) are being retired. All
|
||||
screens, APIs, types and the table go with it. db_helper_postgres is left alone
|
||||
(abandoned per AGENTS.md).
|
||||
|
||||
--- packages/db_helper_sqlite/src/db/schema.ts
|
||||
- vendorSnippets table, vendorSnippetsRelations, and the deliverySlotInfo
|
||||
vendorSnippets relation.
|
||||
--- packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts (deleted)
|
||||
--- packages/db_helper_sqlite/index.ts
|
||||
- Vendor Snippets export block.
|
||||
--- packages/db_helper_sqlite/src/admin-apis/slots.ts
|
||||
- snippet imports, mapVendorSnippet, the vendorSnippets relation on slot detail,
|
||||
the snippet create/update loop and createdSnippets in the result.
|
||||
--- packages/db_helper_sqlite/src/admin-apis/product.ts
|
||||
- unused vendorSnippets schema import.
|
||||
--- packages/shared/types/admin.ts
|
||||
- every AdminVendorSnippet* type, SlotSnippetInput, and the snippet fields on the
|
||||
slot result types.
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/vendor-snippets.ts (deleted)
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts
|
||||
- vendorSnippets router registration.
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/slots.ts
|
||||
- vendorSnippets from both slot input schemas and the create/update/detail
|
||||
mapping, including the vendor accessUrl.
|
||||
--- apps/backend/src/dbService.ts, apps/backend/src/sqliteImporter.ts
|
||||
- vendor-snippet type/function re-exports.
|
||||
--- apps/admin-ui
|
||||
- vendor-snippets screen, VendorSnippetForm, SnippetMenu, SnippetOrdersView,
|
||||
types/vendor-snippets.ts, ProductListDialog (only the snippet screen used it),
|
||||
the drawer/stack entries, the SlotForm snippet editor and the slot-details
|
||||
snippet section.
|
||||
--- apps/admin-web
|
||||
- mirror of the above: route, components, types, SlotForm/SlotForm detail,
|
||||
dashboard nav, routeTree.gen.ts entries.
|
||||
--- apps/fallback-ui
|
||||
- vendor-order-list route, its router registration and the sidebar entry, plus
|
||||
the order-details link that opened it.
|
||||
--- apps/backend/scripts/remove-test-data.ts, scripts/clear-db*.sql,
|
||||
tests/e2e/basic-sanity-setup.sh
|
||||
- vendor_snippets / vendorSnippets cleanup statements.
|
||||
--- docs/test-cases/vendor-snippets.md (deleted), docs/test-cases/README.md,
|
||||
apps/admin-ui/JEST-TEST-CASES.md
|
||||
- catalogue rows for the removed screens/tests.
|
||||
--- packages/db_helper_sqlite/drizzle/0007_drop_vendor_snippets.sql (new)
|
||||
+ drops vendor_snippets and the legacy ils table. Not executed here.
|
||||
- Historical test reports under docs/test reports/ are left as written records.
|
||||
--- apps/admin-ui/tests
|
||||
- deleted the four vendor-snippet suites and product-list-dialog.test.tsx;
|
||||
slot-details/slot-form/slot-edit/slot-add/drawer/fixtures/mocks trimmed to the
|
||||
remaining behaviour.
|
||||
--- apps/backend/tests
|
||||
- deleted admin-vendor.test.ts; removed snippet setup and ISO-08 from isolation,
|
||||
the snippet branch of CACHE-76, the vendor rows in the auth matrix, the
|
||||
snippet assertions in admin-slots, and createdSnippets from the unit mock.
|
||||
--- docs (active)
|
||||
- removed docs/test-cases/vendor-snippets.md and its references (README,
|
||||
fallback-legacy-pages, scheduled-slots, authorization, staff-authentication);
|
||||
cleaned admin-ui/backend case catalogues, the validation plan + manual guide,
|
||||
admin-ui-vs-admin-web parity and the e2e sanity plan. Historical reports
|
||||
under docs/test reports/ are untouched.
|
||||
- `packages/db_helper_sqlite/drizzle/meta/_journal.json` gained the 0007 entry.
|
||||
|
||||
[2026-11-05 22:24:32 IST] flash delivery now switches off at 8:30 PM IST instead of 9:30 PM IST.
|
||||
|
||||
15:00 UTC is 20:30 IST; the on-time (0 1 * * *, 06:30 IST) and the archive
|
||||
cron (30 20 * * *) are unchanged. The Cloudflare trigger in wrangler.prod.toml
|
||||
is the source of truth for the schedule, so it moves with the constant in the
|
||||
job itself.
|
||||
|
||||
--- apps/backend/src/lib/flash-delivery-cron.ts
|
||||
-const CRON_TURN_OFF_FLASH_DELIVERY = '0 16 * * *' // 9:30 PM IST
|
||||
+const CRON_TURN_OFF_FLASH_DELIVERY = '0 15 * * *' // 8:30 PM IST
|
||||
--- apps/backend/wrangler.prod.toml
|
||||
-crons = ["0 16 * * *", "0 1 * * *", "30 20 * * *"]
|
||||
+crons = ["0 15 * * *", "0 1 * * *", "30 20 * * *"]
|
||||
|
|
|
|||
|
|
@ -9,10 +9,10 @@
|
|||
**Spot-verified by hand:** `VariantStockDialog` absent on web, image keys vs presigned URLs, web CouponForm missing "First Order Only" (and not round-tripping it), hardcoded "Staff Member" + no staff persistence on web, "Send Welcome Msg" mobile-only, "Load more" web-only on orders/users/coupons/complaints, missing sequence refetch on web, TagForm inline errors web-only, login alert vs inline error, MultiSelect "Clear" button web-only.
|
||||
|
||||
## Parity baseline (already identical — no action)
|
||||
- **Sidebar entries:** all 14 labels in the same order on both sides (Dashboard · Products · Prices Overview · Product Groupings · Dashboard Banners · Slots · Complaints · Manage Orders · Coupons · Vendor Snippets · Stores · User Management · Send Notifications · Logout).
|
||||
- **Sidebar entries:** all 13 labels in the same order on both sides (Dashboard · Products · Prices Overview · Product Groupings · Dashboard Banners · Slots · Complaints · Manage Orders · Coupons · Stores · User Management · Send Notifications · Logout).
|
||||
- **Dashboard home:** same tiles, descriptions, category titles and category order ("Orders", "Products & Inventory", "Marketing & Promotions", "User Management", "Settings & Configuration"); no loading/empty/error states on either side.
|
||||
- **Login copy:** "Admin Login", "Staff Name", "Password", "Enter your name", "Enter your password", "Login" / "Logging in...", "Login failed".
|
||||
- **Empty/loading/error strings** match across products, tags, groupings, slots, stores, banners, orders, sequences, coupons, complaints, snippets, customize-app.
|
||||
- **Empty/loading/error strings** match across products, tags, groupings, slots, stores, banners, orders, sequences, coupons, complaints, customize-app.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -125,7 +125,6 @@
|
|||
- `PLATFORM` `admin-ui: components/OrderNotesForm.tsx:63-69` ↔ `admin-web: components/OrderNotesForm.tsx:54-60` — Cancel button: `fillColor="gray1"` vs `variant="blue" className="bg-gray-400 hover:bg-gray-500"`.
|
||||
- `CONTENT`/`PLATFORM` `admin-ui: components/CancelOrderDialog.tsx:19,23-48` ↔ `admin-web: components/CancelOrderDialog.tsx:17,21-24,35` — confirm: `Alert.alert('Cancel Order','Are you sure you want to cancel this order? This action cannot be undone.',[No, Yes, Cancel])` vs `window.confirm('Cancel Order? …')`; validation/error titled alerts vs `window.alert`.
|
||||
- `CONTENT`/`PLATFORM` `admin-ui: components/UserIncidentsView.tsx:26,33,41` ↔ `admin-web: components/UserIncidentsView.tsx:25,32,40` — "Incident added successfully" / "Please enter a comment or negativity score": titled alerts vs prefixed `window.alert`.
|
||||
- `ProductListDialog.tsx` and `SnippetOrdersView.tsx`: copy/behaviour identical (only DOM primitives differ).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -205,7 +204,7 @@
|
|||
|
||||
---
|
||||
|
||||
## 5. Users / coupons / customize-app / notifications / complaints / snippets
|
||||
## 5. Users / coupons / customize-app / notifications / complaints
|
||||
|
||||
### Users
|
||||
- `STRUCTURE` `admin-ui: user-management/index.tsx:108-126` ↔ `admin-web: dashboard.users.tsx:97-121` — web's list header adds "Refresh"/"Refreshing..." (with refreshing/onRefresh props); admin-ui has only the search bar + "Showing N users".
|
||||
|
|
@ -252,17 +251,6 @@
|
|||
- `PLATFORM` `admin-ui: complaints/index.tsx:98,156,185,196,223` ↔ `admin-web: dashboard.complaints.tsx:108,159,190,201,228` — icons.
|
||||
- Resolve dialog itself is an exact mirror ("Resolve Complaint" / "Add admin notes for this resolution:" / "Resolve" / "Cancel"). No filters/search on either side.
|
||||
|
||||
### Vendor snippets
|
||||
- `BEHAVIOUR` `admin-ui: vendor-snippets/index.tsx:55-67` ↔ `admin-web: dashboard.vendor-snippets.tsx:42-58` — Share: native share sheet (error alert "Failed to share link") vs `navigator.share` else clipboard + an extra `window.alert('Link copied to clipboard')`.
|
||||
- `CONTENT` `admin-ui: vendor-snippets/index.tsx:314,317` ↔ `admin-web: dashboard.vendor-snippets.tsx:294,297` — fetch-orders errors titled vs prefixed.
|
||||
- `CONTENT` `admin-ui: components/SnippetMenu.tsx:56-67,73` ↔ `admin-web: src/components/SnippetMenu.tsx:63-65,74` — delete confirm titled with Cancel/Delete vs `window.confirm('Delete Snippet? …')`; "No URL available to copy" titled vs prefixed (success toast "URL copied to clipboard" identical).
|
||||
- `CONTENT` `admin-ui: components/VendorSnippetForm.tsx:85,88,94` ↔ `admin-web: src/components/VendorSnippetForm.tsx:84,87,93` — updated/created/save-error: titled vs prefixed.
|
||||
- `CONTENT` `admin-ui: components/VendorSnippetForm.tsx:172-178` ↔ `admin-web: src/components/VendorSnippetForm.tsx:168-174` — slot dropdown placeholder "Choose a delivery slot" only on admin-ui.
|
||||
- `PLATFORM` `admin-ui: vendor-snippets/index.tsx:385` ↔ `admin-web: dashboard.vendor-snippets.tsx:363` — empty icon code-working vs Code2.
|
||||
- `PLATFORM` `admin-ui: components/SnippetMenu.tsx:115` ↔ `admin-web: src/components/SnippetMenu.tsx:122` — trigger icon dots-three-vertical vs MoreVertical (menu title/option order identical).
|
||||
- `PLATFORM` `admin-ui: components/VendorSnippetForm.tsx:203,149-162` ↔ `admin-web: src/components/VendorSnippetForm.tsx:199,148-158` — date control DatePicker vs DateInput; themed checkbox vs Checkbox component (labels/helpers match).
|
||||
- `SnippetOrdersView`: copy-identical; only the icon differs.
|
||||
|
||||
### Utility components (web has dedicated files; admin-ui uses common-ui)
|
||||
- `CONTENT` `admin-ui: packages/ui/src/components/bottom-dropdown.tsx:108-121` ↔ `admin-web: src/components/MultiSelect.tsx:46-53` — trigger text: all selected labels joined with ", " vs "N selected".
|
||||
- `BEHAVIOUR` `admin-ui: packages/ui/src/components/bottom-dropdown.tsx:335-345` ↔ `admin-web: src/components/MultiSelect.tsx:130-145` — web dialog has **Clear** + Done; admin-ui has only Done (no way to clear a multi-select in one tap). *Verified.*
|
||||
|
|
|
|||
|
|
@ -9,15 +9,15 @@ Status: proposed checklist from code inspection. Partially executed since — se
|
|||
## Scope and approach
|
||||
|
||||
This plan follows the customer-facing and operational flows in `apps/admin-ui`,
|
||||
`apps/admin-web`, `apps/user-ui`, `apps/web-ui`, `apps/superadmin-ui`, the vendor
|
||||
page in `apps/fallback-ui`, the backend tRPC routers, SQLite helpers, schema,
|
||||
`apps/admin-web`, `apps/user-ui`, `apps/web-ui`, `apps/superadmin-ui`, the legacy
|
||||
pages in `apps/fallback-ui`, the backend tRPC routers, SQLite helpers, schema,
|
||||
regional cache generation, and existing E2E flows. It is a workflow review, not
|
||||
a claim that every source/generated/dependency file has been read line by line.
|
||||
|
||||
The important E2E chain is:
|
||||
|
||||
**Superadmin configuration → admin changes → DB/cache publication → customer
|
||||
discovery → cart/checkout → persisted order → admin/vendor fulfillment → customer status.**
|
||||
discovery → cart/checkout → persisted order → admin fulfillment → customer status.**
|
||||
|
||||
A success toast alone is not proof. Check the result in the other app, and for
|
||||
money/ownership tests also check authoritative API data. Do not mock the backend
|
||||
|
|
@ -67,7 +67,7 @@ in these E2E journeys. Mocked screen/component tests remain a separate layer.
|
|||
in every region, so every regional assertion must be repeated for them.
|
||||
- Two active scheduled slots S1/S2 with future freeze times, plus an inactive slot,
|
||||
a frozen slot and a full-capacity slot. Assign SKUs explicitly.
|
||||
- Unique run prefix for product/tag/coupon/snippet names. Product and tag duplicate
|
||||
- Unique run prefix for product/tag/coupon names. Product and tag duplicate
|
||||
checks are currently global; do not assume the same name is allowed in B.
|
||||
- Freeze/delivery times relative to run start with generous margins. Separately
|
||||
exercise midnight/IST transitions; do not rely on hardcoded dates or slot IDs.
|
||||
|
|
@ -275,7 +275,7 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
|
|||
| OR-03 | Place order → edit instructions from customer order menu → admin refreshes; admin adds internal notes. | User notes propagate; admin notes remain correctly distinguished from customer instructions. The **customer** path rejects editing a delivered/cancelled order; the **admin** path may annotate delivered orders (business decision 2026-10-10). |
|
||||
| OR-04 | Admin packages one item then all items, verifies packaging and marks Delivered → customer refreshes tracking. | Item and aggregate packaging state agree across admin lists/details; customer sees correct fulfillment/delivery status. |
|
||||
| OR-05 | Admin reverses an accidental packaged/delivered toggle where supported → refresh both apps. | Supported reversal is consistent; forbidden transitions show clear errors. No cancelled order resurrected accidentally. |
|
||||
| OR-06 | Customer cancels pending COD order with reason → admin list/detail and vendor page refresh. | Cancelled status/reason/actor persist; cancelled order is not fulfillable or included in vendor production totals; no refund record or cash owed is shown (COD-only). |
|
||||
| OR-06 | Customer cancels pending COD order with reason → admin list/detail refresh. | Cancelled status/reason/actor persist; cancelled order is not fulfillable or included in production totals; no refund record or cash owed is shown (COD-only). |
|
||||
| OR-07 | Admin cancels pending order with reason → customer history/detail and next-order glimpse refresh. | Cancellation is attributed to admin and visible to customer; next-order summary no longer treats it as upcoming. |
|
||||
| OR-08 | Try blank reason, second cancellation and cancellation after Delivered; cancel one of two slot suborders. | Invalid cancellations reject without creating any payment/refund record; other suborder stays intact. |
|
||||
| OR-09 | Admin removes delivery charge from order → customer/admin details refresh. | Saved payable total and fee update together, exactly once; unrelated suborders stay unchanged. |
|
||||
|
|
@ -295,13 +295,11 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
|
|||
| FL-06 | Trigger staging flash enable/disable scheduled jobs → inspect all configured regions and customer app. | Expected schedule and regional values publish to KV; UI transitions without restart. This is a scheduled-job integration test, not a real-time daily wait. |
|
||||
| FL-07 | Open the 1 Hr Delivery page → inspect the header area → tap the address selector → scroll the product grid. | The address selector ("Deliver to: …" + active address) sits directly under the "Delivery in within 1 hour" header at full width, opens the address switcher, and the product grid scrolls beneath it. |
|
||||
|
||||
## L. Vendor, delivery operations, support and notifications
|
||||
## L. Delivery operations, support and notifications
|
||||
|
||||
| ID | Steps / journey | Required result |
|
||||
|---|---|---|
|
||||
| OP-01 | Admin creates slot-specific snippet for P → customer orders P+Q → vendor opens snippet URL. | Only attached SKU lines from matching noncancelled slot orders appear; quantities/summary agree; Q is not exposed by P's snippet. |
|
||||
| OP-02 | Vendor toggles P packaging → admin refreshes order details/list → reverse toggle. | Same order-item packaging state persists; other vendor/customer items remain unchanged. |
|
||||
| OP-03 | Create permanent snippet → vendor selects S1/S2 → expire/delete a slot-specific snippet and retry old link. | **OUT OF SCOPE (2026-10-10): vendor snippets are not a current concern.** Kept for traceability; not executed. (The permanent-mode metadata lookup failing is dropped with it.) |
|
||||
| OP-02 | Admin toggles P packaging in order details → refresh order details/list → reverse toggle. | Same order-item packaging state persists; other/customer items remain unchanged. |
|
||||
| OP-04 | Admin edits delivery sequence and address map coordinates → reopen delivery view and order detail. | Sequence/map changes persist and stay within region; operational coordinate override does not silently mutate customer's region/bound identity. |
|
||||
| OP-05 | Customer raises complaint on own order with photo → admin A views and resolves → customer views response. | Correct order/customer/photo/body/response/status across apps; admin B cannot resolve A complaint. Repeat with general complaint without an order. |
|
||||
| OP-06 | Customer creates product review/rating/photo → admin opens matching review and responds → customer refreshes detail. | **OUT OF SCOPE (2026-10-10): the review feature is no longer maintained.** Kept for traceability; not executed. (Any review findings — e.g. `createReview` failing for SKU-split products — are dropped with the feature.) |
|
||||
|
|
@ -329,12 +327,11 @@ the present implementation.
|
|||
| ID | Steps / journey | Required result |
|
||||
|---|---|---|
|
||||
| SEC-01 | Customer token/anonymous request calls staff CRUD; staff token calls superadmin region/staff/global-config APIs; try legacy admin global-config mutation too. | Unauthorized identities are denied; hiding an admin screen is not the access control. |
|
||||
| SEC-02 | Admin B supplies A IDs to product/store/slot/tag/group/banner/coupon/snippet/order/complaint reads and mutations; mix A/B relation IDs in an otherwise valid save. | No cross-region reads/mutations/associations; rejected mixed save leaves no partial state. |
|
||||
| SEC-02 | Admin B supplies A IDs to product/store/slot/tag/group/banner/coupon/order/complaint reads and mutations; mix A/B relation IDs in an otherwise valid save. | No cross-region reads/mutations/associations; rejected mixed save leaves no partial state. |
|
||||
| SEC-03 | U2 supplies U1 address/order/complaint/payment IDs to read/edit/cancel/delete operations. | Ownership is enforced, not only authentication; U1's data is unchanged. |
|
||||
| SEC-04 | Order request mixes A region with B SKU/slot/bound/address, or a SKU not assigned to that slot. Also test a **global** product (regionId null). | All submitted identities/relations are validated server-side; no foreign or incoherent order accepted (4xx). A **global** product is valid in every region and may be attached to any region's slot; a product of another region is rejected, and a scheduled order's SKU must still be carried by the chosen slot. |
|
||||
| SEC-05 | Submit empty items, zero/negative/fractional quantities, invalid/null regular slot, deleted/suspended/OOS SKU, frozen/inactive slot and full slot. | Backend enforces actual purchasability/quantity/slot rules; bypassing UI guards cannot create an invalid order. |
|
||||
| SEC-06 | U2 applies U1 coupon directly; apply expired/invalid/foreign-region/SKU-ineligible coupon; race usage and reserved redemption. | User scoping and one-time limits are authoritative and atomic; expired codes are rejected. Global coupons are expected to apply in any region and to any SKU (policy), so those two probes assert success, not rejection. |
|
||||
| SEC-07 | Vendor request edits packaging using an unrelated item ID; expired snippet queries another slot; anonymous caller tries same mutation without valid snippet authority. | Vendor access is constrained to authorized snippet/region/items. A public vendor URL is not authority to edit every order item. |
|
||||
| SEC-08 | Reuse revoked/deleted staff identity/token → attempt region-bound mutation; change staff region in superadmin then retry old session. | Access reflects current staff assignment/existence, not a stale token's region. |
|
||||
|
||||
## O. Payments (Cash on Delivery only)
|
||||
|
|
@ -442,22 +439,17 @@ is not yet defined, agree the contract rather than write a test that endorses a
|
|||
region-filtered; checkout validation checks expiry/minimum/usage/first-order,
|
||||
but does not visibly enforce all user/product/region restrictions. See
|
||||
`CP-04`/`CP-05`/`CP-11`/`SEC-06` and the user coupon/order DB helpers.
|
||||
6. **Vendor authority needs a release gate.** Packaging mutation is public and
|
||||
accepts an item ID without snippet code; the selected-slot snippet query does
|
||||
not visibly enforce expiration like the other snippet query. Permanent-link
|
||||
UI initially calls a metadata endpoint that requires a slot. See `OP-03` and
|
||||
`SEC-07`, `vendor-snippets.ts` and fallback `vendor-order-list.tsx`.
|
||||
7. **Persistence tests must use current code.** Older cart documentation describes
|
||||
6. **Persistence tests must use current code.** Older cart documentation describes
|
||||
mount-only remove/re-add reconciliation; current `useReconcileCartSlots`
|
||||
preserves lines and updates their slot. Do not derive expected behavior from
|
||||
historical docs alone. See `CT-04`/`SL-07`, current `cart-query-hooks.tsx`.
|
||||
8. **Existing E2E is a starting point, not complete coverage.**
|
||||
7. **Existing E2E is a starting point, not complete coverage.**
|
||||
`tests/e2e/add-product.yaml`, `add-slot-with-product.yaml` and `user-order.yaml`
|
||||
cover part of the main chain. The user-order flow assumes older auth/address
|
||||
placement (automatic login route and checkout address selection), and needs
|
||||
alignment with current Cart/Me login walls and read-only Checkout. Add
|
||||
regional selection and persisted-order/admin assertions.
|
||||
9. **Writes that fail after committing.** Several endpoints perform the DB write first and a follow-up step
|
||||
8. **Writes that fail after committing.** Several endpoints perform the DB write first and a follow-up step
|
||||
(upload-URL claim, image cleanup, KV mirror) afterwards, so a failing follow-up used to abort the request
|
||||
with the row already stored (product, tag, review). Pre-validate, then write, then treat follow-ups as
|
||||
best-effort — see section `P`.
|
||||
|
|
|
|||
|
|
@ -294,7 +294,7 @@ strong{font-weight:650}
|
|||
<h3 id="2-6-users-complaints-and-notifications">2.6 Users, complaints and notifications</h3>
|
||||
<p><strong>What this tests:</strong> finding customers, suspending them, adding incidents, replying to complaints and sending notifications.</p>
|
||||
<p><strong>Steps:</strong></p>
|
||||
<ol><li>Open <strong>User Management</strong>. Search by Customer 1's name and mobile.</li><li>Sign in as Admin B and search for the same customer.</li><li>Open a customer. Suspend, unsuspend, and add an incident note.</li><li>Open <strong>Complaints</strong>, open a customer complaint, reply and resolve it.</li><li>Open the customer app and check the reply.</li><li>Open <strong>Send Notifications</strong>, select a test user, and send a test message.</li><li>Open <strong>Constants</strong> and change a test setting; check the customer app.</li><li>If <strong>Vendor Snippets</strong> is enabled for your test, open it, create a snippet, add a product, and open the slot picker. Refresh the website and try again.</li><li>Open a screen with no data (for example, a new area with no orders) and use the back/Retry buttons.</li></ol>
|
||||
<ol><li>Open <strong>User Management</strong>. Search by Customer 1's name and mobile.</li><li>Sign in as Admin B and search for the same customer.</li><li>Open a customer. Suspend, unsuspend, and add an incident note.</li><li>Open <strong>Complaints</strong>, open a customer complaint, reply and resolve it.</li><li>Open the customer app and check the reply.</li><li>Open <strong>Send Notifications</strong>, select a test user, and send a test message.</li><li>Open <strong>Constants</strong> and change a test setting; check the customer app.</li><li>Open a screen with no data (for example, a new area with no orders) and use the back/Retry buttons.</li></ol>
|
||||
<p><strong>What you should see:</strong></p>
|
||||
<table>
|
||||
<thead><tr><th>Check</th><th>Expected result</th></tr></thead>
|
||||
|
|
@ -303,7 +303,6 @@ strong{font-weight:650}
|
|||
<tr><td><code>ADM-29</code></td><td>Admin B cannot find Admin A's customers by name or mobile.</td></tr>
|
||||
<tr><td><code>ADM-30</code></td><td>Suspension and incidents are saved; notifications go only to selected test users.</td></tr>
|
||||
<tr><td><code>ADM-31</code></td><td>Complaints are area-scoped and the customer sees the reply.</td></tr>
|
||||
<tr><td><code>ADM-32</code></td><td>Vendor snippets stay in your area and the slot picker still loads after a refresh.</td></tr>
|
||||
<tr><td><code>ADM-33</code></td><td>The changed setting appears for the customer; the other area is unchanged.</td></tr>
|
||||
<tr><td><code>ADM-35</code></td><td>Empty/loading/error screens show a clear message; Retry/back works.</td></tr>
|
||||
</tbody></table>
|
||||
|
|
@ -423,9 +422,9 @@ strong{font-weight:650}
|
|||
<ol><li>Superadmin: change global product G.</li><li>Admin A: immediately change a banner or product in A.</li><li>Wait up to two minutes.</li><li>Refresh the customer apps in A and B.</li></ol>
|
||||
<p><strong>What you should see:</strong> <code>E2E-10</code> — both areas show the global change; A also shows its local change.</p>
|
||||
<h3 id="4-11-admin-website-refresh">4.11 Admin website refresh</h3>
|
||||
<p><strong>What this tests:</strong> an admin website refresh keeps you signed in and keeps the slot picker working.</p>
|
||||
<p><strong>What this tests:</strong> an admin website refresh keeps you signed in and keeps the data loading.</p>
|
||||
<p><strong>Steps:</strong></p>
|
||||
<ol><li>Sign in to the admin website and open <strong>Vendor Snippets</strong>.</li><li>Refresh the browser.</li><li>Create/edit a snippet and open the slot picker.</li><li>Repeat after signing out and in as Admin B.</li></ol>
|
||||
<ol><li>Sign in to the admin website and open <strong>Slots</strong>.</li><li>Refresh the browser.</li><li>Open a slot.</li><li>Repeat after signing out and in as Admin B.</li></ol>
|
||||
<p><strong>What you should see:</strong> <code>E2E-11</code> — you stay signed in with the right area and the slots load.</p>
|
||||
<h3 id="4-12-superadmin-admin-notification">4.12 Superadmin admin notification</h3>
|
||||
<p><strong>What this tests:</strong> sending a notification to admins.</p>
|
||||
|
|
@ -498,7 +497,7 @@ strong{font-weight:650}
|
|||
<ol><li>Superadmin: create a 20% global coupon.</li><li>Edit it to ₹50 and save.</li><li>Use it in the customer app.</li></ol>
|
||||
<p><strong>Expected:</strong> the discount should be ₹50 only. If 20% is still applied, record it as <code>BR-14</code> (known issue).</p>
|
||||
<h3 id="br-15-admin-website-after-refresh">BR-15 — Admin website after refresh</h3>
|
||||
<ol><li>Sign in to the admin website.</li><li>Refresh the page.</li><li>Open Vendor Snippets and the slot picker.</li></ol>
|
||||
<ol><li>Sign in to the admin website.</li><li>Refresh the page.</li><li>Open Slots and a slot detail.</li></ol>
|
||||
<p><strong>Expected:</strong> you stay signed in and the slots load.</p>
|
||||
<h3 id="br-16-superadmin-admin-notification">BR-16 — Superadmin admin notification</h3>
|
||||
<ol><li>Superadmin: Send Notifications → Admin Notifs.</li><li>Send a test message.</li><li>Check the result.</li></ol>
|
||||
|
|
@ -518,9 +517,6 @@ strong{font-weight:650}
|
|||
<hr>
|
||||
<h2 id="6-other-screens-only-if-your-coordinator-says-they-are-active">6. Other screens (only if your coordinator says they are active)</h2>
|
||||
<p>Some screens are not part of normal testing. Test them only if your coordinator confirms they are in use for this release.</p>
|
||||
<h3 id="6-1-vendor-page">6.1 Vendor page</h3>
|
||||
<ol><li>Open the vendor page link and sign in with the provided test code.</li><li>Open the order list and choose an order.</li><li>Mark an item packaged and verified.</li><li>Try a different/incorrect test code.</li></ol>
|
||||
<p><strong>What you should see:</strong> <code>COND-01</code> — the vendor sees only their orders and can package them; a wrong code is rejected.</p>
|
||||
<h3 id="6-2-reviews">6.2 Reviews</h3>
|
||||
<ol><li>As a customer, open a delivered order or product and write a review with an image.</li><li>As an admin, open <strong>Reviews</strong> and reply.</li><li>Check the customer can see the reply.</li></ol>
|
||||
<p><strong>What you should see:</strong> <code>COND-02</code> — the review and reply are saved and visible. If reviews are not active, skip this check.</p>
|
||||
|
|
|
|||
|
|
@ -510,9 +510,7 @@ replying to complaints and sending notifications.
|
|||
5. Open the customer app and check the reply.
|
||||
6. Open **Send Notifications**, select a test user, and send a test message.
|
||||
7. Open **Constants** and change a test setting; check the customer app.
|
||||
8. If **Vendor Snippets** is enabled for your test, open it, create a snippet,
|
||||
add a product, and open the slot picker. Refresh the website and try again.
|
||||
9. Open a screen with no data (for example, a new area with no orders) and use
|
||||
8. Open a screen with no data (for example, a new area with no orders) and use
|
||||
the back/Retry buttons.
|
||||
|
||||
**What you should see:**
|
||||
|
|
@ -523,7 +521,6 @@ replying to complaints and sending notifications.
|
|||
| `ADM-29` | Admin B cannot find Admin A's customers by name or mobile. |
|
||||
| `ADM-30` | Suspension and incidents are saved; notifications go only to selected test users. |
|
||||
| `ADM-31` | Complaints are area-scoped and the customer sees the reply. |
|
||||
| `ADM-32` | Vendor snippets stay in your area and the slot picker still loads after a refresh. |
|
||||
| `ADM-33` | The changed setting appears for the customer; the other area is unchanged. |
|
||||
| `ADM-35` | Empty/loading/error screens show a clear message; Retry/back works. |
|
||||
|
||||
|
|
@ -809,13 +806,13 @@ shows its local change.
|
|||
### 4.11 Admin website refresh
|
||||
|
||||
**What this tests:** an admin website refresh keeps you signed in and keeps the
|
||||
slot picker working.
|
||||
data loading.
|
||||
|
||||
**Steps:**
|
||||
|
||||
1. Sign in to the admin website and open **Vendor Snippets**.
|
||||
1. Sign in to the admin website and open **Slots**.
|
||||
2. Refresh the browser.
|
||||
3. Create/edit a snippet and open the slot picker.
|
||||
3. Open a slot.
|
||||
4. Repeat after signing out and in as Admin B.
|
||||
|
||||
**What you should see:** `E2E-11` — you stay signed in with the right area and
|
||||
|
|
@ -1022,7 +1019,7 @@ as `BR-14` (known issue).
|
|||
|
||||
1. Sign in to the admin website.
|
||||
2. Refresh the page.
|
||||
3. Open Vendor Snippets and the slot picker.
|
||||
3. Open Slots and a slot detail.
|
||||
|
||||
**Expected:** you stay signed in and the slots load.
|
||||
|
||||
|
|
@ -1073,16 +1070,6 @@ disabled.
|
|||
Some screens are not part of normal testing. Test them only if your coordinator
|
||||
confirms they are in use for this release.
|
||||
|
||||
### 6.1 Vendor page
|
||||
|
||||
1. Open the vendor page link and sign in with the provided test code.
|
||||
2. Open the order list and choose an order.
|
||||
3. Mark an item packaged and verified.
|
||||
4. Try a different/incorrect test code.
|
||||
|
||||
**What you should see:** `COND-01` — the vendor sees only their orders and can
|
||||
package them; a wrong code is rejected.
|
||||
|
||||
### 6.2 Reviews
|
||||
|
||||
1. As a customer, open a delivered order or product and write a review with an
|
||||
|
|
|
|||
|
|
@ -119,7 +119,7 @@ Rules for L7:
|
|||
| Money | per-bound free-delivery threshold T and fee D; flash threshold/fee; T−0.01/T/T+0.01. |
|
||||
| Coupons | regional A/B, global, percent, flat, targeted, whole-cart, capped, min-spend, exclusive, first-order, limited-use, personal, expired, invalidated, reserved. |
|
||||
| Orders | pending COD, packaged, verified, delivered, cancelled, multi-slot group, flash, historical product-deleted. |
|
||||
| Content | tags, groups, banners, upload assets, complaints, notifications, vendor snippets (conditional). |
|
||||
| Content | tags, groups, banners, upload assets, complaints, notifications. |
|
||||
| Notifications | sandbox queue and approved test recipients only. |
|
||||
|
||||
### Data rules
|
||||
|
|
@ -332,7 +332,6 @@ Each change below has dedicated cases in §7.
|
|||
| BE-ADMIN-15 | P0 | Search customers by name/mobile in A; same search in B. | Only customers with A/B orders respectively; no cross-region mobile leakage (`BR-01`). |
|
||||
| BE-ADMIN-16 | P1 | Customer detail, order history, suspension/unsuspension, incidents. | Region-scoped; suspension blocks ordering; incident audit correct. |
|
||||
| BE-ADMIN-17 | P0 | `sendAdminNotification` as staff, customer, anonymous. | Staff allowed; customer/anonymous denied; no queue write on denial. |
|
||||
| BE-ADMIN-18 | P1 | Vendor snippet CRUD, order/slot reads, packaging (conditional). | Scoped to staff region; unauthorized IDs denied. |
|
||||
| BE-ADMIN-19 | P1 | Complaints list/reply/resolve in A; B complaint invisible. | Region isolation; customer sees the reply. |
|
||||
| BE-ADMIN-20 | P1 | Region constants edit and propagation to A bounds. | A customer discovery/pricing changes; B unchanged. |
|
||||
| BE-ADMIN-21 | P0 | `getStaff`, `createStaffUser`, `getRoles`, `savePushToken` as customer. | Denied (protectedProcedure is not a staff guard — regression check). |
|
||||
|
|
@ -516,7 +515,6 @@ Run each case on `admin-ui` and `admin-web`; note platform-specific reload/stora
|
|||
| ADM-29 | P0 | Search a U1 mobile from staff B; search same name with A/B customers. | B sees nothing/only B; A sees only A (`BR-01`). |
|
||||
| ADM-30 | P1 | User incidents and notifications to selected users. | Incident audit correct; notification queued only for allowed recipients. |
|
||||
| ADM-31 | P1 | Complaints list/reply/resolve. | Region-scoped; customer sees the reply. |
|
||||
| ADM-32 | P1 | Vendor snippets: create/edit/delete, order/slot reads. | Region-scoped; slot picker works after reload (web, `BR-15`). |
|
||||
| ADM-33 | P1 | Region constants edit. | A customer discovery/pricing changes; B unchanged. |
|
||||
| ADM-34 | P1 | Upload product/store/banner images. | Upload succeeds; URL persisted; replaced image cleanup safe. |
|
||||
| ADM-35 | P2 | Empty/loading/error states across dashboard routes. | Retry/back navigation works; no permanent spinner. |
|
||||
|
|
@ -555,7 +553,6 @@ Run only when product/operations confirms support. `N/A` requires a reason.
|
|||
|
||||
| ID | P | Case | Expected |
|
||||
|---|---|---|---|
|
||||
| COND-01 | P2 | Vendor snippet page: login, list orders, open packaging. | Scoped to the snippet/staff region; packaging correct. |
|
||||
| COND-02 | P2 | Reviews: create a review with image; admin response. | Persisted/visible if the feature is supported; otherwise N/A. |
|
||||
| COND-03 | P2 | OTP login in an isolated provider sandbox. | Account created/authenticated once; no real SMS; otherwise N/A. |
|
||||
| COND-04 | P2 | Legacy fallback login/home/order-details pages. | Only supported ownership paths are exercised; demos/unsupported pages are N/A with reason. |
|
||||
|
|
@ -576,7 +573,7 @@ Only these critical chains use the real backend and real clients.
|
|||
| E2E-08 | P0 | Web scheduled checkout with items in two slots. | No null-slot rejection; correct slots persisted (`BR-06`). |
|
||||
| E2E-09 | P0 | Staff B searches U1's name/mobile; staff A searches same. | B cannot see A customer; A can (`BR-01`). |
|
||||
| E2E-10 | P0 | Global product edit → both region caches refresh → customers in A/B see it. | All regions publish; regional edit does not narrow (`BR-05`). |
|
||||
| E2E-11 | P1 | Admin-web reload → vendor snippet slot picker. | Slots load; staff/region restored (`BR-15`). |
|
||||
| E2E-11 | P1 | Admin-web reload → slots screen. | Slots load; staff/region restored (`BR-15`). |
|
||||
| E2E-12 | P1 | Superadmin sends "Admin Notifs" to admins. | Queued, not UNAUTHORIZED (`BR-16`). |
|
||||
| E2E-13 | P0 | Authorization probe: customer token against admin/superadmin mutations; staff against superadmin. | Denied at every step; no writes. |
|
||||
| E2E-14 | P1 | Product soft-delete after an order; customer/admin order history. | Original name/amount render; catalog removes it. |
|
||||
|
|
@ -606,7 +603,7 @@ These cases must be automated first; they encode the defects found in the
|
|||
| BR-12 | P0 | Two ₹101 sub-orders + two ₹101 stackable coupons. | Discounts `[101, 101]`; totals `[0, 0]`; no negative; delivery handled separately. | `apps/backend/tests/api/coupon-math.test.ts` + `packages/shared` via API |
|
||||
| BR-13 | P2 | Historical order with a coupon-implied discount after migration. | `discount_amount` is `0` (accepted): invoices show no discount; derivation is not required. | `apps/backend/tests/api/order-lifecycle.test.ts` — **accepted limitation** |
|
||||
| BR-14 | P1 | Change a global coupon 20% → ₹50 and save. | Percent is cleared; pricing uses ₹50. | `apps/backend/tests/api/coupons.test.ts` — **known open** |
|
||||
| BR-15 | P1 | Admin-web reload on the vendor snippet screen. | `admin.staffUser.me` restores staff/region; slots load. | `apps/admin-web/tests/flows/vendor-snippets.test.tsx` |
|
||||
| BR-15 | P1 | Admin-web reload on a region-scoped screen. | `admin.staffUser.me` restores staff/region; data loads. | `apps/admin-web/tests/flows/auth-restore.test.tsx` |
|
||||
| BR-16 | P0 | Superadmin sends an admin notification. | `superadmin.staff.sendAdminNotification` succeeds; staff endpoint still staff-guarded. | `apps/backend/tests/api/admin-ops.test.ts` |
|
||||
| BR-17 | P0 | Customer checkout and order detail. | COD only; no online-payment method/routes; disabled "coming soon" card if present. | `apps/backend/tests/api/order-flow.test.ts` + customer UI flows |
|
||||
| BR-18 | P0 | Scheduled order with one null slot and one valid slot. | Rejected; no partial order; valid per-line slots succeed. | `apps/backend/tests/api/place-order-edge-cases.test.ts` |
|
||||
|
|
@ -649,7 +646,7 @@ Recommended new files:
|
|||
- Customer native: `tests/flows/region.test.tsx`, `cart-region.test.tsx`, `checkout-slots.test.tsx`, `flash.test.tsx`, `orders.test.tsx`.
|
||||
- Admin native: `tests/flows/region-scope.test.tsx`, `global-products.test.tsx`, `order-pagination.test.tsx`, `store-safety.test.tsx`.
|
||||
- Customer web: `tests/flows/discovery.test.tsx`, `cart.test.tsx`, `checkout.test.tsx`, `orders.test.tsx`, `auth.test.tsx`.
|
||||
- Admin web: `tests/flows/auth-restore.test.tsx`, `orders.test.tsx`, `products-global.test.tsx`, `vendor-snippets.test.tsx`.
|
||||
- Admin web: `tests/flows/auth-restore.test.tsx`, `orders.test.tsx`, `products-global.test.tsx`.
|
||||
- Superadmin: `src/routes/regions.test.tsx`, `staff.test.tsx`, `global-products.test.tsx`, `global-coupons.test.tsx`, `send-notifications.test.tsx`.
|
||||
- E2E: `tests/e2e/multi-region-order.yaml`, `tests/e2e-web/critical-journeys.spec.ts`.
|
||||
|
||||
|
|
@ -683,7 +680,7 @@ CI split:
|
|||
| Historical `discount_amount = 0` backfill | **Accepted** | `BR-13` asserts the accepted behavior; do not block release on it. |
|
||||
| Server-side order idempotency | Deferred | Characterize concurrent submits; UI guard is required; do not assert deduplication. |
|
||||
| OTP login/SMS | Approval-only | Excluded from default regression; use an isolated provider sandbox. |
|
||||
| Reviews, vendor snippets, legacy fallback pages | Conditional | Run only if product/operations confirms support. |
|
||||
| Reviews, legacy fallback pages | Conditional | Run only if product/operations confirms support. |
|
||||
| Online payments | Removed | Assert COD-only; no gateway routes/UI. |
|
||||
| Admin `protectedProcedure` endpoints (`getStaff`, `createStaffUser`, `getRoles`, `savePushToken`) | **Pending decision** | `BE-ADMIN-21` encodes the staff-only expectation; if customers are intentionally allowed, document it and downgrade the case. |
|
||||
| No emulator/browser in the authoring environment | Process limitation | Cases are static proposals until a device/browser is available. |
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ This folder contains feature-by-feature acceptance and regression checklists for
|
|||
|
||||
Inventory: **45 feature checklists and 855 uniquely identified cases**, plus this index. Features are grouped by business responsibility; closely related operations share a checklist (for example stock, offer flags and suspension). Reuse the shared boundary/security matrix rather than assuming a finite list can cover every possible input.
|
||||
|
||||
Sources: current routers/screens/helpers, existing API tests, [sanity plan](../e2e-sanity-test-plan.md), and [branch review](../multi-region-i2-review.md). Older sanity-plan statements that coupons ignore regions/SKUs are superseded here by the newer coupon requirements. Vendor snippets and reviews remain conditional/legacy coverage. Checkout is COD-only; online payment is not part of this release.
|
||||
Sources: current routers/screens/helpers, existing API tests, [sanity plan](../e2e-sanity-test-plan.md), and [branch review](../multi-region-i2-review.md). Older sanity-plan statements that coupons ignore regions/SKUs are superseded here by the newer coupon requirements. Reviews remain conditional/legacy coverage. Checkout is COD-only; online payment is not part of this release.
|
||||
|
||||
## How to use each checklist
|
||||
|
||||
|
|
@ -54,7 +54,7 @@ Use unique run prefixes. Do not delete regions for cleanup: region deletion is u
|
|||
| Order operations | [Placement/history](orders.md), [Fulfillment](fulfillment.md), [Cancellation](cancellation.md), [Edits/rebalance](order-edits-rebalance.md), [Delivery sequence/maps](delivery-operations.md) |
|
||||
| Support | [Complaints](complaints.md), [Customer operations/incidents](customer-management-incidents.md), [Notifications](notifications.md) **(EXCLUDED from automated run — see below)** |
|
||||
| Infrastructure | [Uploads](uploads-images.md), [Cache publication](cache-publication.md), [Jobs/health](jobs-health.md) **(queue/scheduler cases EXCLUDED — see below)**, [Security](authorization-api-contracts.md), [Recovery/platform/accessibility](recovery-platform-accessibility.md) |
|
||||
| Conditional/legacy | [Vendor snippets](vendor-snippets.md), [Reviews](reviews.md), [Fallback/legacy pages](fallback-legacy-pages.md) **(EXCLUDED — see below)** |
|
||||
| Conditional/legacy | [Reviews](reviews.md), [Fallback/legacy pages](fallback-legacy-pages.md) **(EXCLUDED — see below)** |
|
||||
| Approval-required provider integration | [OTP authentication](otp-authentication.md) (isolated provider sandbox only; excluded from default password regression) |
|
||||
| Excluded from automated regression | [Notifications/push](notifications.md) (**skipped by owner instruction** for the 2026-10-18 run; cases retained, marked `SKIPPED`, never `PASS`/`FAIL`) |
|
||||
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ For **each relevant route**, test anonymous, U1, U2, staff A, staff B, superadmi
|
|||
| SEC-08 | P0 | Regional edit of global product structural fields/global suspension. | Only authorized market fields writable; globally shared structure protected. |
|
||||
| SEC-09 | P0 | Public catalog/detail/summary upload/token routes inspected. | Only intended public fields/contexts; no internal notes or credentials. |
|
||||
| SEC-10 | P0 | Mixed-region checkout and foreign address-bound pairing. | Coherent region/address/SKU/slot/bound validation; no fee manipulation. |
|
||||
| SEC-11 | P0 | Item packaging with unrelated item ID or vendor authority. | Item association/allowed snippet scope checked server-side. |
|
||||
| SEC-11 | P0 | Item packaging with an unrelated order item ID. | Item association is checked server-side. |
|
||||
| SEC-12 | P0 | Invalid/empty ID, whitespace/numeric-prefix string, huge/nonfinite IDs. | Schema rejects malformed identity; no accidental parseInt target. |
|
||||
| SEC-13 | P1 | Unknown key, wrong-scope constant key, incorrect type, null vs omission. | Contract explicit; unexpected write fields don't bypass restrictions. |
|
||||
| SEC-14 | P0 | Customer-supplied money, creator ID, user ID, cancellation actor. | Server-owned fields not trusted; financial/audit identity correct. |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Fallback and legacy standalone pages — conditional
|
||||
|
||||
Scope inventory: fallback login, user-home/user-details/order-details, location-marker, user-connect, create-coupon, vendor-order-list, super-admin, inauguration, home/demo. Presence of a route does not imply supported release functionality. Validate active ownership with product/operations; unsupported/demo pages are N/A with reason, not PASS.
|
||||
Scope inventory: fallback login, user-home/user-details/order-details, location-marker, user-connect, create-coupon, super-admin, inauguration, home/demo. Presence of a route does not imply supported release functionality. Validate active ownership with product/operations; unsupported/demo pages are N/A with reason, not PASS.
|
||||
|
||||
> **STATUS: EXCLUDED from the automated run (2026-10-18).**
|
||||
> The fallback/legacy standalone app (`apps/fallback-ui`) is **out of scope for this release cycle** (low priority —
|
||||
|
|
@ -16,7 +16,6 @@ Scope inventory: fallback login, user-home/user-details/order-details, location-
|
|||
| LEGACY-05 | P1 | Missing/malformed marker params/coords and permission denied. | Recoverable validation; no arbitrary write or endless map. |
|
||||
| LEGACY-06 | P0 | Standalone coupon creation from staff A vs customer/B/global attempt. | Same current regional/global authoring restrictions as primary router. |
|
||||
| LEGACY-07 | P1 | User-connect flow with approved identity/link. | No cross-account join/impersonation; link policy explicit. |
|
||||
| LEGACY-08 | P1 | Vendor page expired/permanent/missing snippet. | Conditional vendor authority enforced; useful empty/error state. |
|
||||
| LEGACY-09 | P2 | Inauguration/demo promotional page. | No production mutation, secret exposure or broken supported navigation. |
|
||||
| LEGACY-10 | P1 | Browser refresh/back/cold direct route. | No stale local auth assumption; correct guarded page. |
|
||||
| LEGACY-11 | P1 | Active backend endpoint changed since legacy UI shipped. | Current request schema (boundId/couponIds/skuId) respected; no `as any`-hidden mismatch. |
|
||||
|
|
@ -24,4 +23,4 @@ Scope inventory: fallback login, user-home/user-details/order-details, location-
|
|||
| LEGACY-13 | P1 | Network/asset error, corrupt local state. | Recoverable safe behavior; no false order/compensation success. |
|
||||
| LEGACY-14 | P2 | Mobile browser keyboard/safe-area/maps and desktop layout. | Supported active pages remain usable and accessible. |
|
||||
|
||||
See [vendor](vendor-snippets.md), [security](authorization-api-contracts.md), [configuration](constants-configuration.md). Require a support decision per route before including legacy pages in a release gate.
|
||||
See [security](authorization-api-contracts.md) and [configuration](constants-configuration.md). Require a support decision per route before including legacy pages in a release gate.
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ Scope: admin slot CRUD/assignment/capacity, customer slot discovery/cart choices
|
|||
| SLOT-13 | P1 | Selected S1 removed/closed while S2 valid. | Clear deterministic fallback/reselection; quantity preserved. |
|
||||
| SLOT-14 | P1 | All slots unavailable for a cart SKU. | Unavailable line identified/excluded; no phantom fee/charge. |
|
||||
| SLOT-15 | P1 | Simultaneous checkout near capacity/manual full toggle. | Record agreed capacity guarantee; no silent bypass of committed full state. |
|
||||
| SLOT-16 | P1 | Slot update fails during related snippet/group writes. | No partial slot state; retry coherent. |
|
||||
| SLOT-16 | P1 | Slot update fails during related group writes. | No partial slot state; retry coherent. |
|
||||
| SLOT-17 | P1 | Empty slot and slot with only hidden/deleted SKUs. | Intentional empty state; no invalid customer purchase. |
|
||||
| SLOT-18 | P1 | Historical slot soft removal/deactivation or expired time. | Existing order time/history preserved; only new purchase blocked. |
|
||||
| SLOT-19 | P2 | Many slots sorted across dates, picker refresh/scroll. | Stable chronological order and correct selected slot ID. |
|
||||
|
|
|
|||
|
|
@ -18,6 +18,6 @@ Scope: `admin.staffUser.login`, `superadmin.auth.login/me`, staff auth contexts
|
|||
| SAUTH-12 | P2 | Keyboard/password visibility toggle and accessible errors. | Password protected; input usable on each platform. |
|
||||
| SAUTH-13 | P1 | Same identity uses native/web simultaneously. | Region/role agreement; supported session behavior documented. |
|
||||
| SAUTH-14 | P0 | Login response/log inspection. | No password hashes or signing secrets exposed. |
|
||||
| SAUTH-15 | P1 | Admin-web reload on a region-scoped screen, specifically Vendor Snippets. | The stored sign-in is restored, staff identity and region are re-fetched, and region-scoped controls such as the slot picker load without another login. |
|
||||
| SAUTH-15 | P1 | Admin-web reload on a region-scoped screen (for example Slots). | The stored sign-in is restored, staff identity and region are re-fetched, and region-scoped data loads without another login. |
|
||||
|
||||
See [authorization](authorization-api-contracts.md) for the complete role matrix.
|
||||
|
|
|
|||
|
|
@ -1,23 +0,0 @@
|
|||
# Vendor snippets — conditional/legacy
|
||||
|
||||
**Status:** Existing routes remain, but prior product scope marked snippets out of current daily sanity. Execute only if operations restores support or approves security coverage. Do not mark unsupported UI paths PASS. Scope: admin snippet CRUD, fallback vendor page, public snippet order/slot reads and packaging.
|
||||
|
||||
| ID | Priority | Action / input | Expected result |
|
||||
|---|---|---|---|
|
||||
| VENDOR-01 | P1 | Create A slot-specific snippet for P only; order P+Q. | Vendor sees only authorized P lines, correct noncancelled slot quantities. |
|
||||
| VENDOR-02 | P1 | Permanent snippet chooses supported upcoming slot. | Correct slot metadata/selection and intended authorized lines. |
|
||||
| VENDOR-03 | P1 | Edit SKU set/expiry/code; reopen URL. | Updated authority/data; old link policy explicit. |
|
||||
| VENDOR-04 | P0 | Expired/deleted/missing code or wrong slot. | No private order read or packaging authority. |
|
||||
| VENDOR-05 | P0 | Unrelated order-item ID in packaging mutation. | Denied; snippet URL does not authorize arbitrary item IDs. |
|
||||
| VENDOR-06 | P0 | A snippet uses B SKU/group/slot or reads B order. | Regional association/isolation enforced. |
|
||||
| VENDOR-07 | P1 | Vendor packages/unpackages permitted item. | Same state in admin/customer where intended; other items unchanged. |
|
||||
| VENDOR-08 | P1 | Cancelled/delivered/past orders and empty slot. | Production-demand policy correct; no cancelled quantity counted. |
|
||||
| VENDOR-09 | P1 | Duplicate/empty SKUs, duplicate code and invalid expiry. | Validations/deduplication; no partial snippet. |
|
||||
| VENDOR-10 | P1 | Same SKU multiple orders/quantities/split groups. | Correct summed demand, distinct authorized order items. |
|
||||
| VENDOR-11 | P1 | Permanent mode missing slot/metadata. | Useful supported selection/error, not endless loader or crash. |
|
||||
| VENDOR-12 | P0 | Anonymous access without valid snippet authority. | No arbitrary vendor data or mutation exposure. |
|
||||
| VENDOR-13 | P1 | Packaging races admin cancellation/delivery. | Legal coherent final state; cancelled order not revived. |
|
||||
| VENDOR-14 | P1 | Delete/update fails midway or request retried. | No partial authority expansion or duplicate relation. |
|
||||
| VENDOR-15 | P2 | Mobile vendor page refresh/back, long demand list. | Correct saved state, readable totals and no stale cross-slot results. |
|
||||
|
||||
Policy checkpoint: snippet credential/expiry enforcement, PII exposure, permanent-code behavior and legal packaging transitions. Security probes require staging fixtures even though routes are public.
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
-- Migration: retire vendor snippets.
|
||||
--
|
||||
-- The vendor-snippet feature (screens, admin router, shared types) has been
|
||||
-- removed from the application. Both the current table name and the legacy
|
||||
-- `ils` name are dropped so environments migrated at different points converge.
|
||||
DROP TABLE IF EXISTS `vendor_snippets`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE IF EXISTS `ils`;
|
||||
|
|
@ -50,6 +50,13 @@
|
|||
"when": 1791367872000,
|
||||
"tag": "0006_regions_and_superadmins",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 7,
|
||||
"version": "6",
|
||||
"when": 1793635740881,
|
||||
"tag": "0007_drop_vendor_snippets",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -164,21 +164,6 @@ export {
|
|||
createUserIncident,
|
||||
} from './src/admin-apis/user'
|
||||
|
||||
export {
|
||||
// Vendor Snippets
|
||||
checkVendorSnippetExists,
|
||||
getVendorSnippetById,
|
||||
getVendorSnippetByCode,
|
||||
getAllVendorSnippets,
|
||||
createVendorSnippet,
|
||||
updateVendorSnippet,
|
||||
deleteVendorSnippet,
|
||||
getProductsByIds,
|
||||
getVendorSlotById,
|
||||
getVendorOrdersBySlotId,
|
||||
updateVendorOrderItemPackaging,
|
||||
} from './src/admin-apis/vendor-snippets'
|
||||
|
||||
export {
|
||||
// User Address
|
||||
getDefaultAddress as getUserDefaultAddress,
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ import {
|
|||
orderItems,
|
||||
coupons,
|
||||
reservedCoupons,
|
||||
vendorSnippets,
|
||||
homeBanners,
|
||||
keyValStore,
|
||||
} from '../db/schema'
|
||||
|
|
|
|||
|
|
@ -4,25 +4,20 @@ import {
|
|||
productInfo,
|
||||
productSkus,
|
||||
skuFeatures,
|
||||
vendorSnippets,
|
||||
productGroupInfo,
|
||||
} from '../db/schema'
|
||||
import { and, asc, desc, eq, gt, inArray, lte, sql } from 'drizzle-orm'
|
||||
import type {
|
||||
AdminDeliverySlot,
|
||||
AdminSlotWithProducts,
|
||||
AdminSlotWithProductsAndSnippetsBase,
|
||||
AdminSlotDetails,
|
||||
AdminSlotCreateResult,
|
||||
AdminSlotUpdateResult,
|
||||
AdminVendorSnippet,
|
||||
AdminSlotProductSummary,
|
||||
AdminUpdateSlotCapacityResult,
|
||||
} from '@packages/shared'
|
||||
import { coerceDate } from '../lib/date'
|
||||
|
||||
// Single source in @packages/shared (admin.ts); groupIds unused in sqlite.
|
||||
import type { SlotSnippetInput } from '@packages/shared'
|
||||
|
||||
const getStringArray = (value: unknown): string[] | null => {
|
||||
if (!Array.isArray(value)) return null
|
||||
return value.map((item) => String(item))
|
||||
|
|
@ -107,16 +102,6 @@ const mapSlotSkuSummary = (sku: { id: number; images: unknown; name: string | nu
|
|||
features: (sku.features || []).map((f) => ({ featureName: f.featureName, featureValue: f.featureValue })),
|
||||
})
|
||||
|
||||
const mapVendorSnippet = (snippet: typeof vendorSnippets.$inferSelect): AdminVendorSnippet => ({
|
||||
id: snippet.id,
|
||||
snippetCode: snippet.snippetCode,
|
||||
slotId: snippet.slotId ?? null,
|
||||
skuIds: snippet.skuIds || [],
|
||||
isPermanent: snippet.isPermanent,
|
||||
validTill: coerceDate(snippet.validTill),
|
||||
createdAt: coerceDate(snippet.createdAt) ?? new Date(0),
|
||||
})
|
||||
|
||||
export async function getActiveSlotsWithProducts(regionId: number, limit: number = 20): Promise<AdminSlotWithProducts[]> {
|
||||
const slots = await db.query.deliverySlotInfo
|
||||
.findMany({
|
||||
|
|
@ -205,15 +190,12 @@ export async function getSlotsAfterDate(regionId: number | null, afterDate: Date
|
|||
return slots.map(mapDeliverySlot)
|
||||
}
|
||||
|
||||
export async function getSlotByIdWithRelations(regionId: number, id: number): Promise<AdminSlotWithProductsAndSnippetsBase | null> {
|
||||
export async function getSlotByIdWithRelations(regionId: number, id: number): Promise<AdminSlotDetails | null> {
|
||||
const slot = await db.query.deliverySlotInfo.findFirst({
|
||||
where: and(
|
||||
eq(deliverySlotInfo.id, id),
|
||||
eq(deliverySlotInfo.regionId, regionId)
|
||||
),
|
||||
with: {
|
||||
vendorSnippets: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!slot) {
|
||||
|
|
@ -235,7 +217,6 @@ export async function getSlotByIdWithRelations(regionId: number, id: number): Pr
|
|||
deliverySequence: getNumberArray(slot.deliverySequence),
|
||||
groupIds: getNumberArray(slot.groupIds),
|
||||
products: skusData.map((sku: any) => mapSlotSkuSummary(sku)),
|
||||
vendorSnippets: slot.vendorSnippets.map(mapVendorSnippet),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -244,10 +225,9 @@ export async function createSlotWithRelations(input: {
|
|||
freezeTime: string
|
||||
isActive?: boolean
|
||||
skuIds?: number[]
|
||||
vendorSnippets?: SlotSnippetInput[]
|
||||
groupIds?: number[]
|
||||
}, regionId: number): Promise<AdminSlotCreateResult> {
|
||||
const { deliveryTime, freezeTime, isActive, skuIds, vendorSnippets: snippets, groupIds } = input
|
||||
const { deliveryTime, freezeTime, isActive, skuIds, groupIds } = input
|
||||
|
||||
const normalizedSkuIds = normalizeSkuIds(skuIds)
|
||||
|
||||
|
|
@ -286,33 +266,8 @@ export async function createSlotWithRelations(input: {
|
|||
})
|
||||
.returning()
|
||||
|
||||
let createdSnippets: AdminVendorSnippet[] = []
|
||||
if (snippets && snippets.length > 0) {
|
||||
for (const snippet of snippets) {
|
||||
await assertSkuIdsInRegion(tx, snippet.skuIds, regionId, 'SKU')
|
||||
|
||||
const existingSnippet = await tx.query.vendorSnippets.findFirst({
|
||||
where: eq(vendorSnippets.snippetCode, snippet.name),
|
||||
})
|
||||
if (existingSnippet) {
|
||||
throw new Error(`Snippet name "${snippet.name}" already exists`)
|
||||
}
|
||||
|
||||
const [createdSnippet] = await tx.insert(vendorSnippets).values({
|
||||
regionId,
|
||||
snippetCode: snippet.name,
|
||||
slotId: newSlot.id,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill ? new Date(snippet.validTill) : undefined,
|
||||
}).returning()
|
||||
|
||||
createdSnippets.push(mapVendorSnippet(createdSnippet))
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
slot: mapDeliverySlot(newSlot),
|
||||
createdSnippets,
|
||||
message: 'Slot created successfully',
|
||||
}
|
||||
})
|
||||
|
|
@ -326,10 +281,9 @@ export async function updateSlotWithRelations(regionId: number, input: {
|
|||
freezeTime: string
|
||||
isActive?: boolean
|
||||
skuIds?: number[]
|
||||
vendorSnippets?: SlotSnippetInput[]
|
||||
groupIds?: number[]
|
||||
}): Promise<AdminSlotUpdateResult | null> {
|
||||
const { id, deliveryTime, freezeTime, isActive, skuIds, vendorSnippets: snippets, groupIds } = input
|
||||
const { id, deliveryTime, freezeTime, isActive, skuIds, groupIds } = input
|
||||
|
||||
const slot = await db.query.deliverySlotInfo.findFirst({
|
||||
where: and(eq(deliverySlotInfo.id, id), eq(deliverySlotInfo.regionId, regionId)),
|
||||
|
|
@ -378,33 +332,8 @@ export async function updateSlotWithRelations(regionId: number, input: {
|
|||
return null
|
||||
}
|
||||
|
||||
let createdSnippets: AdminVendorSnippet[] = []
|
||||
if (snippets && snippets.length > 0) {
|
||||
for (const snippet of snippets) {
|
||||
await assertSkuIdsInRegion(tx, snippet.skuIds, regionId, 'SKU')
|
||||
|
||||
const existingSnippet = await tx.query.vendorSnippets.findFirst({
|
||||
where: eq(vendorSnippets.snippetCode, snippet.name),
|
||||
})
|
||||
if (existingSnippet) {
|
||||
throw new Error(`Snippet name "${snippet.name}" already exists`)
|
||||
}
|
||||
|
||||
const [createdSnippet] = await tx.insert(vendorSnippets).values({
|
||||
regionId: updatedSlot.regionId as number,
|
||||
snippetCode: snippet.name,
|
||||
slotId: id,
|
||||
skuIds: snippet.skuIds,
|
||||
validTill: snippet.validTill ? new Date(snippet.validTill) : undefined,
|
||||
}).returning()
|
||||
|
||||
createdSnippets.push(mapVendorSnippet(createdSnippet))
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
slot: mapDeliverySlot(updatedSlot),
|
||||
createdSnippets,
|
||||
message: 'Slot updated successfully',
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,285 +0,0 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { vendorSnippets, deliverySlotInfo, productInfo, productSkus, orders, orderItems, orderStatus } from '../db/schema'
|
||||
import { desc, eq, and, inArray } from 'drizzle-orm'
|
||||
import type { InferSelectModel } from 'drizzle-orm'
|
||||
import type {
|
||||
AdminDeliverySlot,
|
||||
AdminVendorSnippet,
|
||||
AdminVendorSnippetWithSlot,
|
||||
AdminVendorSnippetProduct,
|
||||
AdminVendorUpdatePackagingResult,
|
||||
} from '@packages/shared'
|
||||
import { coerceDate } from '../lib/date'
|
||||
import { attachOrderItems } from '../lib/order-items'
|
||||
import type { SlotRow } from '../user-apis/slots'
|
||||
|
||||
type VendorSnippetRow = InferSelectModel<typeof vendorSnippets>
|
||||
type DeliverySlotRow = SlotRow
|
||||
|
||||
const mapVendorSnippet = (snippet: VendorSnippetRow): AdminVendorSnippet => ({
|
||||
id: snippet.id,
|
||||
snippetCode: snippet.snippetCode,
|
||||
slotId: snippet.slotId ?? null,
|
||||
skuIds: snippet.skuIds || [],
|
||||
isPermanent: snippet.isPermanent,
|
||||
validTill: coerceDate(snippet.validTill),
|
||||
createdAt: coerceDate(snippet.createdAt) ?? new Date(0),
|
||||
})
|
||||
|
||||
const mapDeliverySlot = (slot: DeliverySlotRow): AdminDeliverySlot => ({
|
||||
id: slot.id,
|
||||
deliveryTime: coerceDate(slot.deliveryTime) ?? new Date(0),
|
||||
freezeTime: coerceDate(slot.freezeTime) ?? new Date(0),
|
||||
isActive: slot.isActive,
|
||||
isFlash: slot.isFlash,
|
||||
isCapacityFull: slot.isCapacityFull,
|
||||
deliverySequence: slot.deliverySequence,
|
||||
groupIds: slot.groupIds,
|
||||
})
|
||||
|
||||
const mapProductSummary = (product: { id: number; name: string }): AdminVendorSnippetProduct => ({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
})
|
||||
|
||||
export async function checkVendorSnippetExists(snippetCode: string): Promise<boolean> {
|
||||
const existingSnippet = await db.query.vendorSnippets.findFirst({
|
||||
where: eq(vendorSnippets.snippetCode, snippetCode),
|
||||
})
|
||||
return !!existingSnippet
|
||||
}
|
||||
|
||||
export async function getVendorSnippetById(regionId: number, id: number): Promise<AdminVendorSnippetWithSlot | null> {
|
||||
const snippet = await db.query.vendorSnippets.findFirst({
|
||||
where: and(
|
||||
eq(vendorSnippets.id, id),
|
||||
eq(vendorSnippets.regionId, regionId)
|
||||
),
|
||||
with: {
|
||||
slot: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!snippet) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
...mapVendorSnippet(snippet),
|
||||
slot: snippet.slot ? mapDeliverySlot(snippet.slot) : null,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getVendorSnippetByCode(regionId: number | null, snippetCode: string): Promise<AdminVendorSnippet | null> {
|
||||
const snippet = await db.query.vendorSnippets.findFirst({
|
||||
where: regionId == null
|
||||
? eq(vendorSnippets.snippetCode, snippetCode)
|
||||
: and(
|
||||
eq(vendorSnippets.snippetCode, snippetCode),
|
||||
eq(vendorSnippets.regionId, regionId)
|
||||
),
|
||||
})
|
||||
|
||||
return snippet ? mapVendorSnippet(snippet) : null
|
||||
}
|
||||
|
||||
export async function getAllVendorSnippets(regionId: number): Promise<AdminVendorSnippetWithSlot[]> {
|
||||
const snippets = await db.query.vendorSnippets.findMany({
|
||||
where: eq(vendorSnippets.regionId, regionId),
|
||||
with: {
|
||||
slot: true,
|
||||
},
|
||||
orderBy: desc(vendorSnippets.createdAt),
|
||||
})
|
||||
|
||||
return snippets.map((snippet: VendorSnippetRow & { slot: DeliverySlotRow | null }) => ({
|
||||
...mapVendorSnippet(snippet),
|
||||
slot: snippet.slot ? mapDeliverySlot(snippet.slot) : null,
|
||||
}))
|
||||
}
|
||||
|
||||
const assertSnippetSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionId: number): Promise<void> => {
|
||||
const unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))]
|
||||
if (unique.length === 0) return
|
||||
const rows = await txOrDb.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, unique),
|
||||
with: { product: { columns: { regionId: true } } },
|
||||
columns: { id: true },
|
||||
})
|
||||
if (rows.length !== unique.length) {
|
||||
const found = new Set(rows.map((r: { id: number }) => r.id))
|
||||
throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`)
|
||||
}
|
||||
const foreign = rows.filter((r: any) => r.product?.regionId !== regionId)
|
||||
if (foreign.length > 0) {
|
||||
throw new Error(`SKU ${foreign.map((r: any) => r.id).join(', ')} belongs to a different region`)
|
||||
}
|
||||
}
|
||||
|
||||
const assertSnippetSlotInRegion = async (txOrDb: any, slotId: number, regionId: number): Promise<void> => {
|
||||
const slot = await txOrDb.query.deliverySlotInfo.findFirst({
|
||||
where: eq(deliverySlotInfo.id, slotId),
|
||||
columns: { id: true, regionId: true },
|
||||
})
|
||||
if (!slot) {
|
||||
throw new Error('Invalid slot ID')
|
||||
}
|
||||
if (slot.regionId !== regionId) {
|
||||
throw new Error('Slot belongs to a different region')
|
||||
}
|
||||
}
|
||||
|
||||
export async function createVendorSnippet(input: {
|
||||
snippetCode: string
|
||||
slotId?: number
|
||||
skuIds: number[]
|
||||
isPermanent: boolean
|
||||
validTill?: Date
|
||||
regionId: number
|
||||
}): Promise<AdminVendorSnippet> {
|
||||
if (input.slotId != null) {
|
||||
await assertSnippetSlotInRegion(db, input.slotId, input.regionId)
|
||||
}
|
||||
await assertSnippetSkuIdsInRegion(db, input.skuIds, input.regionId)
|
||||
|
||||
const [result] = await db.insert(vendorSnippets).values({
|
||||
regionId: input.regionId,
|
||||
snippetCode: input.snippetCode,
|
||||
slotId: input.slotId,
|
||||
skuIds: input.skuIds,
|
||||
isPermanent: input.isPermanent,
|
||||
validTill: input.validTill,
|
||||
}).returning()
|
||||
|
||||
return mapVendorSnippet(result)
|
||||
}
|
||||
|
||||
export async function updateVendorSnippet(regionId: number, id: number, updates: {
|
||||
snippetCode?: string
|
||||
slotId?: number | null
|
||||
skuIds?: number[]
|
||||
isPermanent?: boolean
|
||||
validTill?: Date | null
|
||||
}): Promise<AdminVendorSnippet | null> {
|
||||
const existing = await db.query.vendorSnippets.findFirst({
|
||||
where: and(eq(vendorSnippets.id, id), eq(vendorSnippets.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (!existing) {
|
||||
return null
|
||||
}
|
||||
if (updates.slotId != null) {
|
||||
await assertSnippetSlotInRegion(db, updates.slotId, regionId)
|
||||
}
|
||||
if (updates.skuIds !== undefined) {
|
||||
await assertSnippetSkuIdsInRegion(db, updates.skuIds, regionId)
|
||||
}
|
||||
|
||||
const [result] = await db.update(vendorSnippets)
|
||||
.set(updates)
|
||||
.where(and(eq(vendorSnippets.id, id), eq(vendorSnippets.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
return result ? mapVendorSnippet(result) : null
|
||||
}
|
||||
|
||||
export async function deleteVendorSnippet(regionId: number, id: number): Promise<AdminVendorSnippet | null> {
|
||||
const [result] = await db.delete(vendorSnippets)
|
||||
.where(and(eq(vendorSnippets.id, id), eq(vendorSnippets.regionId, regionId)))
|
||||
.returning()
|
||||
|
||||
return result ? mapVendorSnippet(result) : null
|
||||
}
|
||||
|
||||
export async function getProductsByIds(regionId: number | null, skuIds: number[]): Promise<AdminVendorSnippetProduct[]> {
|
||||
if (skuIds.length === 0) return []
|
||||
const skus = await db.query.productSkus.findMany({
|
||||
where: inArray(productSkus.id, skuIds),
|
||||
with: { product: { columns: { name: true, regionId: true } } },
|
||||
columns: { id: true, isDeleted: true },
|
||||
})
|
||||
|
||||
return skus
|
||||
.filter((sku) => !sku.isDeleted && (regionId == null || sku.product?.regionId === regionId))
|
||||
.map((sku) => ({
|
||||
id: sku.id,
|
||||
name: sku.product?.name ?? 'Unknown',
|
||||
})) as AdminVendorSnippetProduct[]
|
||||
}
|
||||
|
||||
export async function getVendorSlotById(regionId: number | null, slotId: number): Promise<AdminDeliverySlot | null> {
|
||||
const slot = await db.query.deliverySlotInfo.findFirst({
|
||||
where: regionId == null
|
||||
? eq(deliverySlotInfo.id, slotId)
|
||||
: and(
|
||||
eq(deliverySlotInfo.id, slotId),
|
||||
eq(deliverySlotInfo.regionId, regionId)
|
||||
),
|
||||
})
|
||||
|
||||
return slot ? mapDeliverySlot(slot) : null
|
||||
}
|
||||
|
||||
export async function getVendorOrdersBySlotId(regionId: number | null, slotId: number) {
|
||||
const rows = await db.query.orders.findMany({
|
||||
where: regionId == null
|
||||
? eq(orders.slotId, slotId)
|
||||
: and(
|
||||
eq(orders.slotId, slotId),
|
||||
eq(orders.regionId, regionId)
|
||||
),
|
||||
with: {
|
||||
orderStatus: true,
|
||||
user: true,
|
||||
slot: true,
|
||||
},
|
||||
orderBy: desc(orders.createdAt),
|
||||
})
|
||||
|
||||
return attachOrderItems(rows)
|
||||
}
|
||||
|
||||
export async function updateVendorOrderItemPackaging(
|
||||
orderItemId: number,
|
||||
isPackaged: boolean
|
||||
): Promise<AdminVendorUpdatePackagingResult> {
|
||||
const orderItem = await db.query.orderItems.findFirst({
|
||||
where: eq(orderItems.id, orderItemId),
|
||||
with: {
|
||||
order: {
|
||||
with: {
|
||||
slot: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!orderItem) {
|
||||
return { success: false, message: 'Order item not found' }
|
||||
}
|
||||
|
||||
if (!orderItem.order.slotId) {
|
||||
return { success: false, message: 'Order item not associated with a vendor slot' }
|
||||
}
|
||||
|
||||
const snippetExists = await db.query.vendorSnippets.findFirst({
|
||||
where: eq(vendorSnippets.slotId, orderItem.order.slotId),
|
||||
})
|
||||
|
||||
if (!snippetExists) {
|
||||
return { success: false, message: "No vendor snippet found for this order's slot" }
|
||||
}
|
||||
|
||||
const [updatedItem] = await db.update(orderItems)
|
||||
.set({
|
||||
is_packaged: isPackaged,
|
||||
})
|
||||
.where(eq(orderItems.id, orderItemId))
|
||||
.returning({ id: orderItems.id })
|
||||
|
||||
if (!updatedItem) {
|
||||
return { success: false, message: 'Failed to update packaging status' }
|
||||
}
|
||||
|
||||
return { success: true, orderItemId, is_packaged: isPackaged }
|
||||
}
|
||||
|
|
@ -322,17 +322,6 @@ export const deliverySlotInfo = sqliteTable('delivery_slot_info', {
|
|||
skuIds: jsonText<number[]>('sku_ids').$defaultFn(() => []),
|
||||
})
|
||||
|
||||
export const vendorSnippets = sqliteTable('vendor_snippets', {
|
||||
id: integer().primaryKey({ autoIncrement: true }),
|
||||
regionId: integer('region_id').references(() => regions.id),
|
||||
snippetCode: text('snippet_code').notNull().unique(),
|
||||
slotId: integer('slot_id').references(() => deliverySlotInfo.id),
|
||||
isPermanent: integer('is_permanent', { mode: 'boolean' }).notNull().default(false),
|
||||
skuIds: jsonText<number[]>('sku_ids').notNull(),
|
||||
validTill: timestampText('valid_till'),
|
||||
createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
|
||||
})
|
||||
|
||||
export const specialDeals = sqliteTable('special_deals', {
|
||||
id: integer().primaryKey({ autoIncrement: true }),
|
||||
skuId: integer('sku_id').notNull().references(() => productSkus.id),
|
||||
|
|
@ -715,7 +704,6 @@ export const productTagsRelations = relations(productTags, ({ one }) => ({
|
|||
|
||||
export const deliverySlotInfoRelations = relations(deliverySlotInfo, ({ many }) => ({
|
||||
orders: many(orders),
|
||||
vendorSnippets: many(vendorSnippets),
|
||||
}))
|
||||
|
||||
export const specialDealsRelations = relations(specialDeals, ({ one }) => ({
|
||||
|
|
@ -836,10 +824,6 @@ export const userIncidentsRelations = relations(userIncidents, ({ one }) => ({
|
|||
addedBy: one(staffUsers, { fields: [userIncidents.addedBy], references: [staffUsers.id] }),
|
||||
}))
|
||||
|
||||
export const vendorSnippetsRelations = relations(vendorSnippets, ({ one }) => ({
|
||||
slot: one(deliverySlotInfo, { fields: [vendorSnippets.slotId], references: [deliverySlotInfo.id] }),
|
||||
}))
|
||||
|
||||
export const regionsRelations = relations(regions, ({ many }) => ({
|
||||
bounds: many(regionBounds),
|
||||
consts: many(regionConsts),
|
||||
|
|
|
|||
|
|
@ -518,44 +518,14 @@ export interface AdminSlotProductSummary {
|
|||
features?: { featureName: string | null; featureValue: string }[];
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippet {
|
||||
id: number;
|
||||
snippetCode: string;
|
||||
slotId: number | null;
|
||||
skuIds: number[];
|
||||
isPermanent: boolean;
|
||||
validTill: Date | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippetWithAccess extends AdminVendorSnippet {
|
||||
accessUrl: string;
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippetWithSlot extends AdminVendorSnippet {
|
||||
slot: AdminDeliverySlot | null;
|
||||
}
|
||||
|
||||
export type AdminVendorSnippetProduct = IdName
|
||||
|
||||
export interface AdminVendorSnippetWithProducts extends AdminVendorSnippetWithSlot {
|
||||
accessUrl: string;
|
||||
products: AdminVendorSnippetProduct[];
|
||||
}
|
||||
|
||||
export interface AdminSlotWithProducts extends AdminDeliverySlot {
|
||||
deliverySequence: number[];
|
||||
products: AdminSlotProductSummary[];
|
||||
}
|
||||
|
||||
export interface AdminSlotWithProductsAndSnippets extends AdminSlotWithProducts {
|
||||
/** Slot detail also restores the selected product groups. */
|
||||
export interface AdminSlotDetails extends AdminSlotWithProducts {
|
||||
groupIds: number[];
|
||||
vendorSnippets: AdminVendorSnippetWithAccess[];
|
||||
}
|
||||
|
||||
export interface AdminSlotWithProductsAndSnippetsBase extends AdminSlotWithProducts {
|
||||
groupIds: number[];
|
||||
vendorSnippets: AdminVendorSnippet[];
|
||||
}
|
||||
|
||||
export interface AdminSlotsResult {
|
||||
|
|
@ -569,12 +539,11 @@ export interface AdminSlotsListResult {
|
|||
}
|
||||
|
||||
export interface AdminSlotResult {
|
||||
slot: AdminSlotWithProductsAndSnippets;
|
||||
slot: AdminSlotDetails;
|
||||
}
|
||||
|
||||
export interface AdminSlotCreateResult {
|
||||
slot: AdminDeliverySlot;
|
||||
createdSnippets: AdminVendorSnippet[];
|
||||
message: string;
|
||||
}
|
||||
|
||||
|
|
@ -603,106 +572,3 @@ export interface AdminUpdateSlotCapacityResult {
|
|||
slot: AdminDeliverySlot;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Single complete form input for vendor-snippet create + update — callers
|
||||
// always send every field (no partial shapes). Derived from the row; validTill
|
||||
// is the wire type (ISO string) — the row keeps Date.
|
||||
export type AdminVendorSnippetInput = Omit<AdminVendorSnippet, 'id' | 'createdAt' | 'validTill'> & {
|
||||
validTill: string | null
|
||||
}
|
||||
|
||||
// Slot-level snippet input (group-model) — sqlite carries skuIds and leaves
|
||||
// groupIds unused; the admin-ui SlotForm uses both.
|
||||
export interface SlotSnippetInput {
|
||||
name: string
|
||||
groupIds: number[]
|
||||
skuIds: number[]
|
||||
validTill: string | null
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippetDeleteResult {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippetOrderProduct {
|
||||
orderItemId: number;
|
||||
productId: number;
|
||||
productName: string;
|
||||
quantity: number;
|
||||
productSize: number;
|
||||
price: number;
|
||||
unit: string;
|
||||
subtotal: number;
|
||||
is_packaged: boolean;
|
||||
is_package_verified: boolean;
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippetOrderSummary {
|
||||
orderId: string;
|
||||
orderDate: string;
|
||||
customerName: string;
|
||||
totalAmount: number;
|
||||
slotInfo: {
|
||||
time: string;
|
||||
sequence: unknown;
|
||||
} | null;
|
||||
products: AdminVendorSnippetOrderProduct[];
|
||||
matchedProducts: number[];
|
||||
snippetCode: string;
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippetOrdersResult {
|
||||
success: boolean;
|
||||
data: AdminVendorSnippetOrderSummary[];
|
||||
snippet: {
|
||||
id: number;
|
||||
snippetCode: string;
|
||||
slotId: number | null;
|
||||
skuIds: number[];
|
||||
validTill?: string;
|
||||
createdAt: string;
|
||||
isPermanent: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AdminVendorSnippetOrdersWithSlotResult extends AdminVendorSnippetOrdersResult {
|
||||
selectedSlot: {
|
||||
id: number;
|
||||
deliveryTime: string;
|
||||
freezeTime: string;
|
||||
deliverySequence: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AdminVendorOrderSummary {
|
||||
id: number;
|
||||
status: string;
|
||||
orderDate: string;
|
||||
totalQuantity: number;
|
||||
products: {
|
||||
name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface AdminUpcomingSlotsResult {
|
||||
success: boolean;
|
||||
data: {
|
||||
id: number;
|
||||
deliveryTime: string;
|
||||
freezeTime: string;
|
||||
deliverySequence: unknown;
|
||||
}[];
|
||||
}
|
||||
|
||||
export type AdminVendorUpdatePackagingResult =
|
||||
| {
|
||||
success: true;
|
||||
orderItemId: number;
|
||||
is_packaged: boolean;
|
||||
}
|
||||
| {
|
||||
success: false;
|
||||
message: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,10 +47,9 @@ DROP TABLE IF EXISTS orders;
|
|||
DROP TABLE IF EXISTS payment_info;
|
||||
DROP TABLE IF EXISTS coupon_applicable_users;
|
||||
|
||||
-- ---- coupons & snippets ----
|
||||
-- ---- coupons ----
|
||||
DROP TABLE IF EXISTS coupons;
|
||||
DROP TABLE IF EXISTS reserved_coupons;
|
||||
DROP TABLE IF EXISTS vendor_snippets;
|
||||
DROP TABLE IF EXISTS delivery_slot_info;
|
||||
|
||||
-- ---- content/catalog ----
|
||||
|
|
|
|||
|
|
@ -44,10 +44,9 @@ DROP TABLE IF EXISTS coupon_applicable_users;
|
|||
-- Folded into `coupons.sku_ids` by the regional migration; still present on old DBs.
|
||||
DROP TABLE IF EXISTS coupon_applicable_products;
|
||||
|
||||
-- ---- coupons & snippets ----
|
||||
-- ---- coupons ----
|
||||
DROP TABLE IF EXISTS coupons;
|
||||
DROP TABLE IF EXISTS reserved_coupons;
|
||||
DROP TABLE IF EXISTS vendor_snippets;
|
||||
DROP TABLE IF EXISTS delivery_slot_info;
|
||||
|
||||
-- ---- content/catalog ----
|
||||
|
|
|
|||
|
|
@ -245,7 +245,6 @@ slot = trpc(
|
|||
"freezeTime": iso(freeze),
|
||||
"isActive": True,
|
||||
"skuIds": [sku_500g, sku_1kg, sku_combo],
|
||||
"vendorSnippets": [],
|
||||
"groupIds": [],
|
||||
},
|
||||
)["slot"]
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue