enh
This commit is contained in:
parent
44318541f8
commit
77c46b777f
15 changed files with 426 additions and 126 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
|
|
@ -1,6 +1,7 @@
|
|||
import roleManager from './roles-manager';
|
||||
import './notif-job';
|
||||
import { computeConstants } from './const-store';
|
||||
import { initializeProducts } from './product-store';
|
||||
|
||||
/**
|
||||
* Initialize all application services
|
||||
|
|
@ -21,6 +22,10 @@ export const initFunc = async (): Promise<void> => {
|
|||
await computeConstants();
|
||||
console.log('Const store initialized successfully');
|
||||
|
||||
// Initialize product store in Redis
|
||||
await initializeProducts();
|
||||
console.log('Product store initialized successfully');
|
||||
|
||||
// Notification queue and worker are initialized via import
|
||||
console.log('Notification queue and worker initialized');
|
||||
|
||||
|
|
|
|||
165
apps/backend/src/lib/product-store.ts
Normal file
165
apps/backend/src/lib/product-store.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
import redisClient from './redis-client';
|
||||
import { db } from '../db/db_index';
|
||||
import { productInfo, units, productSlots, deliverySlotInfo, specialDeals, storeInfo } from '../db/schema';
|
||||
import { generateSignedUrlsFromS3Urls } from './s3-client';
|
||||
import { eq, and, gt, sql } from 'drizzle-orm';
|
||||
|
||||
// Uniform Product Type (matches getProductDetails return)
|
||||
interface Product {
|
||||
id: number;
|
||||
name: string;
|
||||
shortDescription: string | null;
|
||||
longDescription: string | null;
|
||||
price: string;
|
||||
marketPrice: string | null;
|
||||
unitNotation: string;
|
||||
images: string[];
|
||||
isOutOfStock: boolean;
|
||||
store: { id: number; name: string; description: string | null } | null;
|
||||
incrementStep: number;
|
||||
productQuantity: number;
|
||||
isFlashAvailable: boolean;
|
||||
flashPrice: string | null;
|
||||
deliverySlots: Array<{ id: number; deliveryTime: Date; freezeTime: Date }>;
|
||||
specialDeals: Array<{ quantity: string; price: string; validTill: Date }>;
|
||||
}
|
||||
|
||||
export async function initializeProducts(): Promise<void> {
|
||||
try {
|
||||
console.log('Initializing product store in Redis...');
|
||||
|
||||
// Fetch all products with full details (similar to productMega logic)
|
||||
const productsData = await db
|
||||
.select({
|
||||
id: productInfo.id,
|
||||
name: productInfo.name,
|
||||
shortDescription: productInfo.shortDescription,
|
||||
longDescription: productInfo.longDescription,
|
||||
price: productInfo.price,
|
||||
marketPrice: productInfo.marketPrice,
|
||||
images: productInfo.images,
|
||||
isOutOfStock: productInfo.isOutOfStock,
|
||||
storeId: productInfo.storeId,
|
||||
unitShortNotation: units.shortNotation,
|
||||
incrementStep: productInfo.incrementStep,
|
||||
productQuantity: productInfo.productQuantity,
|
||||
isFlashAvailable: productInfo.isFlashAvailable,
|
||||
flashPrice: productInfo.flashPrice,
|
||||
})
|
||||
.from(productInfo)
|
||||
.innerJoin(units, eq(productInfo.unitId, units.id));
|
||||
|
||||
// Fetch all stores
|
||||
const allStores = await db.query.storeInfo.findMany({
|
||||
columns: { id: true, name: true, description: true },
|
||||
});
|
||||
const storeMap = new Map(allStores.map(s => [s.id, s]));
|
||||
|
||||
// Fetch all delivery slots
|
||||
const allDeliverySlots = await db
|
||||
.select({
|
||||
productId: productSlots.productId,
|
||||
id: deliverySlotInfo.id,
|
||||
deliveryTime: deliverySlotInfo.deliveryTime,
|
||||
freezeTime: deliverySlotInfo.freezeTime,
|
||||
})
|
||||
.from(productSlots)
|
||||
.innerJoin(deliverySlotInfo, eq(productSlots.slotId, deliverySlotInfo.id))
|
||||
.where(
|
||||
and(
|
||||
eq(deliverySlotInfo.isActive, true),
|
||||
gt(deliverySlotInfo.deliveryTime, sql`NOW()`)
|
||||
)
|
||||
);
|
||||
const deliverySlotsMap = new Map<number, typeof allDeliverySlots>();
|
||||
for (const slot of allDeliverySlots) {
|
||||
if (!deliverySlotsMap.has(slot.productId)) deliverySlotsMap.set(slot.productId, []);
|
||||
deliverySlotsMap.get(slot.productId)!.push(slot);
|
||||
}
|
||||
|
||||
// Fetch all special deals
|
||||
const allSpecialDeals = await db
|
||||
.select({
|
||||
productId: specialDeals.productId,
|
||||
quantity: specialDeals.quantity,
|
||||
price: specialDeals.price,
|
||||
validTill: specialDeals.validTill,
|
||||
})
|
||||
.from(specialDeals)
|
||||
.where(gt(specialDeals.validTill, sql`NOW()`));
|
||||
const specialDealsMap = new Map<number, typeof allSpecialDeals>();
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.productId)) specialDealsMap.set(deal.productId, []);
|
||||
specialDealsMap.get(deal.productId)!.push(deal);
|
||||
}
|
||||
|
||||
// Store each product in Redis
|
||||
for (const product of productsData) {
|
||||
const signedImages = await generateSignedUrlsFromS3Urls((product.images as string[]) || []);
|
||||
const store = product.storeId ? storeMap.get(product.storeId) || null : null;
|
||||
const deliverySlots = deliverySlotsMap.get(product.id) || [];
|
||||
const specialDeals = specialDealsMap.get(product.id) || [];
|
||||
|
||||
const productObj: Product = {
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
shortDescription: product.shortDescription,
|
||||
longDescription: product.longDescription,
|
||||
price: product.price.toString(),
|
||||
marketPrice: product.marketPrice?.toString() || null,
|
||||
unitNotation: product.unitShortNotation,
|
||||
images: signedImages,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
store: store ? { id: store.id, name: store.name, description: store.description } : null,
|
||||
incrementStep: product.incrementStep,
|
||||
productQuantity: product.productQuantity,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
flashPrice: product.flashPrice?.toString() || null,
|
||||
deliverySlots: deliverySlots.map(s => ({ id: s.id, deliveryTime: s.deliveryTime, freezeTime: s.freezeTime })),
|
||||
specialDeals: specialDeals.map(d => ({ quantity: d.quantity.toString(), price: d.price.toString(), validTill: d.validTill })),
|
||||
};
|
||||
|
||||
await redisClient.set(`product:${product.id}`, JSON.stringify(productObj));
|
||||
}
|
||||
|
||||
console.log('Product store initialized successfully');
|
||||
} catch (error) {
|
||||
console.error('Error initializing product store:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProductById(id: number): Promise<Product | null> {
|
||||
try {
|
||||
const key = `product:${id}`;
|
||||
const data = await redisClient.get(key);
|
||||
if (!data) return null;
|
||||
return JSON.parse(data) as Product;
|
||||
} catch (error) {
|
||||
console.error(`Error getting product ${id}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAllProducts(): Promise<Product[]> {
|
||||
try {
|
||||
// Get all keys matching the pattern "product:*"
|
||||
const keys = await redisClient.KEYS('product:*');
|
||||
|
||||
if (keys.length === 0) return [];
|
||||
|
||||
// Get all products using MGET for better performance
|
||||
const productsData = await redisClient.MGET(keys);
|
||||
|
||||
const products: Product[] = [];
|
||||
for (const productData of productsData) {
|
||||
if (productData) {
|
||||
products.push(JSON.parse(productData) as Product);
|
||||
}
|
||||
}
|
||||
|
||||
return products;
|
||||
} catch (error) {
|
||||
console.error('Error getting all products:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
@ -63,6 +63,14 @@ class RedisClient {
|
|||
return await this.client.lPush(key, value);
|
||||
}
|
||||
|
||||
async KEYS(pattern: string): Promise<string[]> {
|
||||
return await this.client.KEYS(pattern);
|
||||
}
|
||||
|
||||
async MGET(keys: string[]): Promise<(string | null)[]> {
|
||||
return await this.client.MGET(keys);
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
if (this.isConnected) {
|
||||
this.client.disconnect();
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { productInfo, units, productSlots, deliverySlotInfo, storeInfo, productT
|
|||
import { eq, gt, and, sql, inArray } from 'drizzle-orm';
|
||||
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url } from '../../lib/s3-client';
|
||||
import { z } from 'zod';
|
||||
import { getAllProducts as getAllProductsFromCache } from '../../lib/product-store';
|
||||
|
||||
export const getNextDeliveryDate = async (productId: number): Promise<Date | null> => {
|
||||
const result = await db
|
||||
|
|
@ -58,76 +59,60 @@ export const commonRouter = router({
|
|||
.query(async ({ input }) => {
|
||||
const { searchQuery, tagId } = input;
|
||||
|
||||
let productIds: number[] | null = null;
|
||||
// Get all products from cache
|
||||
let products = await getAllProductsFromCache();
|
||||
|
||||
// If tagId is provided, get products that have this tag
|
||||
// Apply tag filtering if tagId is provided
|
||||
if (tagId) {
|
||||
// Get products that have this tag from the database
|
||||
const taggedProducts = await db
|
||||
.select({ productId: productTags.productId })
|
||||
.from(productTags)
|
||||
.where(eq(productTags.tagId, tagId));
|
||||
|
||||
productIds = taggedProducts.map(tp => tp.productId);
|
||||
const taggedProductIds = new Set(taggedProducts.map(tp => tp.productId));
|
||||
|
||||
// Filter products based on tag
|
||||
products = products.filter(product => taggedProductIds.has(product.id));
|
||||
}
|
||||
|
||||
let whereConditions = [];
|
||||
|
||||
// Add tag filtering
|
||||
if (productIds && productIds.length > 0) {
|
||||
whereConditions.push(inArray(productInfo.id, productIds));
|
||||
} else if (tagId) {
|
||||
// If tagId was provided but no products found, return empty array
|
||||
return {
|
||||
products: [],
|
||||
count: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Add search filtering
|
||||
// Apply search filtering if searchQuery is provided
|
||||
if (searchQuery) {
|
||||
whereConditions.push(sql`LOWER(${productInfo.name}) LIKE LOWER(${ '%' + searchQuery + '%' })`);
|
||||
const searchLower = searchQuery.toLowerCase();
|
||||
products = products.filter(product =>
|
||||
product.name.toLowerCase().includes(searchLower)
|
||||
);
|
||||
}
|
||||
|
||||
// Get suspended product IDs to filter them out
|
||||
const suspendedProducts = await db
|
||||
.select({ id: productInfo.id })
|
||||
.from(productInfo)
|
||||
.where(eq(productInfo.isSuspended, true));
|
||||
|
||||
const suspendedProductIds = new Set(suspendedProducts.map(sp => sp.id));
|
||||
|
||||
// Filter out suspended products
|
||||
whereConditions.push(eq(productInfo.isSuspended, false));
|
||||
products = products.filter(product => !suspendedProductIds.has(product.id));
|
||||
|
||||
const whereCondition = whereConditions.length > 0 ? and(...whereConditions) : undefined;
|
||||
|
||||
const productsWithUnits = await db
|
||||
.select({
|
||||
id: productInfo.id,
|
||||
name: productInfo.name,
|
||||
shortDescription: productInfo.shortDescription,
|
||||
price: productInfo.price,
|
||||
marketPrice: productInfo.marketPrice,
|
||||
images: productInfo.images,
|
||||
isOutOfStock: productInfo.isOutOfStock,
|
||||
unitShortNotation: units.shortNotation,
|
||||
incrementStep: productInfo.incrementStep,
|
||||
productQuantity: productInfo.productQuantity,
|
||||
storeId: productInfo.storeId,
|
||||
})
|
||||
.from(productInfo)
|
||||
.innerJoin(units, eq(productInfo.unitId, units.id))
|
||||
.where(whereCondition);
|
||||
|
||||
// Generate signed URLs for product images
|
||||
// Format products to match the expected response structure
|
||||
const formattedProducts = await Promise.all(
|
||||
productsWithUnits.map(async (product) => {
|
||||
products.map(async (product) => {
|
||||
const nextDeliveryDate = await getNextDeliveryDate(product.id);
|
||||
return {
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
shortDescription: product.shortDescription,
|
||||
price: product.price,
|
||||
marketPrice: product.marketPrice,
|
||||
unit: product.unitShortNotation,
|
||||
price: parseFloat(product.price),
|
||||
marketPrice: product.marketPrice ? parseFloat(product.marketPrice) : null,
|
||||
unit: product.unitNotation,
|
||||
unitNotation: product.unitNotation,
|
||||
incrementStep: product.incrementStep,
|
||||
productQuantity: product.productQuantity,
|
||||
storeId: product.storeId,
|
||||
storeId: product.store?.id || null,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null,
|
||||
images: await generateSignedUrlsFromS3Urls((product.images as string[]) || []),
|
||||
images: product.images, // Already signed URLs from cache
|
||||
};
|
||||
})
|
||||
);
|
||||
|
|
|
|||
|
|
@ -5,6 +5,27 @@ import { productInfo, units, productSlots, deliverySlotInfo, specialDeals, store
|
|||
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, generateUploadUrl, claimUploadUrl, extractKeyFromPresignedUrl } from '../../lib/s3-client';
|
||||
import { ApiError } from '../../lib/api-error';
|
||||
import { eq, and, gt, sql, inArray, desc } from 'drizzle-orm';
|
||||
import { getProductById as getProductByIdFromCache } from '../../lib/product-store';
|
||||
|
||||
// Uniform Product Type
|
||||
interface Product {
|
||||
id: number;
|
||||
name: string;
|
||||
shortDescription: string | null;
|
||||
longDescription: string | null;
|
||||
price: string;
|
||||
marketPrice: string | null;
|
||||
unitNotation: string;
|
||||
images: string[];
|
||||
isOutOfStock: boolean;
|
||||
store: { id: number; name: string; description: string | null } | null;
|
||||
incrementStep: number;
|
||||
productQuantity: number;
|
||||
isFlashAvailable: boolean;
|
||||
flashPrice: string | null;
|
||||
deliverySlots: Array<{ id: number; deliveryTime: Date; freezeTime: Date }>;
|
||||
specialDeals: Array<{ quantity: string; price: string; validTill: Date }>;
|
||||
}
|
||||
|
||||
export const productRouter = router({
|
||||
getDashboardTags: publicProcedure
|
||||
|
|
@ -32,7 +53,7 @@ export const productRouter = router({
|
|||
.input(z.object({
|
||||
id: z.string().regex(/^\d+$/, 'Invalid product ID'),
|
||||
}))
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input }): Promise<Product> => {
|
||||
const { id } = input;
|
||||
const productId = parseInt(id);
|
||||
|
||||
|
|
@ -40,7 +61,14 @@ export const productRouter = router({
|
|||
throw new Error('Invalid product ID');
|
||||
}
|
||||
|
||||
// Fetch product with unit information
|
||||
// First, try to get the product from Redis cache
|
||||
const cachedProduct = await getProductByIdFromCache(productId);
|
||||
|
||||
if (cachedProduct) {
|
||||
return cachedProduct;
|
||||
}
|
||||
|
||||
// If not in cache, fetch from database (fallback)
|
||||
const productData = await db
|
||||
.select({
|
||||
id: productInfo.id,
|
||||
|
|
@ -53,6 +81,8 @@ export const productRouter = router({
|
|||
isOutOfStock: productInfo.isOutOfStock,
|
||||
storeId: productInfo.storeId,
|
||||
unitShortNotation: units.shortNotation,
|
||||
incrementStep: productInfo.incrementStep,
|
||||
productQuantity: productInfo.productQuantity,
|
||||
isFlashAvailable: productInfo.isFlashAvailable,
|
||||
flashPrice: productInfo.flashPrice,
|
||||
})
|
||||
|
|
@ -110,25 +140,27 @@ export const productRouter = router({
|
|||
// Generate signed URLs for images
|
||||
const signedImages = await generateSignedUrlsFromS3Urls((product.images as string[]) || []);
|
||||
|
||||
const response = {
|
||||
const response: Product = {
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
shortDescription: product.shortDescription,
|
||||
longDescription: product.longDescription,
|
||||
price: product.price,
|
||||
marketPrice: product.marketPrice,
|
||||
unit: product.unitShortNotation,
|
||||
price: product.price.toString(),
|
||||
marketPrice: product.marketPrice?.toString() || null,
|
||||
unitNotation: product.unitShortNotation,
|
||||
images: signedImages,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
flashPrice: product.flashPrice,
|
||||
store: storeData ? {
|
||||
id: storeData.id,
|
||||
name: storeData.name,
|
||||
description: storeData.description,
|
||||
} : null,
|
||||
incrementStep: product.incrementStep,
|
||||
productQuantity: product.productQuantity,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
flashPrice: product.flashPrice?.toString() || null,
|
||||
deliverySlots: deliverySlotsData,
|
||||
specialPackageDeals: specialDealsData,
|
||||
specialDeals: specialDealsData.map(d => ({ quantity: d.quantity.toString(), price: d.price.toString(), validTill: d.validTill })),
|
||||
};
|
||||
|
||||
return response;
|
||||
|
|
@ -222,48 +254,95 @@ export const productRouter = router({
|
|||
}),
|
||||
|
||||
getAllProductsSummary: publicProcedure
|
||||
.query(async () => {
|
||||
const products = await db
|
||||
.select({
|
||||
id: productInfo.id,
|
||||
name: productInfo.name,
|
||||
price: productInfo.price,
|
||||
marketPrice: productInfo.marketPrice,
|
||||
images: productInfo.images,
|
||||
isOutOfStock: productInfo.isOutOfStock,
|
||||
storeId: productInfo.storeId,
|
||||
unitShortNotation: units.shortNotation,
|
||||
incrementStep: productInfo.incrementStep,
|
||||
isFlashAvailable: productInfo.isFlashAvailable,
|
||||
flashPrice: productInfo.flashPrice,
|
||||
productQuantity: productInfo.productQuantity,
|
||||
})
|
||||
.from(productInfo)
|
||||
.innerJoin(units, eq(productInfo.unitId, units.id));
|
||||
.query(async (): Promise<Product[]> => {
|
||||
// Get all product IDs first
|
||||
const productIdsResult = await db
|
||||
.select({ id: productInfo.id })
|
||||
.from(productInfo);
|
||||
|
||||
// Generate signed URLs for images
|
||||
const productsWithSignedUrls = await Promise.all(
|
||||
products.map(async (product) => ({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
price: product.price,
|
||||
marketPrice: product.marketPrice,
|
||||
unit: product.unitShortNotation,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
storeId: product.storeId,
|
||||
images: await generateSignedUrlsFromS3Urls((product.images as string[]) || []),
|
||||
incrementStep: product.incrementStep,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
flashPrice: product.flashPrice,
|
||||
productQuantity: product.productQuantity,
|
||||
}))
|
||||
);
|
||||
const productIds = productIdsResult.map(p => p.id);
|
||||
|
||||
return productsWithSignedUrls;
|
||||
// Try to get all products from cache first
|
||||
const cachedProducts: Product[] = [];
|
||||
const uncachedProductIds: number[] = [];
|
||||
|
||||
console.log(uncachedProductIds)
|
||||
|
||||
for (const id of productIds) {
|
||||
const cachedProduct = await getProductByIdFromCache(id);
|
||||
if (cachedProduct) {
|
||||
cachedProducts.push(cachedProduct);
|
||||
} else {
|
||||
uncachedProductIds.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
// If there are uncached products, fetch them from DB
|
||||
let uncachedProductsFromDb: Product[] = [];
|
||||
if (uncachedProductIds.length > 0) {
|
||||
const products = await db
|
||||
.select({
|
||||
id: productInfo.id,
|
||||
name: productInfo.name,
|
||||
price: productInfo.price,
|
||||
marketPrice: productInfo.marketPrice,
|
||||
images: productInfo.images,
|
||||
isOutOfStock: productInfo.isOutOfStock,
|
||||
storeId: productInfo.storeId,
|
||||
unitShortNotation: units.shortNotation,
|
||||
incrementStep: productInfo.incrementStep,
|
||||
isFlashAvailable: productInfo.isFlashAvailable,
|
||||
flashPrice: productInfo.flashPrice,
|
||||
productQuantity: productInfo.productQuantity,
|
||||
})
|
||||
.from(productInfo)
|
||||
.innerJoin(units, eq(productInfo.unitId, units.id))
|
||||
.where(inArray(productInfo.id, uncachedProductIds));
|
||||
|
||||
// Fetch all stores
|
||||
const allStores = await db.query.storeInfo.findMany({
|
||||
columns: { id: true, name: true, description: true },
|
||||
});
|
||||
const storeMap = new Map(allStores.map(s => [s.id, s]));
|
||||
|
||||
// Generate signed URLs for images and build uniform structure
|
||||
uncachedProductsFromDb = await Promise.all(
|
||||
products.map(async (product) => {
|
||||
const signedImages = await generateSignedUrlsFromS3Urls((product.images as string[]) || []);
|
||||
const store = product.storeId ? storeMap.get(product.storeId) || null : null;
|
||||
|
||||
return {
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
shortDescription: null,
|
||||
longDescription: null,
|
||||
price: product.price.toString(),
|
||||
marketPrice: product.marketPrice?.toString() || null,
|
||||
unitNotation: product.unitShortNotation,
|
||||
images: signedImages,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
store: store ? {
|
||||
id: store.id,
|
||||
name: store.name,
|
||||
description: store.description,
|
||||
} : null,
|
||||
incrementStep: product.incrementStep,
|
||||
productQuantity: product.productQuantity,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
flashPrice: product.flashPrice?.toString() || null,
|
||||
deliverySlots: [],
|
||||
specialDeals: [],
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Combine cached and uncached products
|
||||
return [...cachedProducts, ...uncachedProductsFromDb];
|
||||
}),
|
||||
|
||||
productMega: publicProcedure
|
||||
.query(async () => {
|
||||
.query(async (): Promise<Product[]> => {
|
||||
// Fetch all products with unit info
|
||||
const productsData = await db
|
||||
.select({
|
||||
|
|
@ -277,6 +356,10 @@ export const productRouter = router({
|
|||
isOutOfStock: productInfo.isOutOfStock,
|
||||
storeId: productInfo.storeId,
|
||||
unitShortNotation: units.shortNotation,
|
||||
incrementStep: productInfo.incrementStep,
|
||||
productQuantity: productInfo.productQuantity,
|
||||
isFlashAvailable: productInfo.isFlashAvailable,
|
||||
flashPrice: productInfo.flashPrice,
|
||||
})
|
||||
.from(productInfo)
|
||||
.innerJoin(units, eq(productInfo.unitId, units.id));
|
||||
|
|
@ -314,23 +397,43 @@ export const productRouter = router({
|
|||
deliverySlotsMap.get(slot.productId)!.push(slot);
|
||||
}
|
||||
|
||||
// Fetch all special deals for all products
|
||||
const allSpecialDeals = await db
|
||||
.select({
|
||||
productId: specialDeals.productId,
|
||||
quantity: specialDeals.quantity,
|
||||
price: specialDeals.price,
|
||||
validTill: specialDeals.validTill,
|
||||
})
|
||||
.from(specialDeals)
|
||||
.where(gt(specialDeals.validTill, sql`NOW()`))
|
||||
.orderBy(specialDeals.quantity);
|
||||
|
||||
// Group by productId
|
||||
const specialDealsMap = new Map<number, { productId: number; quantity: string; price: string; validTill: Date; }[]>();
|
||||
for (const deal of allSpecialDeals) {
|
||||
if (!specialDealsMap.has(deal.productId)) {
|
||||
specialDealsMap.set(deal.productId, []);
|
||||
}
|
||||
specialDealsMap.get(deal.productId)!.push(deal);
|
||||
}
|
||||
|
||||
// Build the response
|
||||
const response = await Promise.all(
|
||||
const response: Product[] = await Promise.all(
|
||||
productsData.map(async (product) => {
|
||||
const signedImages = await generateSignedUrlsFromS3Urls((product.images as string[]) || []);
|
||||
const store = product.storeId ? storeMap.get(product.storeId) || null : null;
|
||||
const deliverySlots = deliverySlotsMap.get(product.id) || [];
|
||||
const specialDeals = specialDealsMap.get(product.id) || [];
|
||||
|
||||
return {
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
shortDescription: product.shortDescription,
|
||||
longDescription: product.longDescription,
|
||||
price: product.price,
|
||||
marketPrice: product.marketPrice,
|
||||
unit: product.unitShortNotation,
|
||||
price: product.price.toString(),
|
||||
marketPrice: product.marketPrice?.toString() || null,
|
||||
unitNotation: product.unitShortNotation,
|
||||
images: signedImages,
|
||||
isOutOfStock: product.isOutOfStock,
|
||||
store: store ? {
|
||||
|
|
@ -338,8 +441,12 @@ export const productRouter = router({
|
|||
name: store.name,
|
||||
description: store.description,
|
||||
} : null,
|
||||
incrementStep: product.incrementStep,
|
||||
productQuantity: product.productQuantity,
|
||||
isFlashAvailable: product.isFlashAvailable,
|
||||
flashPrice: product.flashPrice?.toString() || null,
|
||||
deliverySlots: deliverySlots.map(s => ({ id: s.id, deliveryTime: s.deliveryTime, freezeTime: s.freezeTime })),
|
||||
specialPackageDeals: [], // Empty since not fetching
|
||||
specialDeals: specialDeals.map(d => ({ quantity: d.quantity.toString(), price: d.price.toString(), validTill: d.validTill })),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
|
|
|||
|
|
@ -142,7 +142,7 @@ export default function DeliverySlots() {
|
|||
{product.name}
|
||||
</MyText>
|
||||
<MyText style={tw`text-xs text-gray-600`}>
|
||||
₹{product.price} {product.unit && `per ${product.unit}`}
|
||||
₹{product.price} {product.unit && `per ${product.unit}`}
|
||||
</MyText>
|
||||
</View>
|
||||
{product.isOutOfStock && (
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { View, Text, TouchableOpacity, ScrollView } from 'react-native';
|
||||
import { tw, BottomDialog } from 'common-ui';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
|
@ -17,6 +17,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
}) => {
|
||||
const [showAddAddress, setShowAddAddress] = useState(false);
|
||||
const queryClient = useQueryClient();
|
||||
const scrollViewRef = useRef<ScrollView>(null);
|
||||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery();
|
||||
|
||||
// Sort addresses with selected first, then default, then others
|
||||
|
|
@ -46,6 +47,11 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
}
|
||||
}, [sortedAddresses, selectedAddress, onAddressSelect]);
|
||||
|
||||
// Reset scroll to left when address is selected
|
||||
const resetScrollToLeft = () => {
|
||||
scrollViewRef.current?.scrollTo({ x: 0, y: 0, animated: true });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
|
||||
|
|
@ -74,11 +80,19 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
</TouchableOpacity>
|
||||
</View>
|
||||
) : (
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={tw`pb-2`}>
|
||||
<ScrollView
|
||||
ref={scrollViewRef}
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
style={tw`pb-2`}
|
||||
>
|
||||
{sortedAddresses.map((address) => (
|
||||
<TouchableOpacity
|
||||
key={address.id}
|
||||
onPress={() => onAddressSelect(address.id)}
|
||||
onPress={() => {
|
||||
onAddressSelect(address.id);
|
||||
resetScrollToLeft();
|
||||
}}
|
||||
style={tw`w-72 p-4 mr-3 bg-gray-50 rounded-xl border-2 ${selectedAddress === address.id ? 'border-brand500 bg-blue-50' : 'border-gray-200'
|
||||
} shadow-sm`}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -128,7 +128,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
|
|||
)}
|
||||
</View>
|
||||
<View style={tw`flex-row items-center mb-2`}>
|
||||
<MyText style={tw`text-gray-500 text-xs font-medium`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{formatQuantity(item.productQuantity || 1, item.unit).display}</MyText></MyText>
|
||||
<MyText style={tw`text-gray-500 text-xs font-medium`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{formatQuantity(item.productQuantity || 1, item.unitNotation).display}</MyText></MyText>
|
||||
</View>
|
||||
|
||||
{showDeliveryInfo && item.nextDeliveryDate && (
|
||||
|
|
@ -151,7 +151,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
|
|||
value={quantity}
|
||||
setValue={handleQuantityChange}
|
||||
step={item.incrementStep}
|
||||
unit={item.unit}
|
||||
unit={item.unitNotation}
|
||||
/>
|
||||
) : (
|
||||
<MyTouchableOpacity
|
||||
|
|
|
|||
|
|
@ -29,6 +29,13 @@ interface ProductDetailProps {
|
|||
isFlashDelivery?: boolean;
|
||||
}
|
||||
|
||||
const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => {
|
||||
if (unit?.toLowerCase() === 'kg' && quantity < 1) {
|
||||
return { value: `${Math.round(quantity * 1000)} g`, display: `${Math.round(quantity * 1000)}g` };
|
||||
}
|
||||
return { value: `${quantity} ${unit}(s)`, display: `${quantity}${unit}` };
|
||||
};
|
||||
|
||||
const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDelivery = false }) => {
|
||||
const router = useRouter();
|
||||
const [showAllSlots, setShowAllSlots] = useState(false);
|
||||
|
|
@ -239,7 +246,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
<MyText style={tw`text-3xl font-bold text-gray-900`}>
|
||||
₹{productDetail.price}
|
||||
</MyText>
|
||||
<MyText style={tw`text-gray-500 text-lg mb-1 ml-1`}>/ {productDetail.unit}</MyText>
|
||||
<MyText style={tw`text-gray-500 text-lg mb-1 ml-1`}>/ {formatQuantity(productDetail.productQuantity || 1, productDetail.unitNotation).display}</MyText>
|
||||
|
||||
{/* Show market price discount if available */}
|
||||
{productDetail.marketPrice && (
|
||||
|
|
@ -256,7 +263,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
{productDetail.isFlashAvailable && productDetail.flashPrice && productDetail.flashPrice !== productDetail.price && (
|
||||
<View style={tw`mt-1`}>
|
||||
<MyText style={tw`text-pink-600 text-lg font-bold`}>
|
||||
Flash Delivery: ₹{productDetail.flashPrice} / {productDetail.unit}
|
||||
Flash Delivery: ₹{productDetail.flashPrice} / {formatQuantity(productDetail.productQuantity || 1, productDetail.unitNotation).display}
|
||||
</MyText>
|
||||
</View>
|
||||
)}
|
||||
|
|
@ -273,7 +280,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
value={quantity}
|
||||
setValue={handleQuantityChange}
|
||||
step={1} // Default step for product detail quantifier
|
||||
unit={productDetail.unit}
|
||||
unit={productDetail.unitNotation}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
|
|
@ -400,7 +407,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
</View>
|
||||
|
||||
{/* Package Deals */}
|
||||
{productDetail.specialPackageDeals && productDetail.specialPackageDeals.length > 0 && (
|
||||
{productDetail.specialDeals && productDetail.specialDeals.length > 0 && (
|
||||
<View style={tw`px-4 mb-4`}>
|
||||
<View style={tw`bg-white p-5 rounded-2xl shadow-sm border border-gray-100`}>
|
||||
<View style={tw`flex-row items-center mb-4`}>
|
||||
|
|
@ -410,9 +417,9 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
|||
<MyText style={tw`text-lg font-bold text-gray-900`}>Bulk Savings</MyText>
|
||||
</View>
|
||||
|
||||
{productDetail.specialPackageDeals.map((deal, index) => (
|
||||
{productDetail.specialDeals.map((deal: { quantity: string; price: string; validTill: string }, index: number) => (
|
||||
<View key={index} style={tw`flex-row justify-between items-center p-3 bg-amber-50 rounded-xl border border-amber-100 mb-2`}>
|
||||
<MyText style={tw`text-amber-900 font-medium`}>Buy {deal.quantity} {productDetail.unit}</MyText>
|
||||
<MyText style={tw`text-amber-900 font-medium`}>Buy {deal.quantity} {formatQuantity(parseFloat(deal.quantity), productDetail.unitNotation).display}</MyText>
|
||||
<MyText style={tw`text-amber-900 font-bold text-lg`}>₹{deal.price}</MyText>
|
||||
</View>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -293,7 +293,7 @@ const CompactProductCard = ({
|
|||
onChange={handleQuantityChange}
|
||||
step={item.incrementStep}
|
||||
showUnits={true}
|
||||
unit={item.unit}
|
||||
unit={item.unitNotation}
|
||||
/>
|
||||
) : (
|
||||
<MyTouchableOpacity
|
||||
|
|
@ -318,7 +318,7 @@ const CompactProductCard = ({
|
|||
{item.marketPrice && Number(item.marketPrice) > Number(item.price) && (
|
||||
<MyText style={tw`text-gray-400 text-xs ml-1 line-through`}>₹{item.marketPrice}</MyText>
|
||||
)}
|
||||
<MyText style={tw`text-gray-600 text-xs ml-1`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{formatQuantity(item.productQuantity || 1, item.unit).display}</MyText></MyText>
|
||||
<MyText style={tw`text-gray-600 text-xs ml-1`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{formatQuantity(item.productQuantity || 1, item.unitNotation).display}</MyText></MyText>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
|
@ -390,7 +390,7 @@ export function SlotProducts({ slotId:slotIdParent, storeId:storeIdParent, baseU
|
|||
);
|
||||
}
|
||||
|
||||
const filteredProducts: any[] = storeIdNum ? productsQuery?.data?.filter(p => p.storeId === storeIdNum) || [] : slotQuery.data.products;
|
||||
const filteredProducts: any[] = storeIdNum ? productsQuery?.data?.filter(p => p.store?.id === storeIdNum) || [] : slotQuery.data.products;
|
||||
|
||||
return (
|
||||
<View style={tw`flex-1`}>
|
||||
|
|
@ -470,7 +470,7 @@ export function FlashDeliveryProducts({ storeId:storeIdParent, baseUrl, onProduc
|
|||
let flashProducts: any[] = [];
|
||||
if (storeIdNum) {
|
||||
// Filter by store and flash availability
|
||||
flashProducts = productsQuery?.data?.filter(p => p.storeId === storeIdNum && p.isFlashAvailable) || [];
|
||||
flashProducts = productsQuery?.data?.filter(p => p.store?.id === storeIdNum && p.isFlashAvailable) || [];
|
||||
} else {
|
||||
// Show all flash-available products (no slot filtering)
|
||||
flashProducts = productsQuery?.data?.filter(p => p.isFlashAvailable) || [];
|
||||
|
|
|
|||
|
|
@ -444,7 +444,7 @@ export default function CartPage({ isFlashDelivery = false }: CartPageProps) {
|
|||
<MyText style={tw`text-xs text-gray-500 mr-2`}>
|
||||
{(() => {
|
||||
const qty = item.product?.productQuantity || 1;
|
||||
const unit = item.product?.unit || '';
|
||||
const unit = item.product?.unitNotation || '';
|
||||
if (unit?.toLowerCase() === 'kg' && qty < 1) {
|
||||
return `${Math.round(qty * 1000)}g`;
|
||||
}
|
||||
|
|
@ -506,7 +506,7 @@ export default function CartPage({ isFlashDelivery = false }: CartPageProps) {
|
|||
}
|
||||
}}
|
||||
step={item.product.incrementStep}
|
||||
unit={item.product?.unit}
|
||||
unit={item.product?.unitNotation}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -249,7 +249,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
}}
|
||||
step={item.product.incrementStep}
|
||||
showUnits={true}
|
||||
unit={item.product?.unit}
|
||||
unit={item.product?.unitNotation}
|
||||
/>
|
||||
</View>
|
||||
<View style={tw`flex-row items-center justify-between`}>
|
||||
|
|
|
|||
|
|
@ -25,11 +25,20 @@ interface LocalCartItem {
|
|||
interface ProductSummary {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
unit: string;
|
||||
isOutOfStock: boolean;
|
||||
shortDescription?: string | null;
|
||||
longDescription?: string | null;
|
||||
price: string;
|
||||
marketPrice?: string | null;
|
||||
unitNotation: string;
|
||||
images: string[];
|
||||
incrementStep?: number;
|
||||
isOutOfStock: boolean;
|
||||
store?: { id: number; name: string; description?: string | null } | null;
|
||||
incrementStep: number;
|
||||
productQuantity: number;
|
||||
isFlashAvailable: boolean;
|
||||
flashPrice?: string | null;
|
||||
deliverySlots: Array<{ id: number; deliveryTime: Date; freezeTime: Date }>;
|
||||
specialDeals: Array<{ quantity: string; price: string; validTill: Date }>;
|
||||
}
|
||||
|
||||
interface CartItem {
|
||||
|
|
|
|||
|
|
@ -63,9 +63,9 @@ const isDevMode = Constants.executionEnvironment !== "standalone";
|
|||
// const BASE_API_URL = API_URL;
|
||||
// const BASE_API_URL = 'http://10.0.2.2:4000';
|
||||
// const BASE_API_URL = 'http://192.168.100.101:4000';
|
||||
// const BASE_API_URL = 'http://192.168.1.9:4000';
|
||||
const BASE_API_URL = 'http://192.168.1.14:4000';
|
||||
// const BASE_API_URL = "https://mf.technocracy.ovh";
|
||||
let BASE_API_URL = "https://mf.freshyo.in";
|
||||
// let BASE_API_URL = "https://mf.freshyo.in";
|
||||
// let BASE_API_URL = 'http://192.168.100.103:4000';
|
||||
// let BASE_API_URL = 'http://192.168.29.219:4000';
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue