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:
72
backend/db.js
Normal file
72
backend/db.js
Normal file
@@ -0,0 +1,72 @@
|
||||
const { Pool } = require('pg');
|
||||
const { DATABASE_URL } = require('./config');
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: DATABASE_URL
|
||||
});
|
||||
|
||||
const initDB = async () => {
|
||||
try {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id SERIAL PRIMARY KEY,
|
||||
cliente_nome VARCHAR(255),
|
||||
data_pedido VARCHAR(50),
|
||||
valor_pedido NUMERIC(10, 2),
|
||||
produto_id VARCHAR(100),
|
||||
produto_descricao TEXT,
|
||||
quantidade INTEGER,
|
||||
valor_unitario NUMERIC(10, 5),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
await pool.query(`ALTER TABLE orders ADD COLUMN IF NOT EXISTS pedido_id VARCHAR(100);`).catch(() => {});
|
||||
await pool.query(`ALTER TABLE orders ADD COLUMN IF NOT EXISTS cliente_fone VARCHAR(50);`).catch(() => {});
|
||||
|
||||
await pool.query(`CREATE UNIQUE INDEX IF NOT EXISTS unique_order_product ON orders (pedido_id, produto_id);`).catch(err => {
|
||||
console.error('Notice: Could not create unique index (might already exist or there are duplicates):', err.message);
|
||||
});
|
||||
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS stock (
|
||||
produto_id VARCHAR(100) PRIMARY KEY,
|
||||
nome TEXT,
|
||||
saldo INTEGER DEFAULT 0,
|
||||
delta_estoque INTEGER DEFAULT 0,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS stock_campaign_queue (
|
||||
id SERIAL PRIMARY KEY,
|
||||
base_product_name TEXT NOT NULL,
|
||||
produto_id VARCHAR(100) NOT NULL,
|
||||
nome TEXT NOT NULL,
|
||||
saldo INTEGER DEFAULT 0,
|
||||
delta_estoque INTEGER DEFAULT 0,
|
||||
status VARCHAR(20) DEFAULT 'pending',
|
||||
attempts INTEGER DEFAULT 0,
|
||||
last_error TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
sent_at TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_stock_campaign_queue_status ON stock_campaign_queue (status);`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_orders_cliente_fone ON orders (cliente_fone);`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_orders_produto_id ON orders (produto_id);`);
|
||||
|
||||
console.log('Database initialized successfully.');
|
||||
} catch (err) {
|
||||
console.error('Failed to initialize database:', err);
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
pool,
|
||||
initDB
|
||||
};
|
||||
Reference in New Issue
Block a user