"""
Flask Admin Interface pentru Import Comenzi Web → ROA
Gestionează mapările SKU în tabelul ARTICOLE_TERTI
"""
from flask import Flask, jsonify, request, render_template_string
from flask_cors import CORS
from dotenv import load_dotenv
import oracledb
import os
import logging
from datetime import datetime
# Configurare environment
load_dotenv()
# Configurare logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s | %(levelname)s | %(message)s',
handlers=[
logging.FileHandler('/app/logs/admin.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Environment Variables pentru Oracle
user = os.environ['ORACLE_USER']
password = os.environ['ORACLE_PASSWORD']
dsn = os.environ['ORACLE_DSN']
app = Flask(__name__)
CORS(app)
def start_pool():
"""Inițializează connection pool Oracle"""
try:
# Configurare Oracle client
instantclient_path = os.environ.get('INSTANTCLIENTPATH')
if instantclient_path:
oracledb.init_oracle_client(lib_dir=instantclient_path)
else:
oracledb.init_oracle_client(config_dir='/app')
pool = oracledb.create_pool(
user=user,
password=password,
dsn=dsn,
min=2,
max=4,
increment=1
)
logger.info(f"Oracle pool creat cu succes pentru {dsn}")
return pool
except Exception as e:
logger.error(f"Eroare creare pool Oracle: {e}")
raise
@app.route('/health')
def health():
"""Health check pentru Docker"""
return jsonify({"status": "ok", "timestamp": datetime.now().isoformat()})
@app.route('/')
def home():
"""Pagina principală admin interface"""
html_template = """
GoMag Admin - Mapări SKU
🛍️ GoMag Admin - Import Comenzi Web → ROA
✅ Container Docker activ pe port 5003
🔄 Verificare conexiune Oracle...
📋 Mapări SKU Active
"""
return render_template_string(html_template)
@app.route('/test-db')
def test_db():
"""Test conexiune Oracle și verificare tabel"""
try:
with pool.acquire() as con:
with con.cursor() as cur:
# Test conexiune de bază
cur.execute("SELECT SYSDATE FROM DUAL")
db_date = cur.fetchone()[0]
# Verificare existență tabel ARTICOLE_TERTI
cur.execute("""
SELECT COUNT(*) FROM USER_TABLES
WHERE TABLE_NAME = 'ARTICOLE_TERTI'
""")
table_exists = cur.fetchone()[0] > 0
if not table_exists:
return jsonify({
"success": False,
"error": "Tabelul ARTICOLE_TERTI nu există. Rulează 01_create_table.sql"
})
# Count records
cur.execute("SELECT COUNT(*) FROM ARTICOLE_TERTI")
record_count = cur.fetchone()[0]
return jsonify({
"success": True,
"message": f"DB Time: {db_date}, Records: {record_count}",
"table_exists": table_exists,
"record_count": record_count
})
except Exception as e:
logger.error(f"Test DB failed: {e}")
return jsonify({"success": False, "error": str(e)})
@app.route('/api/mappings')
def get_mappings():
"""Returnează toate mapările SKU active"""
try:
with pool.acquire() as con:
with con.cursor() as cur:
cur.execute("""
SELECT sku, codmat, cantitate_roa, procent_pret, activ, data_creare
FROM ARTICOLE_TERTI
ORDER BY sku, codmat
""")
mappings = cur.fetchall()
return jsonify({
"success": True,
"mappings": mappings,
"count": len(mappings)
})
except Exception as e:
logger.error(f"Get mappings failed: {e}")
return jsonify({"success": False, "error": str(e)})
# Inițializare pool la startup
try:
pool = start_pool()
logger.info("Admin interface started successfully")
except Exception as e:
logger.error(f"Failed to start admin interface: {e}")
pool = None
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)