Commit d64a0615 by Javier

Consumo de Planes

parent be2d2b5b
from decimal import Decimal from decimal import Decimal
from typing import Tuple from typing import Tuple
import typer import typer
from mbilling.functions import MagnusCommandError, SipAccount, active_users, fully_ported_users, get_sip_accounts, get_cdrs, add_balance, get_user from mbilling.functions import MagnusCommandError, SipAccount, active_users, fully_ported_users, get_sip_accounts, get_cdrs, add_balance, get_user, get_plan_consumption
import time import time
import pyodbc import pyodbc
import os import os
...@@ -221,7 +221,7 @@ def update_balance() -> Tuple[int, Decimal]: ...@@ -221,7 +221,7 @@ def update_balance() -> Tuple[int, Decimal]:
return accounts, balance return accounts, balance
def add_cdrs(accounts: list[dict]) -> 'list[dict]': def add_cdrs() -> 'list[dict]':
# Obtención de Parámetros # Obtención de Parámetros
sip_accounts = get_sip_accounts(only_postpaid=True) sip_accounts = get_sip_accounts(only_postpaid=True)
...@@ -230,7 +230,8 @@ def add_cdrs(accounts: list[dict]) -> 'list[dict]': ...@@ -230,7 +230,8 @@ def add_cdrs(accounts: list[dict]) -> 'list[dict]':
# Carga en Memoria de CDRs # Carga en Memoria de CDRs
for account in sip_accounts: for account in sip_accounts:
since = last_update[account.callerid] if account.callerid in last_update.keys() else None since = last_update[account.callerid] if account.callerid in last_update.keys(
) else None
cdrs.extend(get_cdrs(phone_number=account.callerid, since=since)) cdrs.extend(get_cdrs(phone_number=account.callerid, since=since))
# Almacenamiento en Servidor SQL # Almacenamiento en Servidor SQL
...@@ -253,12 +254,29 @@ def add_cdrs(accounts: list[dict]) -> 'list[dict]': ...@@ -253,12 +254,29 @@ def add_cdrs(accounts: list[dict]) -> 'list[dict]':
return cdrs return cdrs
def update_plan_consumption():
with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx:
with cnx.cursor() as cursor:
for account, consumption in get_plan_consumption().items():
cursor.execute(
'UPDATE [bdd_wifi].[dbo].[TB_ServicioFijo] SET ConsumoTarifa=?, LimiteTarifa=? WHERE\
UsuarioEXT=?',
(consumption['consumption'], consumption['max'], account)
)
cursor.execute(
'UPDATE [bdd_wifi].[dbo].[TB_ServicioFijo] SET ConsumoTarifa=NULL, LimiteTarifa=NULL WHERE\
TarifaPlana=0')
cnx.commit()
def process_refills() -> Tuple[int, float]: def process_refills() -> Tuple[int, float]:
"""Ejecuta las Recargas pendientes """Ejecuta las Recargas pendientes
""" """
total_refills = 0 total_refills = 0
amount = 0.0 amount = Decimal('0.0')
# Actualización de Balance en Programa de Facturación # Actualización de Balance en Programa de Facturación
with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx: with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx:
...@@ -273,8 +291,7 @@ def process_refills() -> Tuple[int, float]: ...@@ -273,8 +291,7 @@ def process_refills() -> Tuple[int, float]:
) )
# Procesamiento de Recargas # Procesamiento de Recargas
with typer.progressbar(pending_refills.fetchall(), label="Efectuando Recargas") as refills: for refill in pending_refills.fetchall():
for refill in refills:
try: try:
# Generación de Descripción # Generación de Descripción
if refill[4]: if refill[4]:
...@@ -296,10 +313,8 @@ def process_refills() -> Tuple[int, float]: ...@@ -296,10 +313,8 @@ def process_refills() -> Tuple[int, float]:
pass pass
finally: finally:
cnx.execute( cnx.execute('UPDATE [bdd_wifi].[dbo].[TB_Recargas] SET Procesado=1 WHERE ID=?',
'UPDATE [bdd_wifi].[dbo].[TB_Recargas] SET Procesado=1 WHERE ID=?', (refill[0],))
(refill[0],)
)
cnx.commit() cnx.commit()
return total_refills, amount return total_refills, amount
...@@ -355,7 +370,9 @@ def synchronize(): ...@@ -355,7 +370,9 @@ def synchronize():
msg = '\nActualización Finalizada,\n' msg = '\nActualización Finalizada,\n'
# Sincronización de Cuentas # Sincronización de Cuentas
activate_new_plataform()
sip_accounts, did_accounts = update_sip_accounts() sip_accounts, did_accounts = update_sip_accounts()
perform_migration()
msg += f'\t- Se han actualizado {typer.style(sip_accounts, fg=typer.colors.GREEN, bold=True)} CLIs y ' msg += f'\t- Se han actualizado {typer.style(sip_accounts, fg=typer.colors.GREEN, bold=True)} CLIs y '
msg += f'{typer.style(did_accounts, fg=typer.colors.BRIGHT_YELLOW, bold=True)} DIDs.' msg += f'{typer.style(did_accounts, fg=typer.colors.BRIGHT_YELLOW, bold=True)} DIDs.'
...@@ -366,36 +383,20 @@ def synchronize(): ...@@ -366,36 +383,20 @@ def synchronize():
# Actualización de Estado # Actualización de Estado
accounts, balance = update_balance() accounts, balance = update_balance()
update_plan_consumption()
msg += f"\n\t- Se ha actualizado el saldo de {accounts} cuentas, con un saldo total de {typer.style(f'{round(balance,2)}€', fg=typer.colors.GREEN, bold=True)}€." msg += f"\n\t- Se ha actualizado el saldo de {accounts} cuentas, con un saldo total de {typer.style(f'{round(balance,2)}€', fg=typer.colors.GREEN, bold=True)}€."
# Actualización de CDRs # Actualización de CDRs
accounts = get_last_updated_cdr() new_cdrs = add_cdrs()
cdrs = add_cdrs(accounts) msg += f"\n\t- Se han agregado {len(new_cdrs)} llamadas al CDR."
msg += f"\n\t- Se han sincronizado un total de {typer.style(len(cdrs), fg=typer.colors.GREEN, bold=True)} "
msg += f"llamadas de un total de {typer.style(len(accounts), fg=typer.colors.GREEN, bold=True)} líneas telefónicas."
msg += f'\n\nSincronización Finalizada en {round((datetime.now() - start_time).total_seconds(),2)} segundos.' msg += f'\n\nSincronización Finalizada en {round((datetime.now() - start_time).total_seconds(),2)} segundos.'
typer.echo(msg) typer.echo(msg)
@app.command() @app.command()
def restore():
with pyodbc.connect(SQL_SERVER_CNX_STRING) as cnx:
with cnx.cursor() as cursor:
cursor.execute(
'UPDATE [bdd_wifi].[dbo].[TB_ServicioFijo] SET UsuarioEXT=CuentaA2Billing, NuevaPlataforma=0 WHERE NuevaPlataforma=1'
)
cnx.commit()
@app.command()
def test(): def test():
activate_new_plataform() print(a2billing.account_data('956373434'))
perform_migration()
update_balance()
import_cdr()
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -63,12 +63,12 @@ def _create_user(phone_number: str, password: str, name: str, surname: str, plan ...@@ -63,12 +63,12 @@ def _create_user(phone_number: str, password: str, name: str, surname: str, plan
result = subprocess.check_output( result = subprocess.check_output(
['php', pathlib.Path(mbapi_path, 'create_user.php'), ['php', pathlib.Path(mbapi_path, 'create_user.php'),
phone_number, password, f'\"{name}\"', f'\"{surname}\"', str(plan_id), str(offer_id)] phone_number, password, f'\'{name}\'', f'\'{surname}\'', str(plan_id), str(offer_id)]
) )
if not re.match(succesful, result.decode(encoding='utf-8')): if not re.match(succesful, result.decode(encoding='utf-8')):
exception_cmd = ' '.join(['php', str(pathlib.Path(mbapi_path, 'create_user.php')), exception_cmd = ' '.join(['php', str(pathlib.Path(mbapi_path, 'create_user.php')),
phone_number, password, f'\"{name}\"', f'\"{surname}\"', str(plan_id), str(offer_id)]) phone_number, password, f'\'{name}\'', f'\'{surname}\'', str(plan_id), str(offer_id)])
raise MagnusCommandError( raise MagnusCommandError(
f'Command: {exception_cmd} Exception: {result.decode(encoding="utf-8")}') f'Command: {exception_cmd} Exception: {result.decode(encoding="utf-8")}')
...@@ -189,7 +189,7 @@ def add_balance(phone_number: str, quantity: Decimal, tax: Decimal = Decimal('0. ...@@ -189,7 +189,7 @@ def add_balance(phone_number: str, quantity: Decimal, tax: Decimal = Decimal('0.
result = subprocess.check_output( result = subprocess.check_output(
['php', pathlib.Path(mbapi_path, 'add_balance.php'), ['php', pathlib.Path(mbapi_path, 'add_balance.php'),
phone_number.strip(), str(quantity), f'\"{description}\"'] phone_number.strip(), str(quantity), f'\'{description}\'']
) )
if not re.match(succesful, result.decode('utf-8')): if not re.match(succesful, result.decode('utf-8')):
...@@ -208,7 +208,7 @@ def get_user(phone_number: str) -> dict: ...@@ -208,7 +208,7 @@ def get_user(phone_number: str) -> dict:
with mariadb.connect(**DB_CREDENTIALS) as cnx: with mariadb.connect(**DB_CREDENTIALS) as cnx:
with cnx.cursor() as cursor: with cnx.cursor() as cursor:
headers = ['sip','username', 'password', 'host', 'credit', headers = ['sip', 'username', 'password', 'host', 'credit',
'firstname', 'lastname', 'plan', 'offer', 'firstname', 'lastname', 'plan', 'offer',
'active', 'postpaid'] 'active', 'postpaid']
cursor.execute( cursor.execute(
...@@ -254,6 +254,29 @@ def fully_ported_users() -> 'list[tuple]': ...@@ -254,6 +254,29 @@ def fully_ported_users() -> 'list[tuple]':
return data return data
def get_plan_consumption(*account: str) -> dict:
query = 'SELECT u.username user, ROUND(SUM(c.sessiontime)/60, 0) consumption, o.freetimetocall max FROM mbilling.pkg_user u\
LEFT JOIN mbilling.pkg_cdr c ON u.id=c.id_user\
LEFT JOIN mbilling.pkg_offer o ON u.id_offer=o.id\
WHERE MONTH(c.starttime) >= MONTH(CURRENT_DATE()) AND YEAR(c.starttime)=YEAR(CURRENT_DATE())\
AND sipiax=0 AND u.id_plan IN(4) AND c.sessionbill=0.0 '
if len(account):
query += f' AND u.username IN ({",".join(*account)}) '
query += 'GROUP BY c.id_user'
headers = ('consumption', 'max')
data = {}
with mariadb.connect(**DB_CREDENTIALS) as cnx:
with cnx.cursor() as cursor:
cursor.execute(query)
for account in cursor.fetchall():
data[account[0]] = dict(zip(headers, account[1:]))
return data
def active_users() -> 'list[dict]': def active_users() -> 'list[dict]':
"""Devuelve el listado de los Usuarios Activos """Devuelve el listado de los Usuarios Activos
...@@ -328,7 +351,7 @@ def get_cdrs(phone_number: str, since: datetime = None, upto: datetime = None) - ...@@ -328,7 +351,7 @@ def get_cdrs(phone_number: str, since: datetime = None, upto: datetime = None) -
return cdr return cdr
def get_sip_accounts(only_postpaid : bool = False) -> 'list[SipAccount]': def get_sip_accounts(only_postpaid: bool = False) -> 'list[SipAccount]':
"""Obtiene todas las cuentas SIPs de MagnusBilling """Obtiene todas las cuentas SIPs de MagnusBilling
Returns: Returns:
......
from email import message
def fibonacci(n : int):
if n < 0:
raise ValueError()
a,b = 0,1
for i in range(n+1):
a, b = b, a + b
yield a
class Private:
def __init__(self, msg):
self._message = msg
class SecurePrivate(Private):
def __init__(self, password, msg):
self.password = password
super().__init__(msg)
def get_message(self, password):
if self.password == password:
return self._message
private = SecurePrivate('Hola', 'Mundo')
print(private.get_message('Hola'))
\ No newline at end of file
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