All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m32s
57 lines
1.5 KiB
JavaScript
57 lines
1.5 KiB
JavaScript
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
|
|
};
|