enh
This commit is contained in:
parent
77c46b777f
commit
903c5c27bc
14 changed files with 530 additions and 369 deletions
|
|
@ -1,7 +1,5 @@
|
||||||
import roleManager from './roles-manager';
|
|
||||||
import './notif-job';
|
import './notif-job';
|
||||||
import { computeConstants } from './const-store';
|
import { initializeAllStores } from '../stores/store-initializer';
|
||||||
import { initializeProducts } from './product-store';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize all application services
|
* Initialize all application services
|
||||||
|
|
@ -13,22 +11,13 @@ import { initializeProducts } from './product-store';
|
||||||
export const initFunc = async (): Promise<void> => {
|
export const initFunc = async (): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
console.log('Starting application initialization...');
|
console.log('Starting application initialization...');
|
||||||
|
|
||||||
// Initialize role manager
|
|
||||||
await roleManager.fetchRoles();
|
|
||||||
console.log('Role manager initialized successfully');
|
|
||||||
|
|
||||||
// Compute and store constants in Redis
|
// Initialize all stores
|
||||||
await computeConstants();
|
await initializeAllStores();
|
||||||
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
|
// Notification queue and worker are initialized via import
|
||||||
console.log('Notification queue and worker initialized');
|
console.log('Notification queue and worker initialized');
|
||||||
|
|
||||||
console.log('Application initialization completed successfully');
|
console.log('Application initialization completed successfully');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Application initialization failed:', error);
|
console.error('Application initialization failed:', error);
|
||||||
|
|
|
||||||
88
apps/backend/src/stores/banner-store.ts
Normal file
88
apps/backend/src/stores/banner-store.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
// import redisClient from './redis-client';
|
||||||
|
import redisClient from 'src/lib/redis-client';
|
||||||
|
import { db } from '../db/db_index';
|
||||||
|
import { homeBanners } from '../db/schema';
|
||||||
|
import { isNotNull, asc } from 'drizzle-orm';
|
||||||
|
import { generateSignedUrlFromS3Url } from 'src/lib/s3-client';
|
||||||
|
|
||||||
|
// Banner Type (matches getBanners return)
|
||||||
|
interface Banner {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
imageUrl: string | null;
|
||||||
|
serialNum: number | null;
|
||||||
|
productIds: number[] | null;
|
||||||
|
createdAt: Date;
|
||||||
|
// updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function initializeBannerStore(): Promise<void> {
|
||||||
|
try {
|
||||||
|
console.log('Initializing banner store in Redis...');
|
||||||
|
|
||||||
|
const banners = await db.query.homeBanners.findMany({
|
||||||
|
where: isNotNull(homeBanners.serialNum), // Only show assigned banners
|
||||||
|
orderBy: asc(homeBanners.serialNum), // Order by slot number 1-4
|
||||||
|
});
|
||||||
|
|
||||||
|
// Store each banner in Redis
|
||||||
|
for (const banner of banners) {
|
||||||
|
const signedImageUrl = banner.imageUrl ? await generateSignedUrlFromS3Url(banner.imageUrl) : banner.imageUrl;
|
||||||
|
|
||||||
|
const bannerObj: Banner = {
|
||||||
|
id: banner.id,
|
||||||
|
name: banner.name,
|
||||||
|
imageUrl: signedImageUrl,
|
||||||
|
serialNum: banner.serialNum,
|
||||||
|
productIds: banner.productIds,
|
||||||
|
createdAt: banner.createdAt,
|
||||||
|
// updatedAt: banner.updatedAt,
|
||||||
|
};
|
||||||
|
|
||||||
|
await redisClient.set(`banner:${banner.id}`, JSON.stringify(bannerObj));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Banner store initialized successfully');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error initializing banner store:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBannerById(id: number): Promise<Banner | null> {
|
||||||
|
try {
|
||||||
|
const key = `banner:${id}`;
|
||||||
|
const data = await redisClient.get(key);
|
||||||
|
if (!data) return null;
|
||||||
|
return JSON.parse(data) as Banner;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error getting banner ${id}:`, error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllBanners(): Promise<Banner[]> {
|
||||||
|
try {
|
||||||
|
// Get all keys matching the pattern "banner:*"
|
||||||
|
const keys = await redisClient.KEYS('banner:*');
|
||||||
|
|
||||||
|
if (keys.length === 0) return [];
|
||||||
|
|
||||||
|
// Get all banners using MGET for better performance
|
||||||
|
const bannersData = await redisClient.MGET(keys);
|
||||||
|
|
||||||
|
const banners: Banner[] = [];
|
||||||
|
for (const bannerData of bannersData) {
|
||||||
|
if (bannerData) {
|
||||||
|
banners.push(JSON.parse(bannerData) as Banner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by serialNum to maintain the same order as the original query
|
||||||
|
banners.sort((a, b) => (a.serialNum || 0) - (b.serialNum || 0));
|
||||||
|
|
||||||
|
return banners;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting all banners:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
import redisClient from './redis-client';
|
// import redisClient from './redis-client';
|
||||||
|
import redisClient from 'src/lib/redis-client';
|
||||||
import { db } from '../db/db_index';
|
import { db } from '../db/db_index';
|
||||||
import { productInfo, units, productSlots, deliverySlotInfo, specialDeals, storeInfo } from '../db/schema';
|
import { productInfo, units, productSlots, deliverySlotInfo, specialDeals, storeInfo } from '../db/schema';
|
||||||
import { generateSignedUrlsFromS3Urls } from './s3-client';
|
|
||||||
import { eq, and, gt, sql } from 'drizzle-orm';
|
import { eq, and, gt, sql } from 'drizzle-orm';
|
||||||
|
import { generateSignedUrlsFromS3Urls } from 'src/lib/s3-client';
|
||||||
|
|
||||||
// Uniform Product Type (matches getProductDetails return)
|
// Uniform Product Type (matches getProductDetails return)
|
||||||
interface Product {
|
interface Product {
|
||||||
|
|
@ -145,7 +146,9 @@ export async function getAllProducts(): Promise<Product[]> {
|
||||||
// Get all keys matching the pattern "product:*"
|
// Get all keys matching the pattern "product:*"
|
||||||
const keys = await redisClient.KEYS('product:*');
|
const keys = await redisClient.KEYS('product:*');
|
||||||
|
|
||||||
if (keys.length === 0) return [];
|
if (keys.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
// Get all products using MGET for better performance
|
// Get all products using MGET for better performance
|
||||||
const productsData = await redisClient.MGET(keys);
|
const productsData = await redisClient.MGET(keys);
|
||||||
115
apps/backend/src/stores/product-tag-store.ts
Normal file
115
apps/backend/src/stores/product-tag-store.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
||||||
|
// import redisClient from './redis-client';
|
||||||
|
import redisClient from 'src/lib/redis-client';
|
||||||
|
import { db } from '../db/db_index';
|
||||||
|
import { productTagInfo } from '../db/schema';
|
||||||
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { generateSignedUrlFromS3Url } from 'src/lib/s3-client';
|
||||||
|
|
||||||
|
// Tag Type (matches getDashboardTags return)
|
||||||
|
interface Tag {
|
||||||
|
id: number;
|
||||||
|
tagName: string;
|
||||||
|
imageUrl: string | null;
|
||||||
|
isDashboardTag: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function initializeProductTagStore(): Promise<void> {
|
||||||
|
try {
|
||||||
|
console.log('Initializing product tag store in Redis...');
|
||||||
|
|
||||||
|
// Fetch all tags
|
||||||
|
const tagsData = await db
|
||||||
|
.select({
|
||||||
|
id: productTagInfo.id,
|
||||||
|
tagName: productTagInfo.tagName,
|
||||||
|
imageUrl: productTagInfo.imageUrl,
|
||||||
|
isDashboardTag: productTagInfo.isDashboardTag,
|
||||||
|
})
|
||||||
|
.from(productTagInfo);
|
||||||
|
|
||||||
|
// Store each tag in Redis
|
||||||
|
for (const tag of tagsData) {
|
||||||
|
const signedImageUrl = tag.imageUrl ? await generateSignedUrlFromS3Url(tag.imageUrl) : null;
|
||||||
|
|
||||||
|
const tagObj: Tag = {
|
||||||
|
id: tag.id,
|
||||||
|
tagName: tag.tagName,
|
||||||
|
imageUrl: signedImageUrl,
|
||||||
|
isDashboardTag: tag.isDashboardTag,
|
||||||
|
};
|
||||||
|
|
||||||
|
await redisClient.set(`tag:${tag.id}`, JSON.stringify(tagObj));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Product tag store initialized successfully');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error initializing product tag store:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTagById(id: number): Promise<Tag | null> {
|
||||||
|
try {
|
||||||
|
const key = `tag:${id}`;
|
||||||
|
const data = await redisClient.get(key);
|
||||||
|
if (!data) return null;
|
||||||
|
return JSON.parse(data) as Tag;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error getting tag ${id}:`, error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllTags(): Promise<Tag[]> {
|
||||||
|
try {
|
||||||
|
// Get all keys matching the pattern "tag:*"
|
||||||
|
const keys = await redisClient.KEYS('tag:*');
|
||||||
|
|
||||||
|
if (keys.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all tags using MGET for better performance
|
||||||
|
const tagsData = await redisClient.MGET(keys);
|
||||||
|
|
||||||
|
const tags: Tag[] = [];
|
||||||
|
for (const tagData of tagsData) {
|
||||||
|
if (tagData) {
|
||||||
|
tags.push(JSON.parse(tagData) as Tag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return tags;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting all tags:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getDashboardTags(): Promise<Tag[]> {
|
||||||
|
try {
|
||||||
|
// Get all keys matching the pattern "tag:*"
|
||||||
|
const keys = await redisClient.KEYS('tag:*');
|
||||||
|
|
||||||
|
if (keys.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all tags using MGET for better performance
|
||||||
|
const tagsData = await redisClient.MGET(keys);
|
||||||
|
|
||||||
|
const dashboardTags: Tag[] = [];
|
||||||
|
for (const tagData of tagsData) {
|
||||||
|
if (tagData) {
|
||||||
|
const tag = JSON.parse(tagData) as Tag;
|
||||||
|
if (tag.isDashboardTag) {
|
||||||
|
dashboardTags.push(tag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return dashboardTags;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting dashboard tags:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
125
apps/backend/src/stores/slot-store.ts
Normal file
125
apps/backend/src/stores/slot-store.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
import redisClient from 'src/lib/redis-client';
|
||||||
|
import { db } from '../db/db_index';
|
||||||
|
import { deliverySlotInfo, productSlots, productInfo, units } from '../db/schema';
|
||||||
|
import { eq, and, gt, asc } from 'drizzle-orm';
|
||||||
|
import { generateSignedUrlsFromS3Urls } from 'src/lib/s3-client';
|
||||||
|
|
||||||
|
// Define the structure for slot with products
|
||||||
|
interface SlotWithProducts {
|
||||||
|
id: number;
|
||||||
|
deliveryTime: Date;
|
||||||
|
freezeTime: Date;
|
||||||
|
isActive: boolean;
|
||||||
|
products: Array<{
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
shortDescription: string | null;
|
||||||
|
price: string;
|
||||||
|
marketPrice: string | null;
|
||||||
|
unit: string | null;
|
||||||
|
images: string[];
|
||||||
|
isOutOfStock: boolean;
|
||||||
|
storeId: number | null;
|
||||||
|
nextDeliveryDate: Date;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function initializeSlotStore(): Promise<void> {
|
||||||
|
try {
|
||||||
|
console.log('Initializing slot store in Redis...');
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
// Fetch active delivery slots with future delivery times
|
||||||
|
const slots = await db.query.deliverySlotInfo.findMany({
|
||||||
|
where: and(
|
||||||
|
eq(deliverySlotInfo.isActive, true),
|
||||||
|
gt(deliverySlotInfo.deliveryTime, now), // Only future slots
|
||||||
|
),
|
||||||
|
with: {
|
||||||
|
productSlots: {
|
||||||
|
with: {
|
||||||
|
product: {
|
||||||
|
with: {
|
||||||
|
unit: true,
|
||||||
|
store: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: asc(deliverySlotInfo.deliveryTime),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Transform data for storage
|
||||||
|
const slotsWithProducts = await Promise.all(
|
||||||
|
slots.map(async (slot) => ({
|
||||||
|
id: slot.id,
|
||||||
|
deliveryTime: slot.deliveryTime,
|
||||||
|
freezeTime: slot.freezeTime,
|
||||||
|
isActive: slot.isActive,
|
||||||
|
products: await Promise.all(
|
||||||
|
slot.productSlots.map(async (productSlot) => ({
|
||||||
|
id: productSlot.product.id,
|
||||||
|
name: productSlot.product.name,
|
||||||
|
shortDescription: productSlot.product.shortDescription,
|
||||||
|
price: productSlot.product.price.toString(),
|
||||||
|
marketPrice: productSlot.product.marketPrice?.toString() || null,
|
||||||
|
unit: productSlot.product.unit?.shortNotation || null,
|
||||||
|
images: await generateSignedUrlsFromS3Urls(
|
||||||
|
(productSlot.product.images as string[]) || [],
|
||||||
|
),
|
||||||
|
isOutOfStock: productSlot.product.isOutOfStock,
|
||||||
|
storeId: productSlot.product.storeId,
|
||||||
|
nextDeliveryDate: slot.deliveryTime,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Store each slot in Redis with key pattern "slot:{id}"
|
||||||
|
for (const slot of slotsWithProducts) {
|
||||||
|
await redisClient.set(`slot:${slot.id}`, JSON.stringify(slot));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Slot store initialized successfully');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error initializing slot store:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSlotById(slotId: number): Promise<SlotWithProducts | null> {
|
||||||
|
try {
|
||||||
|
const key = `slot:${slotId}`;
|
||||||
|
const data = await redisClient.get(key);
|
||||||
|
if (!data) return null;
|
||||||
|
return JSON.parse(data) as SlotWithProducts;
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error getting slot ${slotId}:`, error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllSlots(): Promise<SlotWithProducts[]> {
|
||||||
|
try {
|
||||||
|
// Get all keys matching the pattern "slot:*"
|
||||||
|
const keys = await redisClient.KEYS('slot:*');
|
||||||
|
|
||||||
|
if (keys.length === 0) return [];
|
||||||
|
|
||||||
|
// Get all slots using MGET for better performance
|
||||||
|
const slotsData = await redisClient.MGET(keys);
|
||||||
|
|
||||||
|
const slots: SlotWithProducts[] = [];
|
||||||
|
for (const slotData of slotsData) {
|
||||||
|
if (slotData) {
|
||||||
|
slots.push(JSON.parse(slotData) as SlotWithProducts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return slots;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting all slots:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
51
apps/backend/src/stores/store-initializer.ts
Normal file
51
apps/backend/src/stores/store-initializer.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
import roleManager from '../lib/roles-manager';
|
||||||
|
import { computeConstants } from '../lib/const-store';
|
||||||
|
import { initializeProducts } from './product-store';
|
||||||
|
import { initializeProductTagStore } from './product-tag-store';
|
||||||
|
import { initializeSlotStore } from './slot-store';
|
||||||
|
import { initializeBannerStore } from './banner-store';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize all application stores
|
||||||
|
* This function handles initialization of:
|
||||||
|
* - Role Manager (fetches and caches all roles)
|
||||||
|
* - Const Store (syncs constants from DB to Redis)
|
||||||
|
* - Product Store (caches all products in Redis)
|
||||||
|
* - Product Tag Store (caches all product tags in Redis)
|
||||||
|
* - Slot Store (caches all delivery slots with products in Redis)
|
||||||
|
* - Banner Store (caches all banners in Redis)
|
||||||
|
*/
|
||||||
|
export const initializeAllStores = async (): Promise<void> => {
|
||||||
|
try {
|
||||||
|
console.log('Starting application stores initialization...');
|
||||||
|
|
||||||
|
// Initialize role manager
|
||||||
|
await roleManager.fetchRoles();
|
||||||
|
console.log('Role manager initialized successfully');
|
||||||
|
|
||||||
|
// Compute and store constants in Redis
|
||||||
|
await computeConstants();
|
||||||
|
console.log('Const store initialized successfully');
|
||||||
|
|
||||||
|
// Initialize product store in Redis
|
||||||
|
await initializeProducts();
|
||||||
|
console.log('Product store initialized successfully');
|
||||||
|
|
||||||
|
// Initialize product tag store in Redis
|
||||||
|
await initializeProductTagStore();
|
||||||
|
console.log('Product tag store initialized successfully');
|
||||||
|
|
||||||
|
// Initialize slot store in Redis
|
||||||
|
await initializeSlotStore();
|
||||||
|
console.log('Slot store initialized successfully');
|
||||||
|
|
||||||
|
// Initialize banner store in Redis
|
||||||
|
await initializeBannerStore();
|
||||||
|
console.log('Banner store initialized successfully');
|
||||||
|
|
||||||
|
console.log('All application stores initialized successfully');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Application stores initialization failed:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -5,6 +5,7 @@ import { eq, and, desc, sql } from 'drizzle-orm';
|
||||||
import { protectedProcedure, router } from '../trpc-index';
|
import { protectedProcedure, router } from '../trpc-index';
|
||||||
import { extractKeyFromPresignedUrl, generateSignedUrlFromS3Url } from '../../lib/s3-client';
|
import { extractKeyFromPresignedUrl, generateSignedUrlFromS3Url } from '../../lib/s3-client';
|
||||||
import { ApiError } from 'src/lib/api-error';
|
import { ApiError } from 'src/lib/api-error';
|
||||||
|
import { initializeAllStores } from '../../stores/store-initializer';
|
||||||
|
|
||||||
export const bannerRouter = router({
|
export const bannerRouter = router({
|
||||||
// Get all banners
|
// Get all banners
|
||||||
|
|
@ -102,6 +103,9 @@ export const bannerRouter = router({
|
||||||
isActive: false, // Default to inactive
|
isActive: false, // Default to inactive
|
||||||
}).returning();
|
}).returning();
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return banner;
|
return banner;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating banner:', error);
|
console.error('Error creating banner:', error);
|
||||||
|
|
@ -145,6 +149,10 @@ export const bannerRouter = router({
|
||||||
.set({ ...finalData, lastUpdated: new Date(), })
|
.set({ ...finalData, lastUpdated: new Date(), })
|
||||||
.where(eq(homeBanners.id, id))
|
.where(eq(homeBanners.id, id))
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return banner;
|
return banner;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error updating banner:', error);
|
console.error('Error updating banner:', error);
|
||||||
|
|
@ -157,6 +165,10 @@ export const bannerRouter = router({
|
||||||
.input(z.object({ id: z.number() }))
|
.input(z.object({ id: z.number() }))
|
||||||
.mutation(async ({ input }) => {
|
.mutation(async ({ input }) => {
|
||||||
await db.delete(homeBanners).where(eq(homeBanners.id, input.id));
|
await db.delete(homeBanners).where(eq(homeBanners.id, input.id));
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
@ -7,6 +7,7 @@ import { ApiError } from '../../lib/api-error';
|
||||||
import { imageUploadS3, generateSignedUrlsFromS3Urls, getOriginalUrlFromSignedUrl, claimUploadUrl } from '../../lib/s3-client';
|
import { imageUploadS3, generateSignedUrlsFromS3Urls, getOriginalUrlFromSignedUrl, claimUploadUrl } from '../../lib/s3-client';
|
||||||
import { deleteS3Image } from '../../lib/delete-image';
|
import { deleteS3Image } from '../../lib/delete-image';
|
||||||
import type { SpecialDeal } from '../../db/types';
|
import type { SpecialDeal } from '../../db/types';
|
||||||
|
import { initializeAllStores } from '../../stores/store-initializer';
|
||||||
|
|
||||||
type CreateDeal = {
|
type CreateDeal = {
|
||||||
quantity: number;
|
quantity: number;
|
||||||
|
|
@ -100,6 +101,9 @@ export const productRouter = router({
|
||||||
throw new ApiError("Product not found", 404);
|
throw new ApiError("Product not found", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: "Product deleted successfully",
|
message: "Product deleted successfully",
|
||||||
};
|
};
|
||||||
|
|
@ -128,6 +132,9 @@ export const productRouter = router({
|
||||||
.where(eq(productInfo.id, id))
|
.where(eq(productInfo.id, id))
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
product: updatedProduct,
|
product: updatedProduct,
|
||||||
message: `Product marked as ${updatedProduct.isOutOfStock ? 'out of stock' : 'in stock'}`,
|
message: `Product marked as ${updatedProduct.isOutOfStock ? 'out of stock' : 'in stock'}`,
|
||||||
|
|
@ -181,6 +188,9 @@ export const productRouter = router({
|
||||||
await db.insert(productSlots).values(newAssociations);
|
await db.insert(productSlots).values(newAssociations);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: "Slot products updated successfully",
|
message: "Slot products updated successfully",
|
||||||
added: productsToAdd.length,
|
added: productsToAdd.length,
|
||||||
|
|
@ -380,6 +390,9 @@ export const productRouter = router({
|
||||||
await db.insert(productGroupMembership).values(memberships);
|
await db.insert(productGroupMembership).values(memberships);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
group: newGroup,
|
group: newGroup,
|
||||||
message: 'Group created successfully',
|
message: 'Group created successfully',
|
||||||
|
|
@ -425,6 +438,9 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
group: updatedGroup,
|
group: updatedGroup,
|
||||||
message: 'Group updated successfully',
|
message: 'Group updated successfully',
|
||||||
|
|
@ -451,6 +467,9 @@ export const productRouter = router({
|
||||||
throw new ApiError('Group not found', 404);
|
throw new ApiError('Group not found', 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: 'Group deleted successfully',
|
message: 'Group deleted successfully',
|
||||||
};
|
};
|
||||||
|
|
@ -504,6 +523,9 @@ export const productRouter = router({
|
||||||
|
|
||||||
await Promise.all(updatePromises);
|
await Promise.all(updatePromises);
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: `Updated prices for ${updates.length} product(s)`,
|
message: `Updated prices for ${updates.length} product(s)`,
|
||||||
updatedCount: updates.length,
|
updatedCount: updates.length,
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { ApiError } from "../../lib/api-error";
|
||||||
import { appUrl } from "../../lib/env-exporter";
|
import { appUrl } from "../../lib/env-exporter";
|
||||||
import redisClient from "../../lib/redis-client";
|
import redisClient from "../../lib/redis-client";
|
||||||
import { getSlotSequenceKey } from "../../lib/redisKeyGetters";
|
import { getSlotSequenceKey } from "../../lib/redisKeyGetters";
|
||||||
|
import { initializeAllStores } from '../../stores/store-initializer';
|
||||||
|
|
||||||
interface CachedDeliverySequence {
|
interface CachedDeliverySequence {
|
||||||
[userId: string]: number[];
|
[userId: string]: number[];
|
||||||
|
|
@ -211,6 +212,9 @@ export const slotsRouter = router({
|
||||||
await db.insert(productSlots).values(newAssociations);
|
await db.insert(productSlots).values(newAssociations);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: "Slot products updated successfully",
|
message: "Slot products updated successfully",
|
||||||
added: productsToAdd.length,
|
added: productsToAdd.length,
|
||||||
|
|
@ -283,6 +287,9 @@ export const slotsRouter = router({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
slot: newSlot,
|
slot: newSlot,
|
||||||
createdSnippets,
|
createdSnippets,
|
||||||
|
|
@ -425,6 +432,9 @@ export const slotsRouter = router({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
slot: updatedSlot,
|
slot: updatedSlot,
|
||||||
createdSnippets,
|
createdSnippets,
|
||||||
|
|
@ -457,6 +467,9 @@ export const slotsRouter = router({
|
||||||
throw new ApiError("Slot not found", 404);
|
throw new ApiError("Slot not found", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: "Slot deleted successfully",
|
message: "Slot deleted successfully",
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import { eq, inArray } from 'drizzle-orm';
|
||||||
import { ApiError } from '../../lib/api-error';
|
import { ApiError } from '../../lib/api-error';
|
||||||
import { extractKeyFromPresignedUrl, deleteImageUtil, generateSignedUrlFromS3Url } from '../../lib/s3-client';
|
import { extractKeyFromPresignedUrl, deleteImageUtil, generateSignedUrlFromS3Url } from '../../lib/s3-client';
|
||||||
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
||||||
|
import { initializeAllStores } from '../../stores/store-initializer';
|
||||||
|
|
||||||
export const storeRouter = router({
|
export const storeRouter = router({
|
||||||
getStores: protectedProcedure
|
getStores: protectedProcedure
|
||||||
|
|
@ -83,6 +84,9 @@ export const storeRouter = router({
|
||||||
.where(inArray(productInfo.id, products));
|
.where(inArray(productInfo.id, products));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
store: newStore,
|
store: newStore,
|
||||||
message: "Store created successfully",
|
message: "Store created successfully",
|
||||||
|
|
@ -159,6 +163,9 @@ export const storeRouter = router({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
store: updatedStore,
|
store: updatedStore,
|
||||||
message: "Store updated successfully",
|
message: "Store updated successfully",
|
||||||
|
|
@ -189,6 +196,9 @@ export const storeRouter = router({
|
||||||
throw new ApiError("Store not found", 404);
|
throw new ApiError("Store not found", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await initializeAllStores();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: "Store deleted successfully",
|
message: "Store deleted successfully",
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,8 @@ import { productInfo, units, productSlots, deliverySlotInfo, storeInfo, productT
|
||||||
import { eq, gt, and, sql, inArray } from 'drizzle-orm';
|
import { eq, gt, and, sql, inArray } from 'drizzle-orm';
|
||||||
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url } from '../../lib/s3-client';
|
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url } from '../../lib/s3-client';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { getAllProducts as getAllProductsFromCache } from '../../lib/product-store';
|
import { getAllProducts as getAllProductsFromCache } from '../../stores/product-store';
|
||||||
|
import { getDashboardTags as getDashboardTagsFromCache } from '../../stores/product-tag-store';
|
||||||
|
|
||||||
export const getNextDeliveryDate = async (productId: number): Promise<Date | null> => {
|
export const getNextDeliveryDate = async (productId: number): Promise<Date | null> => {
|
||||||
const result = await db
|
const result = await db
|
||||||
|
|
@ -32,22 +33,11 @@ export const getNextDeliveryDate = async (productId: number): Promise<Date | nul
|
||||||
export const commonRouter = router({
|
export const commonRouter = router({
|
||||||
getDashboardTags: publicProcedure
|
getDashboardTags: publicProcedure
|
||||||
.query(async () => {
|
.query(async () => {
|
||||||
const tags = await db
|
// Get dashboard tags from cache
|
||||||
.select()
|
const tags = await getDashboardTagsFromCache();
|
||||||
.from(productTagInfo)
|
|
||||||
.where(eq(productTagInfo.isDashboardTag, true))
|
|
||||||
.orderBy(productTagInfo.tagName);
|
|
||||||
|
|
||||||
// Generate signed URLs for tag images
|
|
||||||
const tagsWithSignedUrls = await Promise.all(
|
|
||||||
tags.map(async (tag) => ({
|
|
||||||
...tag,
|
|
||||||
imageUrl: tag.imageUrl ? await generateSignedUrlFromS3Url(tag.imageUrl) : null,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tags: tagsWithSignedUrls,
|
tags: tags,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { productInfo, units, productSlots, deliverySlotInfo, specialDeals, store
|
||||||
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, generateUploadUrl, claimUploadUrl, extractKeyFromPresignedUrl } from '../../lib/s3-client';
|
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, generateUploadUrl, claimUploadUrl, extractKeyFromPresignedUrl } from '../../lib/s3-client';
|
||||||
import { ApiError } from '../../lib/api-error';
|
import { ApiError } from '../../lib/api-error';
|
||||||
import { eq, and, gt, sql, inArray, desc } from 'drizzle-orm';
|
import { eq, and, gt, sql, inArray, desc } from 'drizzle-orm';
|
||||||
import { getProductById as getProductByIdFromCache } from '../../lib/product-store';
|
import { getProductById as getProductByIdFromCache, getAllProducts as getAllProductsFromCache } from '../../stores/product-store';
|
||||||
|
|
||||||
// Uniform Product Type
|
// Uniform Product Type
|
||||||
interface Product {
|
interface Product {
|
||||||
|
|
@ -28,27 +28,6 @@ interface Product {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const productRouter = router({
|
export const productRouter = router({
|
||||||
getDashboardTags: publicProcedure
|
|
||||||
.query(async () => {
|
|
||||||
const tags = await db
|
|
||||||
.select()
|
|
||||||
.from(productTagInfo)
|
|
||||||
.where(eq(productTagInfo.isDashboardTag, true))
|
|
||||||
.orderBy(productTagInfo.tagName);
|
|
||||||
|
|
||||||
// Generate signed URLs for tag images
|
|
||||||
const tagsWithSignedUrls = await Promise.all(
|
|
||||||
tags.map(async (tag) => ({
|
|
||||||
...tag,
|
|
||||||
imageUrl: tag.imageUrl ? await generateSignedUrlFromS3Url(tag.imageUrl) : null,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
tags: tagsWithSignedUrls,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
|
|
||||||
getProductDetails: publicProcedure
|
getProductDetails: publicProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.string().regex(/^\d+$/, 'Invalid product ID'),
|
id: z.string().regex(/^\d+$/, 'Invalid product ID'),
|
||||||
|
|
@ -61,9 +40,11 @@ export const productRouter = router({
|
||||||
throw new Error('Invalid product ID');
|
throw new Error('Invalid product ID');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('from the api to get product details')
|
||||||
|
|
||||||
// First, try to get the product from Redis cache
|
// First, try to get the product from Redis cache
|
||||||
const cachedProduct = await getProductByIdFromCache(productId);
|
const cachedProduct = await getProductByIdFromCache(productId);
|
||||||
|
|
||||||
if (cachedProduct) {
|
if (cachedProduct) {
|
||||||
return cachedProduct;
|
return cachedProduct;
|
||||||
}
|
}
|
||||||
|
|
@ -255,202 +236,18 @@ export const productRouter = router({
|
||||||
|
|
||||||
getAllProductsSummary: publicProcedure
|
getAllProductsSummary: publicProcedure
|
||||||
.query(async (): Promise<Product[]> => {
|
.query(async (): Promise<Product[]> => {
|
||||||
// Get all product IDs first
|
// Get all products from cache
|
||||||
const productIdsResult = await db
|
const allCachedProducts = await getAllProductsFromCache();
|
||||||
.select({ id: productInfo.id })
|
|
||||||
.from(productInfo);
|
|
||||||
|
|
||||||
const productIds = productIdsResult.map(p => p.id);
|
// Transform the cached products to match the expected summary format
|
||||||
|
// (with empty deliverySlots and specialDeals arrays for summary view)
|
||||||
|
const transformedProducts = allCachedProducts.map(product => ({
|
||||||
|
...product,
|
||||||
|
deliverySlots: [], // Empty for summary view
|
||||||
|
specialDeals: [], // Empty for summary view
|
||||||
|
}));
|
||||||
|
|
||||||
// Try to get all products from cache first
|
return transformedProducts;
|
||||||
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 (): Promise<Product[]> => {
|
|
||||||
// Fetch all products with unit info
|
|
||||||
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 for all products
|
|
||||||
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()`)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.orderBy(deliverySlotInfo.deliveryTime);
|
|
||||||
|
|
||||||
// Group by productId
|
|
||||||
const deliverySlotsMap = new Map<number, { productId: number; id: number; deliveryTime: Date; freezeTime: Date; }[]>();
|
|
||||||
for (const slot of allDeliverySlots) {
|
|
||||||
if (!deliverySlotsMap.has(slot.productId)) {
|
|
||||||
deliverySlotsMap.set(slot.productId, []);
|
|
||||||
}
|
|
||||||
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: 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.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 })),
|
|
||||||
};
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
return response;
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
@ -1,49 +1,27 @@
|
||||||
import { router, publicProcedure } from '../trpc-index';
|
import { router, publicProcedure } from "../trpc-index";
|
||||||
import { z } from 'zod';
|
import { z } from "zod";
|
||||||
import { db } from '../../db/db_index';
|
import { db } from "../../db/db_index";
|
||||||
import { deliverySlotInfo, productSlots, productInfo, units } from '../../db/schema';
|
import {
|
||||||
import { eq, and, gt, asc } from 'drizzle-orm';
|
deliverySlotInfo,
|
||||||
import { generateSignedUrlsFromS3Urls } from '../../lib/s3-client';
|
productSlots,
|
||||||
|
productInfo,
|
||||||
|
units,
|
||||||
|
} from "../../db/schema";
|
||||||
|
import { eq, and, gt, asc } from "drizzle-orm";
|
||||||
|
import { generateSignedUrlsFromS3Urls } from "../../lib/s3-client";
|
||||||
|
import { getAllSlots as getAllSlotsFromCache, getSlotById as getSlotByIdFromCache } from "../../stores/slot-store";
|
||||||
|
|
||||||
// Helper method to get formatted slot data by ID
|
// Helper method to get formatted slot data by ID
|
||||||
async function getSlotData(slotId: number) {
|
async function getSlotData(slotId: number) {
|
||||||
const slot = await db.query.deliverySlotInfo.findFirst({
|
// Get slot from cache
|
||||||
where: eq(deliverySlotInfo.id, slotId),
|
const slot = await getSlotByIdFromCache(slotId);
|
||||||
with: {
|
|
||||||
productSlots: {
|
|
||||||
with: {
|
|
||||||
product: {
|
|
||||||
with: {
|
|
||||||
unit: true,
|
|
||||||
store: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!slot) {
|
if (!slot) {
|
||||||
return null; // Slot not found
|
return null; // Slot not found
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter out out-of-stock products and format to match home page display structure
|
// Filter out out-of-stock products and format to match home page display structure
|
||||||
const products = await Promise.all(
|
const products = slot.products.filter((product) => !product.isOutOfStock);
|
||||||
slot.productSlots
|
|
||||||
.filter(productSlot => !productSlot.product.isOutOfStock)
|
|
||||||
.map(async (productSlot) => ({
|
|
||||||
id: productSlot.product.id,
|
|
||||||
name: productSlot.product.name,
|
|
||||||
price: productSlot.product.price,
|
|
||||||
unit: productSlot.product.unit?.shortNotation || 'unit',
|
|
||||||
images: await generateSignedUrlsFromS3Urls(
|
|
||||||
(productSlot.product.images as string[]) || []
|
|
||||||
),
|
|
||||||
isOutOfStock: productSlot.product.isOutOfStock,
|
|
||||||
storeId: productSlot.product.storeId,
|
|
||||||
nextDeliveryDate: slot.deliveryTime, // For home page compatibility
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
deliveryTime: slot.deliveryTime,
|
deliveryTime: slot.deliveryTime,
|
||||||
|
|
@ -54,95 +32,64 @@ async function getSlotData(slotId: number) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const slotsRouter = router({
|
export const slotsRouter = router({
|
||||||
getSlots: publicProcedure
|
getSlots: publicProcedure.query(async () => {
|
||||||
.query(async () => {
|
const slots = await db.query.deliverySlotInfo.findMany({
|
||||||
const slots = await db.query.deliverySlotInfo.findMany({
|
where: eq(deliverySlotInfo.isActive, true),
|
||||||
where: eq(deliverySlotInfo.isActive, true),
|
});
|
||||||
});
|
return {
|
||||||
return {
|
slots,
|
||||||
slots,
|
count: slots.length,
|
||||||
count: slots.length,
|
};
|
||||||
};
|
}),
|
||||||
}),
|
|
||||||
|
|
||||||
getSlotsWithProducts: publicProcedure
|
getSlotsWithProducts: publicProcedure.query(async () => {
|
||||||
.query(async () => {
|
// Get all slots from cache
|
||||||
const now = new Date();
|
const slotsWithProducts = await getAllSlotsFromCache();
|
||||||
|
|
||||||
// Fetch active delivery slots with future delivery times
|
return {
|
||||||
const slots = await db.query.deliverySlotInfo.findMany({
|
slots: slotsWithProducts,
|
||||||
where: and(
|
count: slotsWithProducts.length,
|
||||||
eq(deliverySlotInfo.isActive, true),
|
};
|
||||||
gt(deliverySlotInfo.deliveryTime, now) // Only future slots
|
}),
|
||||||
),
|
|
||||||
with: {
|
|
||||||
productSlots: {
|
|
||||||
with: {
|
|
||||||
product: {
|
|
||||||
with: {
|
|
||||||
unit: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderBy: asc(deliverySlotInfo.deliveryTime),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Transform data for frontend
|
nextMajorDelivery: publicProcedure.query(async () => {
|
||||||
const slotsWithProducts = await Promise.all(
|
const now = new Date();
|
||||||
slots.map(async (slot) => ({
|
|
||||||
id: slot.id,
|
|
||||||
deliveryTime: slot.deliveryTime,
|
|
||||||
freezeTime: slot.freezeTime,
|
|
||||||
isActive: slot.isActive,
|
|
||||||
products: await Promise.all(
|
|
||||||
slot.productSlots.map(async (productSlot) => ({
|
|
||||||
id: productSlot.product.id,
|
|
||||||
name: productSlot.product.name,
|
|
||||||
shortDescription: productSlot.product.shortDescription,
|
|
||||||
price: productSlot.product.price,
|
|
||||||
marketPrice: productSlot.product.marketPrice,
|
|
||||||
unit: productSlot.product.unit?.shortNotation,
|
|
||||||
images: await generateSignedUrlsFromS3Urls(
|
|
||||||
(productSlot.product.images as string[]) || []
|
|
||||||
),
|
|
||||||
isOutOfStock: productSlot.product.isOutOfStock,
|
|
||||||
}))
|
|
||||||
),
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
// Find the next upcoming active delivery slot ID
|
||||||
slots: slotsWithProducts,
|
const nextSlot = await db.query.deliverySlotInfo.findFirst({
|
||||||
count: slotsWithProducts.length,
|
where: and(
|
||||||
};
|
eq(deliverySlotInfo.isActive, true),
|
||||||
}),
|
gt(deliverySlotInfo.deliveryTime, now),
|
||||||
|
),
|
||||||
|
orderBy: asc(deliverySlotInfo.deliveryTime),
|
||||||
|
});
|
||||||
|
|
||||||
nextMajorDelivery: publicProcedure
|
if (!nextSlot) {
|
||||||
.query(async () => {
|
return null; // No upcoming delivery slots
|
||||||
const now = new Date();
|
}
|
||||||
|
|
||||||
// Find the next upcoming active delivery slot ID
|
// Get formatted data using helper method
|
||||||
const nextSlot = await db.query.deliverySlotInfo.findFirst({
|
return await getSlotData(nextSlot.id);
|
||||||
where: and(
|
}),
|
||||||
eq(deliverySlotInfo.isActive, true),
|
|
||||||
gt(deliverySlotInfo.deliveryTime, now)
|
|
||||||
),
|
|
||||||
orderBy: asc(deliverySlotInfo.deliveryTime),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!nextSlot) {
|
|
||||||
return null; // No upcoming delivery slots
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get formatted data using helper method
|
|
||||||
return await getSlotData(nextSlot.id);
|
|
||||||
}),
|
|
||||||
|
|
||||||
getSlotById: publicProcedure
|
getSlotById: publicProcedure
|
||||||
.input(z.object({ slotId: z.number() }))
|
.input(z.object({ slotId: z.number() }))
|
||||||
.query(async ({ input }) => {
|
.query(async ({ input }) => {
|
||||||
return await getSlotData(input.slotId);
|
// Get slot from cache
|
||||||
|
const slot = await getSlotByIdFromCache(input.slotId);
|
||||||
|
|
||||||
|
if (!slot) {
|
||||||
|
return null; // Slot not found
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter out out-of-stock products and format to match home page display structure
|
||||||
|
const products = slot.products.filter((product) => !product.isOutOfStock);
|
||||||
|
|
||||||
|
return {
|
||||||
|
deliveryTime: slot.deliveryTime,
|
||||||
|
freezeTime: slot.freezeTime,
|
||||||
|
slotId: slot.id,
|
||||||
|
products,
|
||||||
|
};
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -111,7 +111,6 @@ export default function Dashboard() {
|
||||||
const { data: essentialConsts, isLoading: isLoadingConsts, error: constsError } = useGetEssentialConsts();
|
const { data: essentialConsts, isLoading: isLoadingConsts, error: constsError } = useGetEssentialConsts();
|
||||||
|
|
||||||
const { data: tagsData } = trpc.common.product.getDashboardTags.useQuery();
|
const { data: tagsData } = trpc.common.product.getDashboardTags.useQuery();
|
||||||
const { data: cartData, refetch: refetchCart } = useGetCart();
|
|
||||||
const { data: storesData } = trpc.user.stores.getStores.useQuery();
|
const { data: storesData } = trpc.user.stores.getStores.useQuery();
|
||||||
const { data: defaultAddressResponse } =
|
const { data: defaultAddressResponse } =
|
||||||
trpc.user.address.getDefaultAddress.useQuery();
|
trpc.user.address.getDefaultAddress.useQuery();
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue