refactor backend and persist stock campaign queue
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m32s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m32s
This commit is contained in:
56
backend/services/stockService.js
Normal file
56
backend/services/stockService.js
Normal file
@@ -0,0 +1,56 @@
|
||||
const { pool } = require('../db');
|
||||
const { normalizeStockPayload } = require('../mappers/stockMapper');
|
||||
const { enqueueStockCampaignItem } = require('./campaignService');
|
||||
|
||||
const CAMPAIGN_DELTA_THRESHOLD = 100;
|
||||
|
||||
const listStock = async () => {
|
||||
const result = await pool.query('SELECT * FROM stock');
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
const upsertStockItems = async (payload) => {
|
||||
const client = await pool.connect();
|
||||
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
const insertQuery = `
|
||||
INSERT INTO stock (produto_id, nome, saldo, delta_estoque)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (produto_id) DO UPDATE SET
|
||||
nome = EXCLUDED.nome,
|
||||
saldo = EXCLUDED.saldo,
|
||||
delta_estoque = EXCLUDED.delta_estoque,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
`;
|
||||
|
||||
for (const rawItem of payload) {
|
||||
const item = normalizeStockPayload(rawItem);
|
||||
if (!item.produtoId) continue;
|
||||
|
||||
await client.query(insertQuery, [
|
||||
item.produtoId,
|
||||
item.nome,
|
||||
item.saldo,
|
||||
item.deltaEstoque
|
||||
]);
|
||||
|
||||
if (item.deltaEstoque >= CAMPAIGN_DELTA_THRESHOLD) {
|
||||
await enqueueStockCampaignItem(client, item);
|
||||
}
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
listStock,
|
||||
upsertStockItems
|
||||
};
|
||||
Reference in New Issue
Block a user