forked from elmau/empresa-libre
264 lines
7.3 KiB
Python
264 lines
7.3 KiB
Python
![]() |
#!/usr/bin/env python
|
||
|
|
||
|
import sys
|
||
|
import util
|
||
|
from peewee import *
|
||
|
from conf import DATABASE
|
||
|
from settings import log
|
||
|
|
||
|
|
||
|
database = DATABASE
|
||
|
class BaseModel(Model):
|
||
|
class Meta:
|
||
|
database = database
|
||
|
|
||
|
|
||
|
class Users(BaseModel):
|
||
|
username = CharField(max_length=50, unique=True)
|
||
|
first_name = CharField(max_length=50, default='')
|
||
|
last_name = CharField(max_length=50, default='')
|
||
|
email = CharField(max_length=200, default='')
|
||
|
password = CharField(max_length=100)
|
||
|
is_superuser = BooleanField(default=False)
|
||
|
is_admin = BooleanField(default=False)
|
||
|
is_staff = BooleanField(default=False)
|
||
|
is_active = BooleanField(default=True)
|
||
|
date_joined = DateTimeField(default=util.now)
|
||
|
last_login = DateTimeField(null=True)
|
||
|
|
||
|
def __str__(self):
|
||
|
t = '{} {} ({})'
|
||
|
return t.format(self.first_name, self.last_name, self.username)
|
||
|
|
||
|
class Meta:
|
||
|
order_by = ('username',)
|
||
|
|
||
|
|
||
|
class Clients(BaseModel):
|
||
|
id = IntegerField(db_column='cliente_id', primary_key=True)
|
||
|
cia = CharField(max_length=11, default='', index=True)
|
||
|
rfc = CharField(max_length=13, index=True)
|
||
|
name = CharField(db_column='nombre', max_length=60)
|
||
|
street = CharField(db_column='calle', max_length=60, default='')
|
||
|
num_ext = CharField(db_column='noExterior', max_length=10, default='')
|
||
|
num_int = CharField(db_column='noInterior', max_length=10, default='')
|
||
|
colonia = CharField(max_length=60, default='')
|
||
|
localidad = CharField(max_length=60, default='')
|
||
|
municipio = CharField(max_length=60, default='')
|
||
|
state = CharField(db_column='estado', max_length=40, default='')
|
||
|
country = CharField(db_column='pais', max_length=30, default='')
|
||
|
postal_code = CharField(db_column='codigoPostal', max_length=6, default='')
|
||
|
email = CharField(db_column='correos', max_length=250, default='')
|
||
|
contact = CharField(db_column='nombre_contacto', max_length=60, default='')
|
||
|
phone = CharField(db_column='telefono', max_length=40, default='')
|
||
|
CUS_ErpId = FixedCharField(max_length=20, default='')
|
||
|
CUS_SatClas = FixedCharField(max_length=2, default='')
|
||
|
CUS_SatClasNombre = FixedCharField(max_length=50, default='')
|
||
|
CUS_DefaultCurrency = FixedCharField(max_length=3, default='')
|
||
|
CUS_DefaultCurrencyNombre = FixedCharField(max_length=120, default='')
|
||
|
CUS_AccHabe = FixedCharField(max_length=20, default='')
|
||
|
CUS_AccHabeNombre = FixedCharField(max_length=60, default='')
|
||
|
CUS_AccDebe = FixedCharField(max_length=20, default='')
|
||
|
CUS_AccDebeNombre = FixedCharField(max_length=60, default='')
|
||
|
|
||
|
def __str__(self):
|
||
|
t = '{} ({})'
|
||
|
return t.format(self.name, self.rfc)
|
||
|
|
||
|
class Meta:
|
||
|
db_table = 'clientes'
|
||
|
order_by = ('name',)
|
||
|
|
||
|
|
||
|
class StorageEngine(object):
|
||
|
|
||
|
def __init__(self):
|
||
|
database.connect()
|
||
|
|
||
|
def authenticate(self, username, password):
|
||
|
data = {'login': False, 'msg': 'No Autorizado', 'user': ''}
|
||
|
try:
|
||
|
obj = Users.get(Users.username==username, Users.is_active==True)
|
||
|
except Users.DoesNotExist:
|
||
|
return data
|
||
|
|
||
|
if not util.validate_password(obj.password, password):
|
||
|
return data
|
||
|
|
||
|
obj.last_login = util.now()
|
||
|
obj.save()
|
||
|
data['msg'] = ''
|
||
|
data['login'] = True
|
||
|
data['user'] = str(obj)
|
||
|
return data
|
||
|
|
||
|
def get_partners(self, values):
|
||
|
if values:
|
||
|
id = int(values['id'])
|
||
|
row = Clients.select().where(Clients.id==id).dicts()[0]
|
||
|
return row
|
||
|
else:
|
||
|
rows = Clients.select(
|
||
|
Clients.id, Clients.cia, Clients.rfc, Clients.name).dicts()
|
||
|
return {'ok': True, 'rows': tuple(rows)}
|
||
|
|
||
|
def new_partner(self, values):
|
||
|
fields = util.clean(values)
|
||
|
fields['rfc'] = fields['rfc'].upper()
|
||
|
Clients.create(**fields)
|
||
|
#~ Wend custom ID
|
||
|
obj = Clients.select().order_by(Clients.id.desc()).get()
|
||
|
row = {
|
||
|
'id': obj.id,
|
||
|
'cia': obj.cia,
|
||
|
'rfc': obj.rfc,
|
||
|
'name': obj.name,
|
||
|
}
|
||
|
data = {'ok': True, 'row': row, 'new': True}
|
||
|
return data
|
||
|
|
||
|
def update_partner(self, values):
|
||
|
id = int(values['id'])
|
||
|
del values['id']
|
||
|
fields = util.clean(values)
|
||
|
fields['rfc'] = fields['rfc'].upper()
|
||
|
q = Clients.update(**values).where(Clients.id==id)
|
||
|
q.execute()
|
||
|
row = {
|
||
|
'id': id,
|
||
|
'cia': fields['cia'],
|
||
|
'rfc': fields['rfc'],
|
||
|
'name': fields['name'],
|
||
|
}
|
||
|
data = {'ok': True, 'row': row, 'new': False}
|
||
|
return data
|
||
|
|
||
|
def delete_partner(self, id):
|
||
|
q = Clients.delete().where(Clients.id==id)
|
||
|
return bool(q.execute())
|
||
|
|
||
|
|
||
|
def get_cp(cp):
|
||
|
data = {}
|
||
|
rows = util.get_cp(cp)
|
||
|
if rows:
|
||
|
data = {
|
||
|
'estado': rows[0][2],
|
||
|
'municipio': rows[0][1],
|
||
|
}
|
||
|
if len(rows) == 1:
|
||
|
data['colonia'] = rows[0][0]
|
||
|
else:
|
||
|
data['colonia'] = [r[0] for r in rows]
|
||
|
#~ print ('DATA', data)
|
||
|
return data
|
||
|
|
||
|
|
||
|
def _connect():
|
||
|
global database
|
||
|
log.info('Connect to DB...')
|
||
|
database.connect()
|
||
|
return
|
||
|
|
||
|
|
||
|
def create_tables():
|
||
|
_connect()
|
||
|
tables = [Users, Clients]
|
||
|
database.create_tables(tables, True)
|
||
|
log.info('Create tables OK...')
|
||
|
return
|
||
|
|
||
|
|
||
|
def migrate_tables():
|
||
|
_connect()
|
||
|
log.info('Migrate tables OK...')
|
||
|
return
|
||
|
|
||
|
|
||
|
def create_superuser(username):
|
||
|
_connect()
|
||
|
ok, password = util.get_pass()
|
||
|
if not ok:
|
||
|
log.error(password)
|
||
|
return
|
||
|
try:
|
||
|
obj = Users.create(username=username, password=password, is_superuser=True)
|
||
|
except IntegrityError:
|
||
|
msg = 'El usuario ya existe'
|
||
|
log.error(msg)
|
||
|
return
|
||
|
|
||
|
log.info('Create super user OK...')
|
||
|
return
|
||
|
|
||
|
|
||
|
def change_password(username):
|
||
|
_connect()
|
||
|
try:
|
||
|
obj = Users.get(username=username)
|
||
|
except Users.DoesNotExist:
|
||
|
msg = 'El usuario no existe'
|
||
|
log.error(msg)
|
||
|
return
|
||
|
|
||
|
ok, password = util.get_pass()
|
||
|
if not ok:
|
||
|
log.error(password)
|
||
|
return
|
||
|
|
||
|
obj.password = password
|
||
|
obj.save()
|
||
|
|
||
|
log.info('Change password OK...')
|
||
|
return
|
||
|
|
||
|
|
||
|
def main(opt, username=''):
|
||
|
if opt == '-c':
|
||
|
create_tables()
|
||
|
elif opt == '-m':
|
||
|
migrate_tables()
|
||
|
elif opt == '-su':
|
||
|
create_superuser(username)
|
||
|
elif opt == '-cc':
|
||
|
change_password(username)
|
||
|
return
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
opt = sys.argv
|
||
|
if len(opt) == 1:
|
||
|
msg = 'Agrega un argumento'
|
||
|
log.error(msg)
|
||
|
sys.exit(0)
|
||
|
ov = ('-h', '-c', '-m', '-su', '-cc')
|
||
|
if not opt[1] in ov:
|
||
|
msg = 'Opción no válida. Usa -h para ver las opciones'
|
||
|
log.error(msg)
|
||
|
sys.exit(0)
|
||
|
|
||
|
if opt[1] == '-h':
|
||
|
msg = '-h Muestra esta ayuda.\n\t' \
|
||
|
'-c Crea tablas.\n\t' \
|
||
|
'-m Migra tablas.\n\t' \
|
||
|
'-su USERNAME Crea Super Usuario.\n\t' \
|
||
|
'-cc USERNAME Cambiar contraseña.\n\t'
|
||
|
log.info(msg)
|
||
|
sys.exit(0)
|
||
|
|
||
|
if opt[1] == '-su' or opt[1] == '-cc' :
|
||
|
if len(opt) == 2:
|
||
|
msg = 'Falta el argumento: nombre de usuario'
|
||
|
log.error(msg)
|
||
|
sys.exit(0)
|
||
|
|
||
|
try:
|
||
|
main(opt[1], opt[2])
|
||
|
sys.exit(0)
|
||
|
except KeyboardInterrupt:
|
||
|
msg = 'La contraseña es necesaria'
|
||
|
log.error(msg)
|
||
|
sys.exit(0)
|
||
|
|
||
|
main(opt[1])
|