enh
This commit is contained in:
parent
442e20c88a
commit
2cb1cfd807
26 changed files with 1245 additions and 552 deletions
6
apps/admin-ui/.expo/types/router.d.ts
vendored
6
apps/admin-ui/.expo/types/router.d.ts
vendored
File diff suppressed because one or more lines are too long
|
|
@ -895,6 +895,9 @@ Use these fixture names in the cases below.
|
|||
| AOD-23 | happy | Back to orders | route |
|
||||
| AOD-24 | edge | customer link | user detail route |
|
||||
| AOD-25 | edge | no OrderOptionsMenu on details | only the explicit Cancel/Back actions are present (current) |
|
||||
| AOD-26 | edge | delivered timestamp | "Delivered on …" when deliveredAt is set |
|
||||
| AOD-27 | edge | not delivered | no delivered timestamp |
|
||||
| AOD-28 | edge | packed timestamp | per-item "Packed …" only when packagedAt is set |
|
||||
|
||||
### 13.2 OrderNotesForm / CancelOrderDialog / OrderOptionsMenu
|
||||
|
||||
|
|
|
|||
|
|
@ -182,6 +182,17 @@ export default function OrderDetails() {
|
|||
Placed on {dayjs(order.createdAt).format("MMM DD, YYYY • h:mm A")}
|
||||
</MyText>
|
||||
</View>
|
||||
{order.deliveredAt && (
|
||||
<View
|
||||
testID="order-delivered-at"
|
||||
style={tw`flex-row items-center bg-green-50 p-3 rounded-xl mt-2`}
|
||||
>
|
||||
<MaterialIcons name="check-circle" size={20} color="#10B981" />
|
||||
<MyText style={tw`ml-2 text-green-800 font-medium`}>
|
||||
Delivered on {dayjs(order.deliveredAt).format("MMM DD, YYYY • h:mm A")}
|
||||
</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Cancellation Reason */}
|
||||
|
|
@ -403,6 +414,14 @@ export default function OrderDetails() {
|
|||
</MyText>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
{item.packagedAt && (
|
||||
<MyText
|
||||
testID={`order-item-packaged-at-${item.id}`}
|
||||
style={tw`text-[10px] text-gray-400 mt-1`}
|
||||
>
|
||||
Packed {dayjs(item.packagedAt).format("MMM DD, YYYY • h:mm A")}
|
||||
</MyText>
|
||||
)}
|
||||
</View>
|
||||
<MyText style={tw`text-sm font-bold text-gray-900`}>
|
||||
₹{item.amount}
|
||||
|
|
|
|||
|
|
@ -196,8 +196,7 @@ export default function EditProduct() {
|
|||
newImageUrls: allUploadUrls,
|
||||
} as any)
|
||||
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
Alert.alert('Success', 'Product updated successfully!')
|
||||
productFormRef.current?.clearImages()
|
||||
} catch (error: any) {
|
||||
|
|
@ -241,8 +240,7 @@ export default function EditProduct() {
|
|||
deletedImageKeys: [],
|
||||
newImageUrls: [],
|
||||
} as any)
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
Alert.alert('Success', 'Market data updated for your region')
|
||||
} catch (error: any) {
|
||||
Alert.alert('Error', error.message || 'Failed to update product')
|
||||
|
|
|
|||
|
|
@ -61,8 +61,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
|
|||
{ name, password },
|
||||
{
|
||||
onSuccess: async (data) => {
|
||||
await saveJWT(data.token);
|
||||
await saveStaff(data.staff);
|
||||
await Promise.all([
|
||||
saveJWT(data.token),
|
||||
saveStaff(data.staff),
|
||||
]);
|
||||
setStaff(data.staff);
|
||||
setIsLoggedIn(true);
|
||||
// A push tapped while signed out waits here; land on it first.
|
||||
|
|
@ -77,8 +79,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
|
|||
};
|
||||
|
||||
const logout = async () => {
|
||||
await deleteJWT();
|
||||
await deleteStaff();
|
||||
await Promise.all([
|
||||
deleteJWT(),
|
||||
deleteStaff(),
|
||||
]);
|
||||
setIsLoggedIn(false);
|
||||
setStaff(null);
|
||||
queryClient.clear();
|
||||
|
|
|
|||
3
apps/admin-ui/tests/fixtures/index.ts
vendored
3
apps/admin-ui/tests/fixtures/index.ts
vendored
|
|
@ -312,10 +312,11 @@ export const ORDER_DETAILS = {
|
|||
adminNotes: null,
|
||||
userNotes: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
deliveredAt: null,
|
||||
status: 'pending',
|
||||
isPackaged: false,
|
||||
isDelivered: false,
|
||||
items: ORDER_ITEMS.map((i) => ({ ...i, quantity: String(i.quantity), price: String(i.price) })),
|
||||
items: ORDER_ITEMS.map((i) => ({ ...i, quantity: String(i.quantity), price: String(i.price), packagedAt: null })),
|
||||
cancelReason: null,
|
||||
cancellationReviewed: false,
|
||||
couponData: null,
|
||||
|
|
|
|||
|
|
@ -357,4 +357,40 @@ describe('Order details (AOD-01..25)', () => {
|
|||
expect(view.getByTestId('order-details-cancel-button')).toBeTruthy()
|
||||
expect(view.getByTestId('order-details-back-button')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AOD-26: the delivered timestamp renders when the order is delivered', async () => {
|
||||
setProcedure('admin.order.getOrderDetails', {
|
||||
data: order({
|
||||
status: 'delivered',
|
||||
isDelivered: true,
|
||||
isPackaged: true,
|
||||
deliveredAt: '2026-11-10T10:15:00.000Z',
|
||||
}),
|
||||
})
|
||||
const view = await renderDetails()
|
||||
|
||||
expect(view.getByTestId('order-delivered-at')).toBeTruthy()
|
||||
expect(view.getByText(/Delivered on/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('AOD-27: no delivered timestamp before the order is delivered', async () => {
|
||||
const view = await renderDetails()
|
||||
|
||||
expect(view.queryByTestId('order-delivered-at')).toBeNull()
|
||||
})
|
||||
|
||||
it('AOD-28: a packaged item shows when it was packed', async () => {
|
||||
const items = ORDER_DETAILS.items.map((item, index) =>
|
||||
index === 0
|
||||
? { ...item, isPackaged: true, packagedAt: '2026-11-10T09:30:00.000Z' }
|
||||
: { ...item, isPackaged: true, packagedAt: null },
|
||||
)
|
||||
setProcedure('admin.order.getOrderDetails', { data: order({ items }) })
|
||||
const view = await renderDetails()
|
||||
|
||||
expect(view.getByTestId('order-item-packaged-at-1')).toBeTruthy()
|
||||
expect(view.getByText(/Packed/)).toBeTruthy()
|
||||
// A packaged item with no recorded time renders no timestamp.
|
||||
expect(view.queryByTestId('order-item-packaged-at-2')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
Zap,
|
||||
CircleAlert,
|
||||
Check,
|
||||
CheckCircle,
|
||||
Package,
|
||||
Truck,
|
||||
ChevronRight,
|
||||
|
|
@ -192,6 +193,17 @@ function OrderDetails() {
|
|||
Placed on {dayjs(order.createdAt).format('MMM DD, YYYY • h:mm A')}
|
||||
</MyText>
|
||||
</div>
|
||||
{order.deliveredAt && (
|
||||
<div
|
||||
data-testid="order-delivered-at"
|
||||
className="mt-2 flex flex-row items-center rounded-xl bg-green-50 p-3"
|
||||
>
|
||||
<CheckCircle size={20} color="#10B981" />
|
||||
<MyText className="ml-2 font-medium text-green-800">
|
||||
Delivered on {dayjs(order.deliveredAt).format('MMM DD, YYYY • h:mm A')}
|
||||
</MyText>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Cancellation Reason */}
|
||||
|
|
@ -391,6 +403,14 @@ function OrderDetails() {
|
|||
</MyText>
|
||||
</button>
|
||||
</div>
|
||||
{item.packagedAt && (
|
||||
<MyText
|
||||
data-testid={`order-item-packaged-at-${item.id}`}
|
||||
className="mt-1 block text-[10px] text-gray-400"
|
||||
>
|
||||
Packed {dayjs(item.packagedAt).format('MMM DD, YYYY • h:mm A')}
|
||||
</MyText>
|
||||
)}
|
||||
</div>
|
||||
<MyText className="text-sm font-bold text-gray-900">
|
||||
₹{item.amount}
|
||||
|
|
|
|||
|
|
@ -189,8 +189,7 @@ function EditProduct() {
|
|||
newImageUrls: allUploadUrls,
|
||||
} as any)
|
||||
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
window.alert('Product updated successfully!')
|
||||
productFormRef.current?.clearImages()
|
||||
} catch (error: any) {
|
||||
|
|
@ -233,8 +232,7 @@ function EditProduct() {
|
|||
deletedImageKeys: [],
|
||||
newImageUrls: [],
|
||||
} as any)
|
||||
await refetch()
|
||||
await refetchProducts()
|
||||
await Promise.all([refetch(), refetchProducts()])
|
||||
window.alert('Market data updated for your region')
|
||||
} catch (error: any) {
|
||||
window.alert(error.message || 'Failed to update product')
|
||||
|
|
|
|||
|
|
@ -1187,12 +1187,12 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
|
|||
| AORD-10 | happy | updateNotes | stored |
|
||||
| AORD-11 | error | unknown | error |
|
||||
| AORD-12 | edge | empty notes | stored null |
|
||||
| AORD-13 | happy | updatePackaged true/false | status; user notification |
|
||||
| AORD-13 | happy | updatePackaged true/false | status; user notification; item packagedAt stamped then cleared |
|
||||
| AORD-14 | error | unknown order | 404 |
|
||||
| AORD-15 | edge | string orderId | schema requires string |
|
||||
| AORD-16 | happy | updateDelivered true/false | user status success/pending |
|
||||
| AORD-16 | happy | updateDelivered true/false | user status success/pending; deliveredAt stamped, kept on repeat, cleared |
|
||||
| AORD-17 | error | unknown | 404 |
|
||||
| AORD-18 | happy | updateOrderItemPackaging | flags |
|
||||
| AORD-18 | happy | updateOrderItemPackaging | flags; packagedAt follows the Packaged toggle |
|
||||
| AORD-19 | error | unknown item | 404 |
|
||||
| AORD-20 | edge | only one flag supplied | other preserved |
|
||||
| AORD-21 | happy | removeDeliveryCharge | 0; user sees |
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -40,15 +40,20 @@ export async function initializeProducts(regionId: number): Promise<void> {
|
|||
try {
|
||||
console.log('Initializing product store in Redis...')
|
||||
|
||||
// Fetch all products with full details (similar to productMega logic)
|
||||
const productsData = await getAllProductsForCache(regionId)
|
||||
// All five cache slices are independent: fetch them together.
|
||||
const [productsData, allStores, allDeliverySlots, allSpecialDeals, allProductTags] =
|
||||
await Promise.all([
|
||||
// All products with full details (similar to productMega logic)
|
||||
getAllProductsForCache(regionId),
|
||||
getAllStoresForCache(regionId),
|
||||
// Delivery slots, excluding full capacity slots.
|
||||
getAllDeliverySlotsForCache(regionId),
|
||||
getAllSpecialDealsForCache(regionId),
|
||||
getAllProductTagsForCache(regionId),
|
||||
])
|
||||
|
||||
// Fetch all stores
|
||||
const allStores = await getAllStoresForCache(regionId)
|
||||
const storeMap = new Map(allStores.map((s) => [s.id, s]))
|
||||
|
||||
// Fetch all delivery slots (excluding full capacity slots)
|
||||
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
||||
for (const slot of allDeliverySlots) {
|
||||
if (!deliverySlotsMap.has(slot.skuId))
|
||||
|
|
@ -56,8 +61,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
|
|||
deliverySlotsMap.get(slot.skuId)!.push(slot)
|
||||
}
|
||||
|
||||
// Fetch all special deals
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
// Special deals by sku
|
||||
const specialDealsMap = new Map<number, SpecialDealData[]>()
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.skuId))
|
||||
|
|
@ -65,8 +69,7 @@ export async function initializeProducts(regionId: number): Promise<void> {
|
|||
specialDealsMap.get(deal.skuId)!.push(deal)
|
||||
}
|
||||
|
||||
// Fetch all product tags
|
||||
const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
// Tag names by product
|
||||
const productTagsMap = new Map<number, string[]>()
|
||||
for (const tag of allProductTags) {
|
||||
if (!productTagsMap.has(tag.productId))
|
||||
|
|
@ -158,12 +161,25 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
//
|
||||
// return products
|
||||
|
||||
const productsData = await getAllProductsForCache(regionId)
|
||||
// All six cache slices are independent: fetch them together.
|
||||
const [
|
||||
productsData,
|
||||
allStores,
|
||||
allDeliverySlots,
|
||||
allSpecialDeals,
|
||||
allProductTags,
|
||||
allProductCombos,
|
||||
] = await Promise.all([
|
||||
getAllProductsForCache(regionId),
|
||||
getAllStoresForCache(regionId),
|
||||
getAllDeliverySlotsForCache(regionId),
|
||||
getAllSpecialDealsForCache(regionId),
|
||||
getAllProductTagsForCache(regionId),
|
||||
getAllProductCombosForCache(regionId),
|
||||
])
|
||||
|
||||
const allStores = await getAllStoresForCache(regionId)
|
||||
const storeMap = new Map(allStores.map((s) => [s.id, s]))
|
||||
|
||||
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
||||
for (const slot of allDeliverySlots) {
|
||||
if (!deliverySlotsMap.has(slot.skuId))
|
||||
|
|
@ -171,7 +187,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
deliverySlotsMap.get(slot.skuId)!.push(slot)
|
||||
}
|
||||
|
||||
const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
const specialDealsMap = new Map<number, SpecialDealData[]>()
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.skuId))
|
||||
|
|
@ -179,7 +194,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
specialDealsMap.get(deal.skuId)!.push(deal)
|
||||
}
|
||||
|
||||
const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
const productTagsMap = new Map<number, string[]>()
|
||||
for (const tag of allProductTags) {
|
||||
if (!productTagsMap.has(tag.productId))
|
||||
|
|
@ -188,7 +202,6 @@ export async function getAllProducts(regionId: number): Promise<Product[]> {
|
|||
}
|
||||
|
||||
const products: Product[] = []
|
||||
const allProductCombos = await getAllProductCombosForCache(regionId)
|
||||
const productCombosMap = new Map<number, ProductComboCacheData[]>()
|
||||
for (const comboItem of allProductCombos) {
|
||||
if (!productCombosMap.has(comboItem.comboSkuId))
|
||||
|
|
|
|||
|
|
@ -45,11 +45,11 @@ export async function initializeProductTagStore(regionId: number): Promise<void>
|
|||
try {
|
||||
console.log('Initializing product tag store in Redis...')
|
||||
|
||||
// Fetch all tags
|
||||
const tagsData = await getAllTagsForCache(regionId)
|
||||
|
||||
// Fetch product IDs for each tag
|
||||
const productTagsData = await getAllTagProductMappings(regionId)
|
||||
// The tags and their product mappings are independent reads.
|
||||
const [tagsData, productTagsData] = await Promise.all([
|
||||
getAllTagsForCache(regionId),
|
||||
getAllTagProductMappings(regionId),
|
||||
])
|
||||
|
||||
// Group product IDs by tag
|
||||
const productIdsByTag = new Map<number, number[]>()
|
||||
|
|
|
|||
|
|
@ -81,9 +81,17 @@ export async function getMultipleUserNegativityScores(
|
|||
//
|
||||
// return result
|
||||
|
||||
// One query per user, all independent: run them together.
|
||||
const entries = await Promise.all(
|
||||
userIds.map(async (userId) => ({
|
||||
userId,
|
||||
score: await getUserNegativityScoreFromDb(userId),
|
||||
}))
|
||||
)
|
||||
|
||||
const result: Record<number, number> = {}
|
||||
for (const userId of userIds) {
|
||||
result[userId] = await getUserNegativityScoreFromDb(userId)
|
||||
for (const entry of entries) {
|
||||
result[entry.userId] = entry.score
|
||||
}
|
||||
return result
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -367,9 +367,11 @@ export const productRouter = router({
|
|||
skus: skuInputs,
|
||||
} as any, ctx.staffUser!.regionId)
|
||||
|
||||
await claimUploadUrls(allUploadUrls)
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
// Both are post-write side effects and independent of each other.
|
||||
await Promise.all([
|
||||
claimUploadUrls(allUploadUrls),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const productWithImageUrls = {
|
||||
...newProduct,
|
||||
|
|
@ -470,11 +472,12 @@ export const productRouter = router({
|
|||
throw new ApiError('Product not found', 404)
|
||||
}
|
||||
|
||||
if (uploadsToValidate.length > 0) {
|
||||
await claimUploadUrls(uploadsToValidate)
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
await Promise.all([
|
||||
uploadsToValidate.length > 0
|
||||
? claimUploadUrls(uploadsToValidate)
|
||||
: Promise.resolve(),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const productWithImageUrls = {
|
||||
...updatedProduct,
|
||||
|
|
@ -712,9 +715,10 @@ export const productRouter = router({
|
|||
|
||||
await replaceTagProducts(ctx.staffUser!.regionId, createdTag.id, productIds)
|
||||
|
||||
await claimUploadUrls(uploadUrls)
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
await Promise.all([
|
||||
claimUploadUrls(uploadUrls),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const { products, ...createdTagInfo } = createdTag
|
||||
|
||||
|
|
@ -779,9 +783,10 @@ export const productRouter = router({
|
|||
await replaceTagProducts(ctx.staffUser!.regionId, id, productIds)
|
||||
}
|
||||
|
||||
await claimUploadUrls(uploadUrls)
|
||||
|
||||
await scheduleStoreInitialization(ctx.staffUser!.regionId)
|
||||
await Promise.all([
|
||||
claimUploadUrls(uploadUrls),
|
||||
scheduleStoreInitialization(ctx.staffUser!.regionId),
|
||||
])
|
||||
|
||||
const { products, ...updatedTagInfo } = updatedTag
|
||||
|
||||
|
|
|
|||
|
|
@ -51,9 +51,12 @@ export const userRouter = {
|
|||
// Get order stats for each user
|
||||
const userIds = usersToReturn.map((u: any) => u.id);
|
||||
|
||||
const orderCounts = await getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
const lastOrders = await getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
const suspensionStatuses = await getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds);
|
||||
// The three per-user stats are independent reads.
|
||||
const [orderCounts, lastOrders, suspensionStatuses] = await Promise.all([
|
||||
getOrderCountsByUserIds(ctx.staffUser!.regionId, userIds),
|
||||
getLastOrdersByUserIds(ctx.staffUser!.regionId, userIds),
|
||||
getSuspensionStatusesByUserIds(ctx.staffUser!.regionId, userIds),
|
||||
]);
|
||||
|
||||
// Create lookup maps
|
||||
const orderCountMap = new Map(orderCounts.map(o => [o.userId, o.totalOrders]));
|
||||
|
|
@ -92,18 +95,19 @@ export const userRouter = {
|
|||
throw new ApiError('User not found', 404);
|
||||
}
|
||||
|
||||
// Get user suspension status
|
||||
const isSuspended = await getUserSuspensionStatus(userId);
|
||||
|
||||
// Get all orders for this user
|
||||
const userOrders = await getUserOrders(ctx.staffUser!.regionId, userId);
|
||||
// Suspension status and the order list are independent reads.
|
||||
const [isSuspended, userOrders] = await Promise.all([
|
||||
getUserSuspensionStatus(userId),
|
||||
getUserOrders(ctx.staffUser!.regionId, userId),
|
||||
]);
|
||||
|
||||
// Get order status for each order
|
||||
const orderIds = userOrders.map((o: any) => o.id);
|
||||
const orderStatuses = await getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds);
|
||||
|
||||
// Get item counts for each order
|
||||
const itemCounts = await getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds);
|
||||
// Order status and item counts both key off orderIds; run them together.
|
||||
const [orderStatuses, itemCounts] = await Promise.all([
|
||||
getOrderStatusesByOrderIds(ctx.staffUser!.regionId, orderIds),
|
||||
getItemCountsByOrderIds(ctx.staffUser!.regionId, orderIds),
|
||||
]);
|
||||
|
||||
// Create lookup maps
|
||||
const statusMap = new Map(orderStatuses.map(s => [s.orderId, s]));
|
||||
|
|
@ -163,10 +167,11 @@ export const userRouter = {
|
|||
.query(async ({ input, ctx }) => {
|
||||
const { search } = input;
|
||||
|
||||
const usersList = await searchUsers(ctx.staffUser!.regionId, search);
|
||||
|
||||
// Get eligible users (have notif_creds entry)
|
||||
const eligibleUsers = await getAllNotifCreds();
|
||||
// The user list and the notif_creds lookup are independent.
|
||||
const [usersList, eligibleUsers] = await Promise.all([
|
||||
searchUsers(ctx.staffUser!.regionId, search),
|
||||
getAllNotifCreds(),
|
||||
]);
|
||||
|
||||
const eligibleSet = new Set(eligibleUsers.map(u => u.userId));
|
||||
|
||||
|
|
@ -203,8 +208,10 @@ export const userRouter = {
|
|||
|
||||
if (userIds.length === 0) {
|
||||
// Send to all users - get tokens from both logged-in and unlogged users
|
||||
const loggedInTokens = await getAllNotifCreds();
|
||||
const unloggedTokens = await getAllUnloggedTokens();
|
||||
const [loggedInTokens, unloggedTokens] = await Promise.all([
|
||||
getAllNotifCreds(),
|
||||
getAllUnloggedTokens(),
|
||||
]);
|
||||
|
||||
tokens = [
|
||||
...loggedInTokens.map(t => t.token),
|
||||
|
|
|
|||
|
|
@ -450,8 +450,10 @@ export const orderRouter = router({
|
|||
const userId = ctx.user.userId;
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
const totalCount = await getUserOrderCount(userId);
|
||||
const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize);
|
||||
const [totalCount, userOrders] = await Promise.all([
|
||||
getUserOrderCount(userId),
|
||||
getUserOrdersWithRelations(userId, offset, pageSize),
|
||||
]);
|
||||
|
||||
const mappedOrders = await Promise.all(
|
||||
userOrders.map(async (order) => {
|
||||
|
|
|
|||
|
|
@ -327,6 +327,9 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
const fx = await createCatalogOrderFixture({ price: 100 })
|
||||
const orderId = await placeOne(fx)
|
||||
|
||||
const before: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(before.items[0].packagedAt).toBeNull()
|
||||
|
||||
const packed: any = await admin.admin.order.updatePackaged.mutate({
|
||||
orderId: String(orderId),
|
||||
isPackaged: true,
|
||||
|
|
@ -336,9 +339,17 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
expect(afterPacked.deliveryStatus).toBe('packaged')
|
||||
expect(afterPacked.orderStatus).toBe('success')
|
||||
|
||||
// Every item is stamped with the packaging moment.
|
||||
const packedDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(typeof packedDetail.items[0].packagedAt).toBe('string')
|
||||
expect(Number.isNaN(new Date(packedDetail.items[0].packagedAt).getTime())).toBe(false)
|
||||
|
||||
await admin.admin.order.updatePackaged.mutate({ orderId: String(orderId), isPackaged: false })
|
||||
const afterUnpacked: any = await detail(fx.user.token, orderId)
|
||||
expect(afterUnpacked.deliveryStatus).toBe('pending')
|
||||
|
||||
const unpackedDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(unpackedDetail.items[0].packagedAt).toBeNull()
|
||||
})
|
||||
|
||||
it('AORD-14: updatePackaged on an unknown order is NOT_FOUND 404', async () => {
|
||||
|
|
@ -363,6 +374,9 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
const fx = await createCatalogOrderFixture({ price: 100 })
|
||||
const orderId = await placeOne(fx)
|
||||
|
||||
const before: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(before.deliveredAt).toBeNull()
|
||||
|
||||
const res: any = await admin.admin.order.updateDelivered.mutate({
|
||||
orderId: String(orderId),
|
||||
isDelivered: true,
|
||||
|
|
@ -372,10 +386,21 @@ describe('admin.order.updatePackaged / updateDelivered (AORD-13..17)', () => {
|
|||
expect(delivered.orderStatus).toBe('success')
|
||||
expect(delivered.deliveryStatus).toBe('success')
|
||||
|
||||
// The delivery moment is recorded and survives a repeat "delivered" call.
|
||||
const deliveredDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(typeof deliveredDetail.deliveredAt).toBe('string')
|
||||
expect(Number.isNaN(new Date(deliveredDetail.deliveredAt).getTime())).toBe(false)
|
||||
await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: true })
|
||||
const repeat: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(repeat.deliveredAt).toBe(deliveredDetail.deliveredAt)
|
||||
|
||||
await admin.admin.order.updateDelivered.mutate({ orderId: String(orderId), isDelivered: false })
|
||||
const pending: any = await detail(fx.user.token, orderId)
|
||||
expect(pending.orderStatus).toBe('success')
|
||||
expect(pending.deliveryStatus).toBe('pending')
|
||||
|
||||
const pendingDetail: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(pendingDetail.deliveredAt).toBeNull()
|
||||
})
|
||||
|
||||
it('AORD-17: updateDelivered on an unknown order is NOT_FOUND 404', async () => {
|
||||
|
|
@ -410,6 +435,15 @@ describe('admin.order.updateOrderItemPackaging (AORD-18..20)', () => {
|
|||
const after: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(after.items[0].isPackaged).toBe(true)
|
||||
expect(after.items[0].isPackageVerified).toBe(true)
|
||||
expect(typeof after.items[0].packagedAt).toBe('string')
|
||||
|
||||
await admin.admin.order.updateOrderItemPackaging.mutate({
|
||||
orderItemId: itemId,
|
||||
isPackaged: false,
|
||||
})
|
||||
const unpacked: any = await admin.admin.order.getOrderDetails.query({ orderId })
|
||||
expect(unpacked.items[0].isPackaged).toBe(false)
|
||||
expect(unpacked.items[0].packagedAt).toBeNull()
|
||||
})
|
||||
|
||||
it('AORD-19: an unknown order item is NOT_FOUND 404', async () => {
|
||||
|
|
|
|||
|
|
@ -194,8 +194,8 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
|
||||
const onRefresh = async () => {
|
||||
setRefreshing(true);
|
||||
await refetch(); // Refetch product details
|
||||
await loadReviews(true); // Reset and reload reviews
|
||||
// Product details and reviews are independent: refresh them together.
|
||||
await Promise.all([refetch(), loadReviews(true)]);
|
||||
setRefreshing(false);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -29,10 +29,12 @@ const PendingAddressSync: React.FC = () => {
|
|||
isSyncing.current = true
|
||||
try {
|
||||
const created = await createAddress.mutateAsync(pending)
|
||||
await clearPendingAddress()
|
||||
await utils.user.address.getUserAddresses.invalidate()
|
||||
await utils.user.address.getDefaultAddress.invalidate()
|
||||
|
||||
// The address is saved; clear the draft and refresh both lists together.
|
||||
await Promise.all([
|
||||
clearPendingAddress(),
|
||||
utils.user.address.getUserAddresses.invalidate(),
|
||||
utils.user.address.getDefaultAddress.invalidate(),
|
||||
])
|
||||
// The draft was the address the user was checking out with; make it the
|
||||
// active selection as soon as the list is available.
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -198,8 +198,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
try {
|
||||
setAuthState(prev => ({ ...prev, isLoading: true }));
|
||||
|
||||
await saveAuthToken(token);
|
||||
await saveUserId(user.id.toString());
|
||||
await Promise.all([
|
||||
saveAuthToken(token),
|
||||
saveUserId(user.id.toString()),
|
||||
]);
|
||||
|
||||
setAuthState({
|
||||
user: {
|
||||
|
|
@ -232,8 +234,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
// const response = loginMutation.mutate(credentials);
|
||||
const { token, user } = response.data;
|
||||
|
||||
await saveAuthToken(token);
|
||||
await saveUserId(user.id.toString());
|
||||
await Promise.all([
|
||||
saveAuthToken(token),
|
||||
saveUserId(user.id.toString()),
|
||||
]);
|
||||
|
||||
setAuthState({
|
||||
user: {
|
||||
|
|
@ -266,8 +270,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
const response = await registerMutation.mutateAsync(data);
|
||||
const { token, user } = response;
|
||||
|
||||
await saveAuthToken(token);
|
||||
await saveUserId(user.id.toString());
|
||||
await Promise.all([
|
||||
saveAuthToken(token),
|
||||
saveUserId(user.id.toString()),
|
||||
]);
|
||||
|
||||
setAuthState({
|
||||
user: {
|
||||
|
|
|
|||
154
change-log.txt
154
change-log.txt
|
|
@ -1264,3 +1264,157 @@ was ever published and the address flow stayed up.
|
|||
+ after refreshLocation(), re-arm only when the fix actually arrived
|
||||
(coords != null); a failed re-read leaves the poll subscribed
|
||||
~ keep polling on failure (the effect re-subscribes when the status is unusable)
|
||||
|
||||
[2026-11-10 17:22:58 IST] admin orders: record packaging time and delivery time.
|
||||
|
||||
Both columns already exist on the SQLite schema (order_items.packaged_at from
|
||||
migration 0004/0005, orders.delivered_at from 0005) and were never written. No
|
||||
new migration is needed; this wires the writes and surfaces the values in the
|
||||
admin order-details screens (RN admin-ui + web admin-web).
|
||||
|
||||
--- packages/db_helper_sqlite/src/lib/date.ts
|
||||
+ export function nullableDate(value: Date | null | undefined): Date | null
|
||||
(timestampText's fromDriver maps NULL to new Date(0); treat epoch as null)
|
||||
|
||||
--- packages/db_helper_sqlite/src/admin-apis/order.ts
|
||||
updateOrderPackaged:
|
||||
- .set({ is_packaged: isPackaged })
|
||||
+ isPackaged true -> { is_packaged: true, packagedAt: COALESCE(packaged_at, now) }
|
||||
+ isPackaged false -> { is_packaged: false, packagedAt: null }
|
||||
+ !isPackaged also clears orders.deliveredAt (it already reset isDelivered)
|
||||
updateOrderDelivered:
|
||||
+ stamps orders.deliveredAt = now on the first delivered=true, keeps it on repeat
|
||||
+ calls, and clears it on delivered=false
|
||||
updateOrderItemPackaging:
|
||||
+ isPackaged true -> packaged_at = existing ?? now
|
||||
+ isPackaged false -> packaged_at = null
|
||||
getOrderDetails:
|
||||
+ deliveredAt (order) and packagedAt (per item), epoch-as-null
|
||||
|
||||
--- packages/db_helper_sqlite/src/lib/order-items-archive.ts
|
||||
- packagedAt: row.packagedAt ? row.packagedAt.toISOString() : null
|
||||
+ packagedAt: nullableDate(row.packagedAt)?.toISOString() ?? null
|
||||
(an unset timestamp was archived as 1970-01-01T00:00:00.000Z)
|
||||
|
||||
--- packages/shared/types/admin.ts
|
||||
+ AdminOrderDetails.deliveredAt: Date | null
|
||||
+ AdminOrderDetailsItem.packagedAt: Date | null
|
||||
|
||||
--- apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx
|
||||
+ testID "order-delivered-at" row in the header when order.deliveredAt
|
||||
+ testID `order-item-packaged-at-<id>` under each item when item.packagedAt
|
||||
|
||||
--- apps/admin-web/src/routes/dashboard.orders.$id.tsx
|
||||
+ same two blocks (web counterpart)
|
||||
|
||||
--- apps/backend/tests/api/admin-order.test.ts
|
||||
+ AORD-13: asserts packagedAt is stamped then cleared on un-pack
|
||||
+ AORD-16: asserts deliveredAt is stamped then cleared on un-deliver
|
||||
+ AORD-18: asserts the per-item packagedAt follows the Packaged toggle
|
||||
|
||||
--- apps/admin-ui/tests/fixtures/index.ts
|
||||
+ deliveredAt / packagedAt on ORDER_DETAILS and its items
|
||||
|
||||
--- apps/admin-ui/tests/pages/order-details.test.tsx
|
||||
+ AOD-26: delivered timestamp renders when order.deliveredAt is set
|
||||
+ AOD-27: no delivered timestamp before delivery
|
||||
+ AOD-28: per-item packed timestamp renders only when packagedAt is set
|
||||
|
||||
[2026-11-14 11:21:51 IST] intrv.java: print numbers 1 to 10 using Java streams.
|
||||
|
||||
--- intrv.java (new)
|
||||
+ class intrv with static printOneToTen() using IntStream.rangeClosed(1, 10).forEach(System.out::println)
|
||||
+ main() invoking printOneToTen()
|
||||
|
||||
[2026-11-14 11:27:23 IST] intrv.java: extract company name before the first hyphen.
|
||||
|
||||
--- intrv.java
|
||||
+ import java.util.Arrays
|
||||
+ static String extractCompany(String input): null/blank guard, input.split("-", 2)[0].trim()
|
||||
+ static String extractCompanyStream(String input): Arrays.stream(input.split("-", 2)).findFirst().orElse("")
|
||||
~ main() now also demos both on "Infosys-Interview 2028"
|
||||
|
||||
[2026-11-14 11:27:53 IST] intrv.java: company extraction now stream-only.
|
||||
|
||||
--- intrv.java
|
||||
- remove non-stream extractCompany
|
||||
~ extractCompanyStream renamed to extractCompany; body is a single Arrays.stream(...).findFirst().orElse("") pipeline
|
||||
~ main() calls extractCompany only
|
||||
|
||||
[2026-11-14 11:58:07 IST] intrv.java: extractCompany rewritten with an enhanced for loop.
|
||||
|
||||
--- intrv.java
|
||||
~ extractCompany: drop Arrays.stream/split pipeline; split once and walk the
|
||||
segments with a `for (String part : parts)` loop, returning the first non-blank
|
||||
trimmed segment ("" when none)
|
||||
- drop now-unused `import java.util.Arrays` (IntStream import stays for printOneToTen)
|
||||
|
||||
[2026-11-14 21:20:45 IST] perf: Promise.all for verified-independent sequential awaits.
|
||||
|
||||
Read-only waterfalls and independent storage/refetch pairs that the audit
|
||||
found. No ordering-dependent pair was changed (validate->write, write->read,
|
||||
mutate->refetch, fetch->reload stay sequential).
|
||||
|
||||
--- apps/backend/src/stores/product-store.ts
|
||||
initializeProducts: 5 cache reads -> one Promise.all
|
||||
- const productsData = await getAllProductsForCache(regionId)
|
||||
- const allStores = await getAllStoresForCache(regionId)
|
||||
- const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||
- const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
|
||||
- const allProductTags = await getAllProductTagsForCache(regionId)
|
||||
+ const [productsData, allStores, allDeliverySlots, allSpecialDeals, allProductTags] =
|
||||
+ await Promise.all([...same five calls...])
|
||||
getAllProducts: 6 cache reads -> one Promise.all (adds getAllProductCombosForCache)
|
||||
|
||||
--- apps/backend/src/stores/product-tag-store.ts
|
||||
- const tagsData = await getAllTagsForCache(regionId)
|
||||
- const productTagsData = await getAllTagProductMappings(regionId)
|
||||
+ const [tagsData, productTagsData] = await Promise.all([
|
||||
+ getAllTagsForCache(regionId),
|
||||
+ getAllTagProductMappings(regionId),
|
||||
+ ])
|
||||
|
||||
--- apps/backend/src/stores/user-negativity-store.ts
|
||||
loop of per-user awaits -> Promise.all over userIds, then fill the record.
|
||||
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/user.ts
|
||||
getAllUsers: order counts / last orders / suspension -> Promise.all
|
||||
getUserDetails: suspension + orders -> Promise.all; statuses + item counts -> Promise.all
|
||||
getUsersForNotification: searchUsers + getAllNotifCreds -> Promise.all
|
||||
sendNotification: logged-in + unlogged tokens -> Promise.all
|
||||
|
||||
--- apps/backend/src/trpc/apis/user-apis/apis/order.ts
|
||||
- const totalCount = await getUserOrderCount(userId);
|
||||
- const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize);
|
||||
+ const [totalCount, userOrders] = await Promise.all([...])
|
||||
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/product.ts
|
||||
claimUploadUrls + scheduleStoreInitialization -> Promise.all at 4 sites
|
||||
(create product, update product, create tag, update tag). create/update and
|
||||
replaceTagProducts stay before the batch because the cache rebuild reads them.
|
||||
|
||||
--- apps/user-ui/src/contexts/AuthContext.tsx
|
||||
saveAuthToken + saveUserId -> Promise.all (3 sites: loginWithToken/login/register)
|
||||
|
||||
--- apps/admin-ui/components/context/staff-auth-context.tsx
|
||||
saveJWT + saveStaff, deleteJWT + deleteStaff -> Promise.all
|
||||
|
||||
--- apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx
|
||||
--- apps/admin-web/src/routes/dashboard.products.edit.tsx
|
||||
refetch() + refetchProducts() -> Promise.all (2 sites each; web counterpart)
|
||||
|
||||
--- apps/user-ui/components/ProductDetail.tsx
|
||||
onRefresh: refetch() + loadReviews(true) -> Promise.all
|
||||
|
||||
--- apps/user-ui/src/components/PendingAddressSync.tsx
|
||||
clearPendingAddress + getUserAddresses/getDefaultAddress invalidations -> Promise.all
|
||||
(the createAddress mutation still completes first)
|
||||
|
||||
Skipped on purpose:
|
||||
- write -> scheduleStoreInitialization pairs (store/banner/global-store CRUD):
|
||||
single enqueue after commit, negligible gain.
|
||||
- cloud_cache version bumpers: independent but D1 serializes writes anyway.
|
||||
- per-region loops (createAllCacheFiles, initializeAllStores, gen-store,
|
||||
flash cron): deliberate batching, not a missed parallel await.
|
||||
- getAuthToken + getCurrentUserId (AuthContext:70): getCurrentUserId re-reads
|
||||
the token; needs a refactor, not Promise.all.
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import {
|
|||
orders,
|
||||
orderStatus,
|
||||
} from '../db/schema'
|
||||
import { and, desc, eq, inArray, isNull, lt, SQL } from 'drizzle-orm'
|
||||
import { and, desc, eq, inArray, isNull, lt, sql, SQL } from 'drizzle-orm'
|
||||
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
||||
import {
|
||||
attachOrderItems,
|
||||
|
|
@ -32,7 +32,7 @@ import type {
|
|||
GetAllOrdersInput,
|
||||
} from '@packages/shared'
|
||||
import type { InferSelectModel } from 'drizzle-orm'
|
||||
import { coerceDate } from '../lib/date'
|
||||
import { coerceDate, nullableDate } from '../lib/date'
|
||||
import { marketStatsForRegion } from '../lib/market-stats'
|
||||
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
|
||||
|
||||
|
|
@ -109,7 +109,15 @@ export async function updateOrderPackaged(regionId: number, orderId: string, isP
|
|||
|
||||
await db
|
||||
.update(orderItems)
|
||||
.set({ is_packaged: isPackaged })
|
||||
.set(
|
||||
isPackaged
|
||||
? {
|
||||
is_packaged: true,
|
||||
// First packaging moment wins; re-marking must not move the clock.
|
||||
packagedAt: sql`COALESCE(${orderItems.packagedAt}, ${new Date().toISOString()})`,
|
||||
}
|
||||
: { is_packaged: false, packagedAt: null }
|
||||
)
|
||||
.where(eq(orderItems.orderId, orderIdNumber))
|
||||
|
||||
if (!isPackaged) {
|
||||
|
|
@ -117,6 +125,11 @@ export async function updateOrderPackaged(regionId: number, orderId: string, isP
|
|||
.update(orderStatus)
|
||||
.set({ isPackaged, isDelivered: false })
|
||||
.where(eq(orderStatus.orderId, orderIdNumber))
|
||||
// Un-packaging resets delivery, so the recorded delivery time goes with it.
|
||||
await db
|
||||
.update(orders)
|
||||
.set({ deliveredAt: null })
|
||||
.where(eq(orders.id, orderIdNumber))
|
||||
} else {
|
||||
await db
|
||||
.update(orderStatus)
|
||||
|
|
@ -136,7 +149,7 @@ export async function updateOrderDelivered(regionId: number, orderId: string, is
|
|||
|
||||
const orderCheck = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
columns: { id: true, deliveredAt: true },
|
||||
})
|
||||
if (!orderCheck) {
|
||||
return null
|
||||
|
|
@ -147,6 +160,16 @@ export async function updateOrderDelivered(regionId: number, orderId: string, is
|
|||
.set({ isDelivered })
|
||||
.where(eq(orderStatus.orderId, orderIdNumber))
|
||||
|
||||
// Stamp the first delivery moment; a repeat "delivered" call keeps it, and
|
||||
// un-delivering clears it so the next delivery gets a fresh time.
|
||||
const deliveredAt = isDelivered
|
||||
? nullableDate(orderCheck.deliveredAt) ?? new Date()
|
||||
: null
|
||||
await db
|
||||
.update(orders)
|
||||
.set({ deliveredAt })
|
||||
.where(eq(orders.id, orderIdNumber))
|
||||
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
|
||||
})
|
||||
|
|
@ -238,6 +261,7 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
|||
adminNotes: orderData.adminNotes,
|
||||
userNotes: orderData.userNotes,
|
||||
createdAt: orderData.createdAt,
|
||||
deliveredAt: nullableDate(orderData.deliveredAt),
|
||||
status,
|
||||
isPackaged: orderStatusRecord?.isPackaged || false,
|
||||
isDelivered: orderStatusRecord?.isDelivered || false,
|
||||
|
|
@ -252,6 +276,7 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
|||
amount: parseFloat(item.price.toString()) * parseFloat(item.quantity || '0'),
|
||||
isPackaged: item.is_packaged,
|
||||
isPackageVerified: item.is_package_verified,
|
||||
packagedAt: nullableDate(item.packagedAt),
|
||||
features: (item.sku.features || []).map((f: any) => ({
|
||||
featureName: f.featureName,
|
||||
featureValue: f.featureValue,
|
||||
|
|
@ -286,10 +311,14 @@ export async function updateOrderItemPackaging(
|
|||
const updateData: Partial<{
|
||||
is_packaged: boolean
|
||||
is_package_verified: boolean
|
||||
packaged_at: Date | null
|
||||
}> = {}
|
||||
|
||||
if (isPackaged !== undefined) {
|
||||
updateData.is_packaged = isPackaged
|
||||
updateData.packaged_at = isPackaged
|
||||
? nullableDate(orderItem.packagedAt) ?? new Date()
|
||||
: null
|
||||
}
|
||||
if (isPackageVerified !== undefined) {
|
||||
updateData.is_package_verified = isPackageVerified
|
||||
|
|
|
|||
|
|
@ -1,3 +1,14 @@
|
|||
/**
|
||||
* `timestampText` reads SQL NULL back as `new Date(0)`, so a plain `?? null`
|
||||
* would hand clients 1970-01-01 instead of "not set". Anything at or before the
|
||||
* epoch is treated as unset.
|
||||
*/
|
||||
export function nullableDate(value: Date | null | undefined): Date | null {
|
||||
if (!value) return null
|
||||
const time = value instanceof Date ? value.getTime() : NaN
|
||||
return Number.isNaN(time) || time <= 0 ? null : value
|
||||
}
|
||||
|
||||
export function coerceDate(value: unknown): Date | null {
|
||||
if (value instanceof Date) {
|
||||
return Number.isNaN(value.getTime()) ? null : value
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { and, eq, gt, inArray, isNull, sql } from 'drizzle-orm'
|
||||
import { db } from '../db/db_index'
|
||||
import { orderItems, orders, productSkus, type OrderItemSnapshot } from '../db/schema'
|
||||
import { nullableDate } from './date'
|
||||
|
||||
const IST_OFFSET_MS = 5.5 * 60 * 60 * 1000
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
|
|
@ -132,7 +133,7 @@ export function buildSnapshot(
|
|||
discountedPrice: row.discountedPrice,
|
||||
isPackaged: row.is_packaged,
|
||||
isPackageVerified: row.is_package_verified,
|
||||
packagedAt: row.packagedAt ? row.packagedAt.toISOString() : null,
|
||||
packagedAt: nullableDate(row.packagedAt)?.toISOString() ?? null,
|
||||
productName: sku.product.name,
|
||||
skuName: sku.name,
|
||||
image: Array.isArray(sku.images) && sku.images.length > 0 ? sku.images[0] : null,
|
||||
|
|
|
|||
|
|
@ -90,6 +90,7 @@ export interface AdminOrderDetailsItem extends AdminOrderItemCore {
|
|||
price: string;
|
||||
productSize: number;
|
||||
unit?: string;
|
||||
packagedAt: Date | null;
|
||||
}
|
||||
|
||||
export interface AdminOrderDetailsCouponData {
|
||||
|
|
@ -112,6 +113,7 @@ export interface AdminOrderDetails {
|
|||
adminNotes: string | null;
|
||||
userNotes: string | null;
|
||||
createdAt: Date;
|
||||
deliveredAt: Date | null;
|
||||
status: 'pending' | 'delivered' | 'cancelled';
|
||||
isPackaged: boolean;
|
||||
isDelivered: boolean;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue