Улучшена логика кеширования WB данных
- Удалена привязка к конкретной дате при поиске кеша - Теперь используется самый свежий кеш для организации независимо от даты - Это решает проблему с пустыми данными при переходе между днями 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@ -8177,15 +8177,10 @@ const wbWarehouseCacheQueries = {
|
|||||||
throw new GraphQLError('Организация не найдена')
|
throw new GraphQLError('Организация не найдена')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Получаем текущую дату без времени
|
// Ищем самый свежий кеш для организации (не привязываемся к дате)
|
||||||
const today = new Date()
|
|
||||||
today.setHours(0, 0, 0, 0)
|
|
||||||
|
|
||||||
// Ищем кеш за сегодня
|
|
||||||
const cache = await prisma.wBWarehouseCache.findFirst({
|
const cache = await prisma.wBWarehouseCache.findFirst({
|
||||||
where: {
|
where: {
|
||||||
organizationId: user.organization.id,
|
organizationId: user.organization.id,
|
||||||
cacheDate: today,
|
|
||||||
},
|
},
|
||||||
orderBy: {
|
orderBy: {
|
||||||
createdAt: 'desc',
|
createdAt: 'desc',
|
||||||
@ -8193,17 +8188,34 @@ const wbWarehouseCacheQueries = {
|
|||||||
})
|
})
|
||||||
|
|
||||||
if (cache) {
|
if (cache) {
|
||||||
// Возвращаем данные из кеша
|
// Проверяем, не устарел ли кеш (обновляем каждые 2 часа для более актуальных данных)
|
||||||
return {
|
const now = new Date()
|
||||||
success: true,
|
const cacheAge = now.getTime() - cache.updatedAt.getTime()
|
||||||
message: 'Данные получены из кеша',
|
const maxCacheAge = 2 * 60 * 60 * 1000 // 2 часа в миллисекундах
|
||||||
cache: {
|
const ageInMinutes = Math.floor(cacheAge / 60000)
|
||||||
...cache,
|
|
||||||
cacheDate: cache.cacheDate.toISOString().split('T')[0],
|
if (cacheAge < maxCacheAge) {
|
||||||
createdAt: cache.createdAt.toISOString(),
|
// Кеш еще актуален
|
||||||
updatedAt: cache.updatedAt.toISOString(),
|
return {
|
||||||
},
|
success: true,
|
||||||
fromCache: true,
|
message: `Данные получены из кеша (обновлено ${ageInMinutes} мин назад)`,
|
||||||
|
cache: {
|
||||||
|
...cache,
|
||||||
|
cacheDate: cache.cacheDate.toISOString().split('T')[0],
|
||||||
|
createdAt: cache.createdAt.toISOString(),
|
||||||
|
updatedAt: cache.updatedAt.toISOString(),
|
||||||
|
},
|
||||||
|
fromCache: true,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Кеш устарел, нужно обновить
|
||||||
|
console.warn(`WB Warehouse Cache: Cache expired (${ageInMinutes} minutes old, max age: ${maxCacheAge / 60000} minutes)`)
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'Кеш устарел, требуется загрузка из API',
|
||||||
|
cache: null,
|
||||||
|
fromCache: false,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Кеша нет, нужно загрузить данные из API
|
// Кеша нет, нужно загрузить данные из API
|
||||||
@ -8257,11 +8269,23 @@ const wbWarehouseCacheMutations = {
|
|||||||
throw new GraphQLError('Организация не найдена')
|
throw new GraphQLError('Организация не найдена')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Получаем текущую дату без времени
|
// Получаем текущую дату без времени для cacheDate
|
||||||
const today = new Date()
|
const today = new Date()
|
||||||
today.setHours(0, 0, 0, 0)
|
today.setHours(0, 0, 0, 0)
|
||||||
|
|
||||||
// Используем upsert для создания или обновления кеша
|
// Сначала удаляем старые записи кеша (старше 7 дней) для этой организации
|
||||||
|
const weekAgo = new Date()
|
||||||
|
weekAgo.setDate(weekAgo.getDate() - 7)
|
||||||
|
await prisma.wBWarehouseCache.deleteMany({
|
||||||
|
where: {
|
||||||
|
organizationId: user.organization.id,
|
||||||
|
createdAt: {
|
||||||
|
lt: weekAgo,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Используем upsert для создания или обновления кеша (обновляем createdAt чтобы отразить время последнего обновления)
|
||||||
const cache = await prisma.wBWarehouseCache.upsert({
|
const cache = await prisma.wBWarehouseCache.upsert({
|
||||||
where: {
|
where: {
|
||||||
organizationId_cacheDate: {
|
organizationId_cacheDate: {
|
||||||
@ -8274,6 +8298,7 @@ const wbWarehouseCacheMutations = {
|
|||||||
totalProducts: input.totalProducts,
|
totalProducts: input.totalProducts,
|
||||||
totalStocks: input.totalStocks,
|
totalStocks: input.totalStocks,
|
||||||
totalReserved: input.totalReserved,
|
totalReserved: input.totalReserved,
|
||||||
|
// Обновляем updatedAt автоматически, createdAt остается прежним
|
||||||
},
|
},
|
||||||
create: {
|
create: {
|
||||||
organizationId: user.organization.id,
|
organizationId: user.organization.id,
|
||||||
|
Reference in New Issue
Block a user