diff --git a/source/app/controllers/main.py b/source/app/controllers/main.py index eab4209..3d95a12 100644 --- a/source/app/controllers/main.py +++ b/source/app/controllers/main.py @@ -16,9 +16,17 @@ class AppEmpresas(object): def on_post(self, req, resp): values = req.params - req.context['result'] = self._db.empresas(values) + req.context['result'] = self._db.empresa_agregar(values) resp.status = falcon.HTTP_200 + def on_delete(self, req, resp): + values = req.params + if self._db.empresa_borrar(values): + resp.status = falcon.HTTP_200 + else: + resp.status = falcon.HTTP_204 + + class AppLogin(object): template = 'login.html' diff --git a/source/app/controllers/util.py b/source/app/controllers/util.py index 2fba46a..64f0fbb 100644 --- a/source/app/controllers/util.py +++ b/source/app/controllers/util.py @@ -1352,6 +1352,35 @@ def get_float(value): return round(float(value), DECIMALES) +def crear_rol(user, contra=''): + if not contra: + contra = user + args = 'psql -U postgres -c "CREATE ROLE {} WITH LOGIN ENCRYPTED ' \ + 'PASSWORD \'{}\';"'.format(user, contra) + try: + result = _call(args) + if result == 'CREATE ROLE\n': + return True + except Exception as e: + log.info(e) + + return False + + +def crear_db(nombre): + args = 'psql -U postgres -c "CREATE DATABASE {0} WITH ' \ + 'OWNER {0};"'.format(nombre) + try: + result = _call(args) + print (result) + if result == 'CREATE DATABASE\n': + return True + except Exception as e: + log.info(e) + + return False + + class ImportFacturaLibre(object): def __init__(self, path, rfc): diff --git a/source/app/models/db.py b/source/app/models/db.py index f7fa23a..6398df5 100644 --- a/source/app/models/db.py +++ b/source/app/models/db.py @@ -11,6 +11,15 @@ class StorageEngine(object): def authenticate(self, args): return main.authenticate(args) + def empresa_agregar(self, values): + return main.empresa_agregar(values['alta_rfc']) + + def empresa_borrar(self, values): + return main.empresa_borrar(values['rfc']) + + def _get_empresas(self, values): + return main.get_empresas() + def get_values(self, table, values=None): return getattr(self, '_get_{}'.format(table))(values) diff --git a/source/app/models/main.py b/source/app/models/main.py index dfc0eee..7dd6033 100644 --- a/source/app/models/main.py +++ b/source/app/models/main.py @@ -3673,6 +3673,57 @@ def _listar_rfc(): log.info(msg) return + +def get_empresas(): + data = util.get_rfcs() + rows = [] + for row in data: + rows.append({'delete': '-', 'rfc': row[0]}) + return tuple(rows) + + +def empresa_agregar(rfc): + rfc = rfc.upper() + if util.get_con(rfc): + msg = 'El RFC ya esta dado de alta' + return {'ok': False, 'msg': msg} + + user = rfc.replace('&', '').lower() + if not util.crear_rol(user): + msg = 'No se pudo crear el usuario, es probable que ya exista' + return {'ok': False, 'msg': msg} + + if not util.crear_db(user): + msg = 'No se pudo crear la base de datos' + return {'ok': False, 'msg': msg} + + args = { + "type": "postgres", + "name": user, + "user": user, + "password": user, + } + if not conectar(args.copy()): + msg = 'No se pudo conectar a la base de datos' + return {'ok': False, 'msg': msg} + + if not _add_emisor(rfc, util.dumps(args)): + msg = 'No se pudo guardar el nuevo emisor' + return {'ok': False, 'msg': msg} + + if not _crear_tablas(rfc): + msg = 'No se pudo crear las tablas' + return {'ok': False, 'msg': msg} + + msg = 'Emisor dado de alta correctamente' + row = {'delete': '-', 'rfc': rfc} + return {'ok': True, 'msg': msg, 'row': row} + + +def empresa_borrar(rfc): + return _delete_emisor(rfc) + + def _importar_valores(archivo='', rfc=''): if not rfc: rfc = input('Introduce el RFC: ').strip().upper() @@ -3767,19 +3818,7 @@ def _importar_facturas(rows): def _importar_categorias(rows): log.info('\tImportando Categorías...') for row in rows: - # ~ if row['padre'] is None: - # ~ filters = ( - # ~ (Categorias.categoria==row['categoria']) & - # ~ (Categorias.padre.is_null(True)) - # ~ ) - # ~ else: - # ~ filters = ( - # ~ (Categorias.categoria==row['categoria']) & - # ~ (Categorias.padre==row['padre']) - # ~ ) with database_proxy.atomic() as txn: - # ~ if Categorias.exists(filters): - # ~ continue try: Categorias.create(**row) except IntegrityError: diff --git a/source/static/js/controller/util.js b/source/static/js/controller/util.js index 713a3bb..8e8c4f1 100644 --- a/source/static/js/controller/util.js +++ b/source/static/js/controller/util.js @@ -176,6 +176,58 @@ function validate_rfc(value){ } +function validar_rfc(value){ + rfc = value.trim().toUpperCase(); + if (rfc == ""){ + msg_error('El RFC no puede estar vacío') + return false + } + + if (rfc.length < 12 || rfc.length > 13){ + msg_error('Longitud incorrecta del RFC') + return false + } + + var length = rfc.length + var start = 4 + if(length==12){ + start = 2 + } + + var part = rfc.slice(0, start); + var re = new RegExp('[a-z&Ñ]{' + start + '}', 'i'); + if (!part.match(re)){ + msg_error('El RFC tiene caractéres inválidos al inicio') + return false + } + part = rfc.slice(-3); + re = new RegExp('[a-z0-9]{3}', 'i'); + if (!part.match(re)){ + msg_error('El RFC tiene caractéres inválidos al final') + return false + } + + part = rfc.slice(-9, -3); + re = new RegExp('[0-9]{6}', 'i'); + if (!part.match(re)){ + msg_error('Fecha inválida') + return false + } + var month = parseInt(part.slice(-4, -2)) + if (month == 0 || month > 12 ){ + msg_error('Fecha inválida') + return false + } + var day = parseInt(part.slice(-2)) + if (day == 0 || day > 31 ){ + msg_error('Fecha inválida') + return false + } + + return true +} + + function validate_email(email){ var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return re.test(email) diff --git a/source/static/js/ui/empresas.js b/source/static/js/ui/empresas.js index 750febc..2991cff 100644 --- a/source/static/js/ui/empresas.js +++ b/source/static/js/ui/empresas.js @@ -9,7 +9,34 @@ var form_controls_empresa = [ ] -var msg_header = 'Bienvenido a Empresa Libre' +var msg_header = 'Bienvenido a Empresa Libre' +var header = [ + {view: 'label', label: 'Alta de Emisor'}, + {}, + {view: 'button', type: 'icon', width: 40, css: 'app_button', + icon: 'home', click: 'window.location = "/"'}, +] + + +var grid_empresas_cols = [ + {id: 'delete', header: '', width: 30, css: 'delete'}, + {id: 'rfc', header: 'RFC Emisor', fillspace: true, + footer: {content: 'rowCount', css: 'right'}}, +] + + +var grid_empresas = { + view: 'datatable', + id: 'grid_empresas', + select: 'row', + url: '/values/empresas', + adjust: true, + autoheight: true, + headermenu: true, + footer: true, + columns: grid_empresas_cols, +} + var ui_empresas = { rows: [ @@ -18,7 +45,7 @@ var ui_empresas = { {maxHeight: 50}, {cols: [{}, {type: 'space', padding: 5, rows: [ - {view: 'template', template: 'Alta de nuevo emisor', type: 'header'}, + {view: 'toolbar', elements: header}, { container: 'form_empresas', view: 'form', @@ -29,6 +56,7 @@ var ui_empresas = { alta_rfc:function(value){ return value.trim() != '';}, } }, + grid_empresas, ]}, {}, ] }, ] diff --git a/source/static/js/ui/login.js b/source/static/js/ui/login.js index e8e9743..3a9a5da 100644 --- a/source/static/js/ui/login.js +++ b/source/static/js/ui/login.js @@ -16,7 +16,7 @@ var form_controls = [ ] -var msg_header = 'Bienvenido a Empresa Libre' +var msg_header = 'Bienvenido a Empresa Libre' var ui_login = { rows: [ @@ -25,7 +25,8 @@ var ui_login = { {maxHeight: 50}, {cols: [{}, {type: 'space', padding: 5, rows: [ - {view: 'template', template: 'Acceso al sistema', type: 'header'}, + {view: 'template', type: 'header', + template: 'Acceso al sistema'}, { container: 'form_login', view: 'form', diff --git a/source/templates/empresas.html b/source/templates/empresas.html index a557531..90aa95f 100644 --- a/source/templates/empresas.html +++ b/source/templates/empresas.html @@ -1,6 +1,7 @@ <%inherit file="base.html"/> <%block name="media"> + @@ -10,29 +11,97 @@