Commit caf4ba71 by Javier

Recargas

parent 7906dc3f
from typing import Tuple from typing import Tuple
import typer import typer
from mbilling.functions import active_users, fully_ported_clis, get_cdrs from mbilling.functions import MagnusCommandError, active_users, fully_ported_clis, get_cdrs, add_balance
import time import time
import pyodbc import pyodbc
import os import os
...@@ -135,7 +135,8 @@ def update_balance(target_clis: list[str]) -> Tuple[int, int]: ...@@ -135,7 +135,8 @@ def update_balance(target_clis: list[str]) -> Tuple[int, int]:
# Cálculo de Parámetros # Cálculo de Parámetros
flat_rate = sip_account['offer'] if sip_account['plan'] == TARIFA_PLANA_ID else None flat_rate = sip_account['offer'] if sip_account['plan'] == TARIFA_PLANA_ID else None
credit = 999.00 if sip_account['credit'] <= 0 and sip_account['postpaid'] == True else round(sip_account['credit'],2) credit = 999.00 if sip_account['credit'] <= 0 and sip_account['postpaid'] == True else round(
sip_account['credit'], 2)
# Si la cuenta es emisora de llamadas, añadimos ClaveEXT # Si la cuenta es emisora de llamadas, añadimos ClaveEXT
if sip_account['credit'] > 0: if sip_account['credit'] > 0:
...@@ -145,7 +146,7 @@ def update_balance(target_clis: list[str]) -> Tuple[int, int]: ...@@ -145,7 +146,7 @@ def update_balance(target_clis: list[str]) -> Tuple[int, int]:
ClaveEXT=? WHERE DDI=? AND FechaBaja is NULL""", ClaveEXT=? WHERE DDI=? AND FechaBaja is NULL""",
(credit, sip_account['active'], (credit, sip_account['active'],
flat_rate, sip_account['postpaid'], sip_account['plan'], sip_account['username'], flat_rate, sip_account['postpaid'], sip_account['plan'], sip_account['username'],
sip_account['password'], sip_account['username']) sip_account['password'], sip_account['username'])
) )
else: else:
...@@ -162,21 +163,19 @@ def update_balance(target_clis: list[str]) -> Tuple[int, int]: ...@@ -162,21 +163,19 @@ def update_balance(target_clis: list[str]) -> Tuple[int, int]:
else: else:
non_updated = non_updated + 1 non_updated = non_updated + 1
return updated, non_updated return updated, non_updated
def add_cdrs(accounts: list[dict]) -> 'list[dict]': def add_cdrs(accounts: list[dict]) -> 'list[dict]':
cdrs = [] cdrs = []
with typer.progressbar(accounts.keys(), label="Descargando CDRs") as account_data: for account in (accounts.keys()):
for account in account_data: cdrs.extend(get_cdrs(phone_number=account,since=accounts[account]))
cdrs.extend(get_cdrs(phone_number=account,
since=accounts[account]))
with typer.progressbar(cdrs, label='Sincronizando CDRs') as cdr_data: with typer.progressbar(cdrs, label='Sincronizando CDRs') as cdr_data:
with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx: with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx:
with cnx.cursor() as cursor: with cnx.cursor() as cursor:
for cdr in cdr_data: for cdr in cdr_data:
cursor.execute( cursor.execute(
'INSERT INTO bdd_wifi.dbo.TB_OMV_CDR_Cliente (Tipo, DDi, Fecha, \ 'INSERT INTO bdd_wifi.dbo.TB_OMV_CDR_Cliente (Tipo, DDi, Fecha, \
...@@ -191,6 +190,57 @@ def add_cdrs(accounts: list[dict]) -> 'list[dict]': ...@@ -191,6 +190,57 @@ def add_cdrs(accounts: list[dict]) -> 'list[dict]':
cnx.commit() cnx.commit()
return cdrs return cdrs
def process_refills() -> Tuple[int,float]:
"""Ejecuta las Recargas pendientes
"""
total_refills = 0
amount = 0.0
# Actualización de Balance en Programa de Facturación
with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx:
with cnx.cursor() as cursor:
# Obtención de Recargas Pendientes
pending_refills = cnx.execute(
'SELECT r.ID, f.DDI, r.Importe, r.Automatica \
FROM [bdd_wifi].[dbo].[TB_Recargas] r \
INNER JOIN [bdd_wifi].[dbo].[TB_ServicioFijo] f ON f.UsuarioEXT=r.Cuenta \
WHERE Procesado=0'
)
# Procesamiento de Recargas
with typer.progressbar(pending_refills.fetchall(), label="Efectuando Recargas") as refills:
for refill in refills:
try:
# Generación de Descripción
description = 'Recarga Automática ID ' if refill[3] else 'Recarga Manual ID '
description = description + str(refill[0])
# Insercción de Balance
add_balance(
phone_number=refill[1],
quantity=refill[2],
description=description
)
total_refills = total_refills + 1
amount = amount + refill[2]
except MagnusCommandError:
# Número no registrado en Magnus
pass
finally:
cnx.execute(
'UPDATE [bdd_wifi].[dbo].[TB_Recargas] SET Procesado=1 WHERE ID=?',
(refill[0],)
)
cnx.commit()
return total_refills, amount
# Definición de Comandos # Definición de Comandos
...@@ -258,6 +308,8 @@ def import_cdr(account: str = typer.Argument(None), only_charged: bool = typer.A ...@@ -258,6 +308,8 @@ def import_cdr(account: str = typer.Argument(None), only_charged: bool = typer.A
@app.command() @app.command()
def synchronize(): def synchronize():
"""Sincroniza el Servidor de Telefonía con el de Facturación
"""
start_time = datetime.now() start_time = datetime.now()
# Verificación de SIP en Nueva Plataforma # Verificación de SIP en Nueva Plataforma
...@@ -271,6 +323,14 @@ def synchronize(): ...@@ -271,6 +323,14 @@ def synchronize():
msg = msg + f" de un total de {updated + non_updated} líneas." msg = msg + f" de un total de {updated + non_updated} líneas."
typer.echo(msg) typer.echo(msg)
# Recargas
total_refills, amount = process_refills()
msg = f"Se han procesado "
msg = msg + typer.style(total_refills, fg=typer.colors.GREEN, bold=True)
msg = msg + " recargas con un importe total de "
msg = msg + typer.style(f'{amount}€', fg=typer.colors.GREEN, bold=True)
typer.echo(msg)
# Actualización de CDRs # Actualización de CDRs
accounts = get_last_updated_cdr() accounts = get_last_updated_cdr()
cdrs = add_cdrs(accounts) cdrs = add_cdrs(accounts)
...@@ -281,7 +341,8 @@ def synchronize(): ...@@ -281,7 +341,8 @@ def synchronize():
msg = msg + " líneas telefónicas." msg = msg + " líneas telefónicas."
typer.echo(msg) typer.echo(msg)
typer.echo(f'Sincronización Finalizada en {round((datetime.now() - start_time).total_seconds(),2)} segundos.') typer.echo(
f'Sincronización Finalizada en {round((datetime.now() - start_time).total_seconds(),2)} segundos.')
if __name__ == "__main__": if __name__ == "__main__":
......
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