Commit 4c381dd1 by Javier

Sincronización de Sistemas con CLI

parent 55093fd7
......@@ -9,7 +9,7 @@
"type": "python",
"request": "launch",
"program": "cli.py",
"args": ["synchronize"],
"args": ["update-plataform", "update-account","import-cdr"],
"console": "integratedTerminal",
"justMyCode": true
},
......
from http.client import CannotSendRequest
from typing import Tuple
import typer
from mbilling.functions import active_users, fully_ported_clis, get_cdrs
import time
import pyodbc
import os
from datetime import timedelta
from datetime import timedelta, datetime
# Credenciales SQL Server
sql_server_hostname = "192.168.2.200"
sql_server_database = "bdd_wifi"
......@@ -23,7 +23,7 @@ SQL_SERVER_CNX_STRING = "DRIVER={driver};SERVER={server};\
TARIFA_PLANA_ID = 4
# Inicialización del CLI
app = typer.Typer()
app = typer.Typer(chain=True)
# Funciones Auxiliares
......@@ -112,30 +112,17 @@ def get_last_updated_cdr(account: str = None, only_post_payment: bool = True) ->
)
last_updated = cursor.fetchone()
cdr_last_updated[ddi[0]] = last_updated[0] if last_updated else None
cdr_last_updated[ddi[0]
] = last_updated[0] if last_updated else None
return cdr_last_updated
# Definición de Comandos
@app.command()
def update_plataform():
"""Actualiza las CLIs agregados a la Nueva Plataforma
def update_balance(target_clis: list[str]) -> Tuple[int, int]:
"""Actualiza el Saldo de las Cuentas SIP
"""
typer.echo('Actualizando Líneas en Nueva Plataforma.')
new_plataform_activate(*fully_ported_clis())
typer.echo('Actualización finalizada.')
@app.command()
def update_account(account: str = typer.Argument(None)):
# Obtiene los números completamente portados.
target_clis = update_target_clis() if not account else account
# Líneas Actualizadas
# Cuentas Actualizadas
updated = 0
non_updated = 0
......@@ -158,11 +145,68 @@ def update_account(account: str = typer.Argument(None)):
else:
non_updated = non_updated + 1
msg = f"De un total de {updated + non_updated} líneas, "
return updated, non_updated
def add_cdrs(accounts: list[dict]) -> 'list[dict]':
cdrs = []
with typer.progressbar(accounts.keys(), label="Descargando CDRs") as account_data:
for account in account_data:
cdrs.extend(get_cdrs(phone_number=account,
since=accounts[account]))
with typer.progressbar(cdrs, label='Sincronizando CDRs') as cdr_data:
with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx:
with cnx.cursor() as cursor:
for cdr in cdr_data:
cursor.execute(
'INSERT INTO bdd_wifi.dbo.TB_OMV_CDR_Cliente (Tipo, DDi, Fecha, \
Destino, DesDestino, DuracionSegundos, DuracionFormato, Pvc, Pvp, Fuente) \
VALUES(?,?,?,?,?,?,?,?,?,?)',
('VOZ', cdr['callerid'], cdr['timestamp'], cdr['destination'], cdr['description'],
cdr['duration'], str(
timedelta(seconds=cdr['duration'])), cdr['cost'], cdr['price'],
'Magnus')
)
cnx.commit()
return cdrs
# Definición de Comandos
@app.command()
def update_plataform():
"""Actualiza las CLIs agregados a la Nueva Plataforma
"""
typer.echo('Actualizando Líneas en Nueva Plataforma.')
new_plataform_activate(*fully_ported_clis())
typer.echo('Actualización finalizada.')
@app.command()
def update_account(account: str = typer.Argument(default=None, )):
"""Actualiza las cuentas SIP
Sincroniza de MagnusBilling en el programa de facturación.
Args:
account (str, optional): Cuenta Objetivo, por defecto todas. Defaults to typer.Argument(default=None, ).
"""
# Obtiene los números completamente portados.
target_clis = update_target_clis() if not account else [account]
# Líneas Actualizadas
updated = 0
non_updated = 0
updated, non_updated = update_balance(target_clis)
msg = "Se han actualizado "
msg = msg + typer.style(updated, fg=typer.colors.GREEN, bold=True)
msg = msg + " han sido actualizadas correctamente, "
msg = msg + typer.style(non_updated, fg=typer.colors.RED, bold=True)
msg = msg + " no han sido actualizadas por estar activas en A2Billing."
msg = msg + f" de un total de {updated + non_updated} líneas."
typer.echo(msg)
......@@ -181,28 +225,36 @@ def import_cdr(account: str = typer.Argument(None), only_charged: bool = typer.A
"""
typer.echo('Obteniendo Líneas a Sincronizar')
accounts = get_last_updated_cdr()
cdrs = []
with typer.progressbar(accounts.keys(), label="Descargando CDRs") as account_data:
for account in account_data:
cdrs.extend(get_cdrs(phone_number=account, since=accounts[account]))
accounts = get_last_updated_cdr() if not account else [account]
cdrs = add_cdrs(accounts)
with typer.progressbar(cdrs, label='Sincronizando CDRs') as cdr_data:
with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx:
with cnx.cursor() as cursor:
for cdr in cdr_data:
cursor.execute(
'INSERT INTO bdd_wifi.dbo.TB_OMV_CDR_Cliente (Tipo, DDi, Fecha, \
Destino, DesDestino, DuracionSegundos, DuracionFormato, Pvc, Pvp, Fuente) \
VALUES(?,?,?,?,?,?,?,?,?,?)',
('VOZ', cdr['callerid'], cdr['timestamp'], cdr['destination'], cdr['description'],
cdr['duration'], str(timedelta(seconds=cdr['duration'])), cdr['cost'], cdr['price'],
'Magnus')
)
msg = f"Se han sincronizado un total de "
msg = msg + typer.style(len(cdrs), fg=typer.colors.GREEN, bold=True)
msg = msg + " llamadas de un total de "
msg = msg + typer.style(len(accounts), fg=typer.colors.GREEN, bold=True)
msg = msg + " líneas telefónicas."
typer.echo(msg)
cnx.commit()
@app.command()
def syncrhonize():
start_time = datetime.now()
# Verificación de SIP en Nueva Plataforma
new_plataform_activate(*fully_ported_clis())
typer.echo('Verificación de Plataformas Finalizada')
# Actualización de Estado
updated, non_updated = update_balance(update_target_clis())
msg = "Se han actualizado "
msg = msg + typer.style(updated, fg=typer.colors.GREEN, bold=True)
msg = msg + f" de un total de {updated + non_updated} líneas."
typer.echo(msg)
# Actualización de CDRs
accounts = get_last_updated_cdr()
cdrs = add_cdrs(accounts)
msg = f"Se han sincronizado un total de "
msg = msg + typer.style(len(cdrs), fg=typer.colors.GREEN, bold=True)
msg = msg + " llamadas de un total de "
......@@ -210,12 +262,8 @@ def import_cdr(account: str = typer.Argument(None), only_charged: bool = typer.A
msg = msg + " líneas telefónicas."
typer.echo(msg)
typer.echo(f'Sincronización Finalizada en {round((datetime.now() - start_time).total_seconds(),2)} segundos.')
@app.command()
def synchronize():
update_plataform()
update_account()
import_cdr()
if __name__ == "__main__":
app()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment