96 lines
2.5 KiB
JavaScript
96 lines
2.5 KiB
JavaScript
const { Pool } = require('pg');
|
|
|
|
const UPSERT_ORDER_SQL = `
|
|
INSERT INTO production_orders (
|
|
tiny_id,
|
|
number,
|
|
status,
|
|
order_reference,
|
|
issue_date,
|
|
expected_date,
|
|
product_sku,
|
|
product_description,
|
|
quantity,
|
|
unit,
|
|
integration_status,
|
|
tiny_payload,
|
|
updated_at
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5::date, $6::date, $7, $8, $9, $10, $11, $12::jsonb, CURRENT_TIMESTAMP)
|
|
ON CONFLICT (tiny_id) DO UPDATE SET
|
|
number = EXCLUDED.number,
|
|
status = EXCLUDED.status,
|
|
order_reference = EXCLUDED.order_reference,
|
|
issue_date = EXCLUDED.issue_date,
|
|
expected_date = EXCLUDED.expected_date,
|
|
product_sku = EXCLUDED.product_sku,
|
|
product_description = EXCLUDED.product_description,
|
|
quantity = EXCLUDED.quantity,
|
|
unit = EXCLUDED.unit,
|
|
integration_status = EXCLUDED.integration_status,
|
|
tiny_payload = EXCLUDED.tiny_payload,
|
|
updated_at = CURRENT_TIMESTAMP
|
|
RETURNING id;
|
|
`;
|
|
|
|
class ProductionOrderRepository {
|
|
constructor(databaseUrl) {
|
|
this.pool = new Pool({ connectionString: databaseUrl });
|
|
}
|
|
|
|
async connect() {
|
|
await this.pool.query(`SET TIME ZONE 'America/Sao_Paulo';`);
|
|
}
|
|
|
|
async close() {
|
|
await this.pool.end();
|
|
}
|
|
|
|
async upsertOrder(order, markers) {
|
|
const client = await this.pool.connect();
|
|
try {
|
|
await client.query('BEGIN');
|
|
const result = await client.query(UPSERT_ORDER_SQL, [
|
|
order.tinyId,
|
|
order.number,
|
|
order.status,
|
|
order.orderReference,
|
|
order.issueDate,
|
|
order.expectedDate,
|
|
order.productSku,
|
|
order.productDescription,
|
|
order.quantity,
|
|
order.unit,
|
|
order.integrationStatus,
|
|
JSON.stringify(order.tinyPayload)
|
|
]);
|
|
|
|
const productionOrderId = result.rows[0].id;
|
|
await client.query('DELETE FROM production_order_markers WHERE production_order_id = $1', [productionOrderId]);
|
|
|
|
for (const marker of markers) {
|
|
await client.query(
|
|
`
|
|
INSERT INTO production_order_markers (production_order_id, label, color)
|
|
VALUES ($1, $2, $3)
|
|
ON CONFLICT (production_order_id, label) DO UPDATE SET color = EXCLUDED.color;
|
|
`,
|
|
[productionOrderId, marker.label, marker.color || null]
|
|
);
|
|
}
|
|
|
|
await client.query('COMMIT');
|
|
return productionOrderId;
|
|
} catch (error) {
|
|
await client.query('ROLLBACK');
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
ProductionOrderRepository
|
|
};
|