Ajuste comentario cache de departamento

This commit is contained in:
JurTI-BR 2025-03-14 13:01:15 -03:00
parent 6c324df9e9
commit 17fd2a5411
1 changed files with 48 additions and 130 deletions

View File

@ -796,159 +796,77 @@ export class OrderService {
}
}
async getOrders(
store: string,
initialDate: any,
finalDate: any,
document: string,
name: string,
sellerId: number,
idOrder: string
): Promise<any[]> {
const initialDateObj = initialDate instanceof Date ? initialDate : new Date(initialDate);
const finalDateObj = finalDate instanceof Date ? finalDate : new Date(finalDate);
const cacheKey =
'getOrders:' +
store +
'_' +
initialDateObj.toISOString() +
'_' +
finalDateObj.toISOString() +
'_' +
document +
'_' +
name +
'_' +
sellerId +
'_' +
idOrder;
const lockKey = 'lock:' + cacheKey;
const lockTimeout = 30; // lock expira em 30 segundos
async getOrders(store: string, initialDate: Date, finalDate: Date,
document: string, name: string, sellerId: number, idOrder: string) {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
let sqlWhere = '';
let sql = '';
try {
const cachedResult = await this.redisClient.get(cacheKey);
if (cachedResult) {
console.log('Retornando resultado do cache (getOrders)');
return JSON.parse(cachedResult);
}
} catch (err) {
console.error('Erro ao acessar o Redis no getOrders:', err?.message || err);
}
const lockValue = Date.now() + lockTimeout * 1000 + 1;
let acquiredLock: string | null = null;
try {
acquiredLock = await this.redisClient.set(lockKey, lockValue, 'NX', 'EX', lockTimeout);
} catch (err) {
console.error('Erro ao adquirir lock no Redis (getOrders):', err?.message || err);
}
if (acquiredLock === 'OK') {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
let sqlWhere = '';
let sql = '';
try {
sql = ` SELECT TO_CHAR(PCPEDC.DATA, 'DD/MM/YYYY') as "createDate",
PCPEDC.NUMPED as "orderId",
PCPEDC.CODFILIAL as "store",
CASE
WHEN PCPEDC.POSICAO = 'B' THEN 'BLOQUEADO'
WHEN PCPEDC.POSICAO = 'P' THEN 'PENDENTE'
WHEN PCPEDC.POSICAO = 'L' THEN 'LIBERADO'
WHEN PCPEDC.POSICAO = 'M' THEN 'MONTADO'
WHEN PCPEDC.POSICAO = 'F' THEN 'FATURADO'
END as "status",
PCPEDC.CODCLI as "customerId",
PCPEDC.CODUSUR as "sellerId",
PCCLIENT.CLIENTE as "customerName",
PCPEDC.VLATEND as "orderValue",
PCPEDC.NUMITENS as "itens",
CASE WHEN ( SELECT COUNT(1) FROM ESTPIX WHERE ESTPIX.NUMPED = PCPEDC.NUMPED ) > 0 THEN 'S' ELSE 'N' END as "pixCreate"
FROM PCPEDC, PCCLIENT
WHERE PCPEDC.CODCLI = PCCLIENT.CODCLI
AND PCPEDC.CONDVENDA IN (1,7)
AND PCPEDC.DTCANCEL IS NULL
AND PCPEDC.POSICAO NOT IN ('C')
AND PCPEDC.ROTINALANC = 'VENDAWEB' `;
if (store && store !== '') {
sqlWhere += ` AND PCPEDC.CODFILIAL = '${store}' `;
sql = ` SELECT TO_CHAR(PCPEDC.DATA, \'DD/MM/YYYY\') as "createDate" ` +
` ,PCPEDC.NUMPED as "orderId" ` +
` ,PCPEDC.CODFILIAL as "store" ` +
` ,CASE WHEN PCPEDC.POSICAO = 'B' THEN 'BLOQUEADO' ` +
` WHEN PCPEDC.POSICAO = 'P' THEN 'PENDENTE' ` +
` WHEN PCPEDC.POSICAO = 'L' THEN 'LIBERADO' ` +
` WHEN PCPEDC.POSICAO = 'M' THEN 'MONTADO' ` +
` WHEN PCPEDC.POSICAO = 'F' THEN 'FATURADO' END as "status" ` +
` ,PCPEDC.CODCLI as "customerId" ` +
` ,PCPEDC.CODUSUR as "sellerId" ` +
` ,PCCLIENT.CLIENTE as "customerName" ` +
` ,PCPEDC.VLATEND as "orderValue" ` +
` ,PCPEDC.NUMITENS as "itens" ` +
` ,CASE WHEN ( SELECT COUNT(1) FROM ESTPIX WHERE ESTPIX.NUMPED = PCPEDC.NUMPED ) > 0 THEN 'S' ELSE 'N' END as "pixCreate" ` +
` FROM PCPEDC, PCCLIENT ` +
` WHERE PCPEDC.CODCLI = PCCLIENT.CODCLI ` +
` AND PCPEDC.CONDVENDA IN (1,7) ` +
` AND PCPEDC.DTCANCEL IS NULL AND PCPEDC.POSICAO NOT IN ('C') `;
` AND PCPEDC.ROTINALANC = 'VENDAWEB' `;
if (store != null && store != '') {
sqlWhere += ` AND PCPEDC.CODFILIAL = '${store}' `;
}
if (document && document !== '') {
sqlWhere += ` AND REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') = REGEXP_REPLACE('${document}', '[^0-9]', '') `;
if (document != null && document != '') {
sqlWhere += ` AND REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') = REGEXP_REPLACE('${document}', '[^0-9]', '')`;
}
if (name && name !== '') {
sqlWhere += ` AND PCCLIENT.CLIENTE LIKE '${name.replace('@', '%')}'||'%' `;
if (name != null && name != '') {
sqlWhere += ` AND PCCLIENT.CLIENTE LIKE '${name.replace('@', '%')}'||'%'`;
}
if (sellerId > 0) {
sqlWhere += ` AND PCPEDC.CODUSUR = ${sellerId} `;
sqlWhere += ` AND PCPEDC.CODUSUR = ${sellerId} `;
}
if (idOrder && idOrder.trim() !== '') {
sqlWhere += ` AND PCPEDC.NUMPED = ${idOrder} `;
if (idOrder.trim() != null && idOrder.trim() != '') {
sqlWhere += ` AND PCPEDC.NUMPED = ${idOrder} `;
}
// Formatação das datas para o SQL
const startDate = initialDateObj;
//tratamento de data//
const startDate = new Date(initialDate);
let day = startDate.getDate();
let month = ("00" + (startDate.getMonth() + 1)).slice(-2);
let year = startDate.getFullYear();
const startFormat = day + "/" + month + "/" + year;
const endDate = finalDateObj;
const endDate = new Date(finalDate);
day = endDate.getDate();
month = ("00" + (endDate.getMonth() + 1)).slice(-2);
year = endDate.getFullYear();
const endFormat = day + "/" + month + "/" + year;
sqlWhere += ` AND PCPEDC.DATA BETWEEN TO_DATE('${startFormat}', 'DD/MM/YYYY') AND TO_DATE('${endFormat}', 'DD/MM/YYYY') `;
sqlWhere += ` AND PCPEDC.DATA BETWEEN TO_DATE('${startFormat}', 'DD/MM/YYYY') AND TO_DATE('${endFormat}', 'DD/MM/YYYY') `;
const result = await queryRunner.query(sql + sqlWhere);
// Armazena o resultado no cache com TTL de 1 hora (3600 segundos)
try {
await this.redisClient.set(cacheKey, JSON.stringify(result), 'EX', 3600);
} catch (cacheSetErr) {
console.error('Erro ao salvar o resultado no cache (getOrders):', cacheSetErr?.message || cacheSetErr);
}
return result;
} catch (error) {
console.error('Erro ao executar a query no getOrders:', error?.message || error);
} catch (error) {
console.log(error);
throw error;
} finally {
} finally {
await queryRunner.release();
await connection.close();
// Libera o lock, somente se o valor armazenado for o mesmo deste processo
try {
const currentLockValue = await this.redisClient.get(lockKey);
if (currentLockValue === lockValue.toString()) {
await this.redisClient.del(lockKey);
}
} catch (lockErr) {
console.error('Erro ao liberar o lock do Redis (getOrders):', lockErr?.message || lockErr);
}
}
} else {
// Se não conseguir adquirir o lock, aguarda 1 segundo e tenta novamente
console.log('Lock não adquirido (getOrders), aguardando e tentando novamente...');
await this.sleep(1000);
return this.getOrders(store, initialDate, finalDate, document, name, sellerId, idOrder);
}
}
// Função auxiliar para aguardar um período determinado (em milissegundos)
private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
async getItensOrder(idOrder: number) {