Example #1
0
class UserNote(Base,Record):

    __tablename__ = 'usernote'
    id = Column(Integer, primary_key=True)
    UserId = Column(Integer, ForeignKey(User.id), nullable=False)
    ProfId = Column(Integer, ForeignKey(User.id), nullable=False)
    CompanyId = Column(Integer, ForeignKey(Company.id))
    TransDate = Column(DateTime)
    Note = Column(MediumText())

    @classmethod
    def fieldsDefinition(cls):
        res = Record.fieldsDefinition()
        res['id'] = {'Type': 'integer','Hidde': True}
        res['UserId'] = {'Type': 'integer','Hidde': True}
        res['ProfId'] = {'Type': 'integer', 'Hidde': True}
        res['CompanyId'] = {'Type': 'text', 'Hidde': True}
        res['TransDate'] = {'Type': 'datetime', 'Hidde': True}
        res['Note'] = {'Type': 'text', 'Label': 'Nota','Input':'textarea','rows':'4','cols':'50'}
        return res

    @classmethod
    def getRecordList(cls,TableClass,custId=None,limit=None,order_by=None,desc=None):
        session = Session()
        if current_user.UserType==3:
            records = session.query(cls).filter_by(UserId=current_user.id)\
                .join(User,User.id==cls.ProfId)\
                .with_entities(User.Name,cls.TransDate,cls.Note)\
                .order_by(UserNote.TransDate.desc())
        elif current_user.UserType in (0,1):
            records = session.query(cls).filter_by(CompanyId=current_user.CompanyId,UserId=custId)\
                .join(User,User.id==cls.ProfId)\
                .with_entities(User.Name,cls.TransDate,cls.Note)\
                .order_by(UserNote.TransDate.desc())
        elif current_user.UserType==2:
            records = session.query(cls).filter_by(CompanyId=current_user.CompanyId,UserId=custId,ProfId=current_user.id)\
                .join(User,User.id==cls.ProfId)\
                .with_entities(User.Name,cls.TransDate,cls.Note)\
                .order_by(UserNote.TransDate.desc())
        session.close()
        return records

    @classmethod
    def getUserFieldsReadOnly(cls,record,fieldname):
        if current_user.UserType in (1,2):
            if fieldname in ('ProfId','TransDate','CompanyId'):
                return 2 #solo insertar nuevos

    def defaults(self):
        self.TransDate = now()
        self.ProfId = current_user.id
        self.CompanyId = current_user.CompanyId

    @classmethod
    def canUserDelete(self):
        return False
Example #2
0
class Company(Base, Record):
    __tablename__ = 'company'
    id = Column(Integer, primary_key=True)
    Active = Column(Integer)
    Name = Column(String(40))
    Phone = Column(String(40))
    Email = Column(String(40))
    WebSite = Column(String(40))
    Comment = Column(MediumText())
    City = Column(String(100))
    Address = Column(String(100))
    ImageProfile = Column(String(100))
    OnlinePayment = Column(Integer)
    KeyPayco = Column(String(50))
    Closed = Column(Integer)

    def defaults(self):
        self.Closed = 0

    def check(self):
        if not self.Name: return Error("Debe Completar el Nombre")
        return True

    @classmethod
    def canUserDelete(self):
        if current_user.UserType == 0:
            return True
        else:
            return False

    @classmethod
    def getRecordTitle(self):
        return ['Name']

    @classmethod
    def canUserEdit(cls, record):
        if current_user.UserType == 3:
            return False
        return True

    @classmethod
    def getUserFieldsReadOnly(cls, record, fieldname):
        if current_user.UserType == 3:
            return 2
        return 0
class Notification(Base,Record):

    __tablename__ = 'notification'
    id = Column(Integer, primary_key=True)
    UserId = Column(Integer, ForeignKey(User.id), nullable=True)
    Status = Column(Integer)
    Comment = Column(String(255))
    Action = Column(String(255))
    TransDate = Column(DateTime)
    Description = Column(MediumText())

    def __init__(self):
        super(self.__class__,self).__init__()
        #super().__init__()

    def defaults(self):
        self.TransDate = now()
        self.Status = 0

    @classmethod
    def canUserCreate(self):
        return False

    @classmethod
    def canUserDelete(cls):
        return False

    @classmethod
    def getRecordList(cls,TableClass,limit=None,order_by=None,desc=None):
        session = Session()
        records = session.query(cls).filter_by(UserId=current_user.id).order_by(Notification.TransDate.desc())
        session.close()
        return records

    def afterSaveJS(self):
        return 'getNotifications()'

    @classmethod
    def getLinksTo(cls,record_list):
        res = {'Status': {}}
        res['Status'][0] = ['No Leída',0]
        res['Status'][1] = ['Leída',0]
        return res
Example #4
0
class User(Base,Record,UserMixin):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True,autoincrement=True)
    Email = Column(String(50))
    Password = Column(String(20))
    Active = Column(Boolean)
    UserType = Column(Integer)
    CompanyId = Column(Integer, ForeignKey(Company.id))
    Name = Column(String(40))
    Title = Column(String(40))
    FindMe = Column(Boolean)
    EditSchedule = Column(Integer)
    FixedSchedule = Column(Boolean)
    MinTime = Column(Integer)
    MaxTime = Column(Integer)
    ShowDays = Column(Integer)
    Phone = Column(String(40))
    Comment = Column(MediumText())
    City = Column(String(100))
    Address = Column(String(100))
    ImageProfile = Column(String(100))
    NtfActivityCancel = Column(Boolean)
    NtfActivityNew = Column(Boolean)
    NtfActivityChange = Column(Boolean)
    NtfActivityReminder = Column(Boolean)
    NtfReminderDays = Column(Integer)
    NtfReminderHours = Column(Integer)
    ShowFromDays = Column(Integer)
    NtfActivityConfirm = Column(Boolean)
    NtfActivityNewCust = Column(Boolean)
    Closed = Column(Boolean)
    CreatedDate = Column(Date)

    Schedules = relationship('UserSchedule', cascade="all, delete-orphan")

    #def __repr__(self):
    #    return "<User(Active='%s', AcessGroup='%s', Password='******')>" % (self.Active, self.AcessGroup, self.Password)

    SUPER = 0
    ADMIN = 1
    PROF = 2
    CUST = 3

    def filterFields(self,fields):
        #filtro de campo por tipo de usuario
        filters = {3:['Title','FindMe','FixedSchedule','MinTime','MaxTime','EditSchedule','Schedules','ShowDays','ShowFromDays','Comment']}
        if self.UserType in filters:
            filters = filters[self.UserType]
            for fn in filters:
                if fn in fields:
                    del fields[fn]
        if (current_user.id==self.id) and (self.EditSchedule):
            del fields['Schedules']
        if self.id and current_user.UserType!=0:
            del fields['Password']

    @classmethod
    def getUserFromDataBase(cls,id):
        user = cls.getRecordById(id)
        if user:
            return user

    @classmethod
    def getUserIdByEmail(cls,email):
        session = Session()
        record = session.query(cls).filter_by(Email=email).first()
        if not record:
            return
        id = record.id
        session.close()
        return id

    def defaults(self):
        self.syncVersion = 0
        self.UserType = 3
        self.Closed = 0
        self.NtfActivityConfirm = 1
        self.NtfActivityCancel = 1
        self.NtfActivityChange = 1
        self.NtfActivityNew = 1
        self.CreatedDate = today()

    @classmethod
    def addNewUser(cls,email,password,name):
        session = Session()
        new_user = User(Password=password)
        new_user.syncVersion = 0
        new_user.UserType = 3
        new_user.Closed = 0
        new_user.NtfActivityConfirm = 1
        new_user.NtfActivityCancel = 1
        new_user.NtfActivityChange = 1
        new_user.NtfActivityNew = 1
        new_user.Name = name
        new_user.Email = email
        new_user.CreatedDate = today()
        session.add(new_user)
        try:
            session.commit()
            from tools.MailTools import sendNewUserMail
            sendNewUserMail(email,name,password)
        except Exception as e:
            session.rollback()
            session.close()
            return Error(str(e))
        user = session.query(User).filter_by(Email=email).first()
        session.close()
        if user:
            return User(user.id,user.Password,user.Active,user.UserType,user.CompanyId)

    @classmethod
    def get(cls,username):
        user_data = cls.getUserFromDataBase(username)
        return user_data

    def __init__(self, id=None, Password=None, Active=0, UserType=3, CompanyId=None, EditSchedule=None):
        self.id = id
        self.Password = Password
        self.Active = Active
        self.UserType = UserType
        self.CompanyId = CompanyId
        self.EditSchedule = EditSchedule

    def check(self):
        if self.UserType==3:
            self.CompanyId = None
        if current_user.UserType in (1,2) and self.UserType in (1,2,3):
            self.CompanyId = current_user.CompanyId
        if current_user.UserType in (1,2) and not self.CompanyId: return Error("Completar Empresa")
        return True

    @classmethod
    def getRecordList(cls,TableClass,limit=None,order_by=None,desc=None):
        session = Session()
        records = session.query(cls)
        if current_user.UserType==1:
            records = records.filter(cls.CompanyId==current_user.CompanyId,cls.UserType>=1)
        elif current_user.UserType==2:
            records = records.filter(cls.CompanyId==current_user.CompanyId, \
                or_(cls.UserType==3,cls.id==current_user.id))
        session.close()
        return records

    @classmethod
    def canUserCreate(self):
        if current_user.UserType in (0,1,2):
            return True

    @classmethod
    def canUserDelete(self):
        if current_user.UserType == 0:
            return True

    @classmethod
    def canUserEdit(self,record):
        if current_user.id==record.id:
            return True
        elif record.UserType==None:
            return True
        elif current_user.UserType<record.UserType:
            return True
            return False

    @classmethod
    def getUserFieldsReadOnly(cls,record,fieldname):
        if fieldname=="Favorite":
            return
        if record and record.id==current_user.id:
            return
        if current_user.UserType==1:
            if record and record.UserType==3:
                return 1 #solo insertar nuevos
        if current_user.UserType==2:
            if record and record.UserType in (0,1,2):
                return 2 #nunca
            if record and record.UserType==3:
                return 1 #solo insertar nuevos

    @classmethod
    def customGetFieldsDefinition(cls,record,res):
        if record and record.id==current_user.id:
            res['UserType']['Hidde'] = True
        return res

    def getFavorite(self):
        from db.UserFavorite import UserFavorite
        session = Session()
        record = session.query(UserFavorite).filter_by(UserId=current_user.id,FavoriteId=self.id).first()
        if record and record.Checked:
            session.close()
            return 1
        session.close()
        return 0

    @classmethod
    def getRecordTitle(self):
        return ['Name']

    @classmethod
    def getLinksTo(self,record_list):
        res = {}
        res['UserType'] = {self.CUST: ['Cliente',0]}
        if current_user.UserType==0:
            res['UserType'][self.SUPER] = ['Super',0]
            res['UserType'][self.ADMIN] = ['Administrador',0]
            res['UserType'][self.PROF] = ['Profesional', 0]
        if current_user.UserType==1:
            res['UserType'][self.ADMIN] = ['Administrador',0]
            res['UserType'][self.PROF] = ['Profesional',0]
        res['CompanyId'] = {}
        session = Session()
        records = session.query(Company)
        for record in records:
            res['CompanyId'][record.id] = [record.Name,record.Closed]
        session.close()

        return res
Example #5
0
class Activity(Base, Record):

    __tablename__ = 'activity'
    id = Column(Integer, primary_key=True)
    CustId = Column(Integer, ForeignKey(User.id), nullable=True)
    ProfId = Column(Integer, ForeignKey(User.id), nullable=False)
    CompanyId = Column(Integer, ForeignKey(Company.id))
    ServiceId = Column(Integer, ForeignKey(Service.id), nullable=True)
    Type = Column(Integer)
    Comment = Column(String(100))
    Image = Column(String(100))
    MaxPersons = Column(Integer)
    Price = Column(Float)
    Description = Column(MediumText())
    Users = relationship('ActivityUsers', cascade="all, delete-orphan")
    Schedules = relationship('ActivitySchedules', cascade="all, delete-orphan")
    Status = Column(Integer)
    OnlinePayment = Column(Boolean)

    StatusList = ['Tomar este curso', 'Anular Inscripción']

    ACTIVITY_NEW = 0
    ACTIVITY_UPDATE = 1
    ACTIVITY_CANCEL = 2
    ACTIVITY_CONFIRM = 3
    ACTIVITY_NEW_CUST = 4
    ACTIVITY_NEAR = 5

    REQUESTED = 0
    CONFIRMED = 1
    CANCELLED = 2

    TYPE_MEETING = 0
    TYPE_COURSE = 1
    TYPE_EVENT = 2
    TYPE_BLOCK = 3

    def __init__(self):
        super(self.__class__, self).__init__()
        #super().__init__()

    @classmethod
    def getEventList(cls,
                     UserId=None,
                     CompanyId=None,
                     limit=None,
                     order_by=None,
                     desc=None):
        UserProf = aliased(User)
        session = Session()
        records = session.query(cls) \
            .filter(or_(cls.Type==1,cls.Type==2)) \
            .join(ActivitySchedules,cls.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate>=today()) \
            .join(Company,cls.CompanyId==Company.id)\
            .join(UserProf,cls.ProfId==UserProf.id)\
            .outerjoin(Service,cls.ServiceId==Service.id)\
            .with_entities(cls.Comment,UserProf.Name.label('ProfId') \
            ,ActivitySchedules.TransDate \
            ,ActivitySchedules.StartTime \
            ,ActivitySchedules.EndTime,cls.id,cls.Status,Company.Name.label('CompanyId')\
            ,Service.Name.label('ServiceId'))
        if UserId:
            records = records.filter(cls.ProfId == UserId)
        if CompanyId:
            records = records.filter(cls.CompanyId == CompanyId)
        if order_by and desc:
            records = records.order_by(ActivitySchedules.TransDate.desc())
        elif order_by:
            records = records.order_by(ActivitySchedules.TransDate)
        else:
            records = records.order_by(ActivitySchedules.TransDate)
        if limit: records = records.limit(limit)
        session.close()
        return records

    @classmethod
    def getRecordList(cls,
                      TableClass,
                      custId=None,
                      limit=None,
                      order_by=None,
                      desc=None,
                      ProfId=None,
                      Alias=False):
        if Alias:
            UserProf = aliased(User)
            UserCust = aliased(User)

        session = Session()
        records = session.query(cls)
        if current_user.UserType == 3:
            records = records.filter_by(CustId=current_user.id)
        if custId and current_user.UserType in (1, 2):
            records = records.filter_by(CompanyId=current_user.CompanyId,
                                        CustId=custId)
        if current_user.UserType == 2:
            records = records.filter_by(ProfId=current_user.id)
        records = records.join(ActivitySchedules,cls.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate>=today())
        if Alias:
            records = records.join(UserProf,cls.ProfId==UserProf.id)\
                .outerjoin(UserCust,cls.CustId==UserCust.id)\
                .outerjoin(Service,cls.ServiceId==Service.id)
        if current_user.UserType == 0:
            records = records.filter(or_(ProfId == None, cls.ProfId == ProfId))
        if not Alias:
            records = records.with_entities(cls.Comment,cls.ProfId,ActivitySchedules.TransDate,ActivitySchedules.StartTime \
                ,ActivitySchedules.EndTime,cls.id,cls.Status,cls.CustId,cls.CompanyId,cls.ServiceId,cls.Type)
        else:
            records = records.with_entities(cls.Comment, UserProf.id.label('ProfId'), ActivitySchedules.TransDate \
                ,ActivitySchedules.StartTime , ActivitySchedules.EndTime, cls.id, cls.Status, UserCust.id.label('CustId')\
                , cls.CompanyId, Service.id.label('ServiceId'), cls.Type, UserCust.Name.label('CustName'))
        if not custId and current_user.UserType in (1, 2):
            records = records.filter(
                Activity.CompanyId == current_user.CompanyId)
        if order_by and desc:
            records = records.order_by(ActivitySchedules.TransDate.desc())
        elif order_by:
            records = records.order_by(ActivitySchedules.TransDate)
        if limit: records = records.limit(limit)
        session.close()
        return records

    @classmethod
    def getUserFieldsReadOnly(cls, record, fieldname):
        if current_user.UserType == 1:
            if fieldname in ['Type']:
                return 1  #solo insertar nuevos
            elif fieldname in ['CompanyId']:
                return 2  # nunca
        if current_user.UserType == 2:
            if fieldname in ['CustId', 'Type']:
                return 1  #solo insertar nuevos
            elif fieldname in ('ProfId', 'CompanyId'):
                return 2  # nunca
        if current_user.UserType == 3:
            if fieldname in ['Comment']:
                return 1  #solo insertar nuevos
            elif fieldname in ('ProfId', 'CompanyId', 'TransDate', 'StartTime',
                               'EndTime', 'CustId', 'Type', 'Status', 'Price'):
                return 2  # nunca
        return 0  # siempre

    @classmethod
    def recordListFilters(cls):
        if current_user.UserType == 2:
            return ['Type','ServiceId','Status','CustId'],\
                   {'Type':'Tipo de Actividad','ServiceId':'Servicio','Status':'Estado','CustId':'Cliente'}
        if current_user.UserType == 3:
            return ['CompanyId','ServiceId','Status','ProfId']\
                   ,{'CompanyId':'Empresa','ServiceId':'Servicio','Status':'Estado','ProfId':'Profesional'}
        return ['Type','ServiceId','Status','ProfId','CustId'], \
                {'Type':'Tipo de Actividad','ServiceId': 'Servicio', 'Status': 'Estado'
                    , 'ProfId': 'Profesional','CustId':'Cliente'}

    def defaults(self):
        if current_user.UserType in (0, 1, 2):
            self.ProfId = current_user.id
        self.Status = 0
        self.CompanyId = current_user.CompanyId

    def check(self):
        #if not self.ServiceId:
        #    return Error("Debe Elegir un Servicio")
        if not len(self.Schedules):
            return Error("Debe ingresar horarios")
        if self.Type in (1, 2) and not self.Comment:
            return Error("Debe ingresar Nombre del Curso o Evento")
        res = self.checkSchedules()
        if not res: return res
        return True

    def getOverlapHeader(self, UserId, TransDate, StartTime, EndTime,
                         ActivityUser):
        session = Session()
        records = session.query(Activity) \
            .filter(Activity.Status!=2,ActivityUser==UserId,Activity.id!=self.id) \
            .join(ActivitySchedules,Activity.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate==TransDate,~ or_(ActivitySchedules.EndTime<=StartTime,ActivitySchedules.StartTime>=EndTime)) \
            .join(User,ActivityUser==User.id)\
            .with_entities(User.Name,ActivitySchedules.TransDate,ActivitySchedules.StartTime \
            ,ActivitySchedules.EndTime,Activity.id,Activity.Status)
        session.close()
        if records.count() > 0:
            return True
        return False

    def getOverlapCustRow(self, UserId, TransDate, StartTime, EndTime):
        session = Session()
        records = session.query(Activity) \
            .filter(Activity.Status!=2,Activity.id!=self.id) \
            .join(ActivitySchedules,Activity.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate==TransDate,~ or_(ActivitySchedules.EndTime<=StartTime,ActivitySchedules.StartTime>=EndTime)) \
            .join(ActivityUsers,Activity.id==ActivityUsers.activity_id)\
            .filter(ActivityUsers.CustId==UserId)\
            .join(User,ActivityUsers.CustId==User.id)\
            .with_entities(User.Name,ActivitySchedules.TransDate,ActivitySchedules.StartTime \
            ,ActivitySchedules.EndTime,Activity.id,Activity.Status)
        session.close()
        if records.count() > 0:
            return True
        return False

    def checkSchedules(self):
        if self.ProfId:
            for row in self.Schedules:
                res = self.getOverlapHeader(self.ProfId, row.TransDate,
                                            row.StartTime, row.EndTime,
                                            Activity.ProfId)
                if res: return Error('Superposición de Horarios')
                res = self.getOverlapCustRow(self.ProfId, row.TransDate,
                                             row.StartTime, row.EndTime)
                if res: return Error('Superposición de Horarios')
        if self.CustId:
            for row in self.Schedules:
                res = self.getOverlapHeader(self.CustId, row.TransDate,
                                            row.StartTime, row.EndTime,
                                            Activity.CustId)
                if res: return Error('Superposición de Horarios')
                res = self.getOverlapCustRow(self.CustId, row.TransDate,
                                             row.StartTime, row.EndTime)
                if res: return Error('Superposición de Horarios')
        for crow in self.Users:
            if crow.CustId:
                for row in self.Schedules:
                    res = self.getOverlapHeader(crow.CustId, row.TransDate,
                                                row.StartTime, row.EndTime,
                                                Activity.CustId)
                    if res: return Error('Superposición de Horarios')
                    res = self.getOverlapCustRow(crow.CustId, row.TransDate,
                                                 row.StartTime, row.EndTime)
                    if res: return Error('Superposición de Horarios')
        return True

    @classmethod
    def canUserCreate(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def canUserDelete(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def canUserAddRow(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def canUserDeleteRow(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def customGetFieldsDefinition(cls, record, res):
        if current_user.UserType == 3:
            res['Type']['Input'] = 'Hidde'
            res['OnlinePayment']['Input'] = 'Hidde'
        if current_user.UserType != 3 and record.Type != 0:
            res['Comment']['Label'] = 'Nombre de Curso/Evento'
        return res

    def setNotification(self, comment, user_id, type):
        ntf = Notification()
        ntf.defaults()
        ntf.UserId = user_id
        if self.Comment:
            ntf.Comment = "%s: %s" % (comment, self.Comment)
        else:
            ntf.Comment = comment
        ntf.Action = ""
        session = Session()
        res = ntf.save(session)
        if not res: return res
        return True

    def setNotificationActivityUpdate(self, UserId):
        res = True
        if self.OldFields['Status'] == self.Status:
            res = self.setNotification("Actividad Modificada", UserId,
                                       self.ACTIVITY_UPDATE)
        elif self.Status == 1:
            res = self.setNotification("Actividad Confirmada", UserId,
                                       self.ACTIVITY_CONFIRM)
        elif self.Status == 2:
            res = self.setNotification("Actividad Cancelada", UserId,
                                       self.ACTIVITY_CANCEL)
        return res

    def setMailActivity(self, user_id, type):
        user = User.getRecordById(user_id)
        if user:
            if type == self.ACTIVITY_UPDATE and user.NtfActivityChange:
                res = sendMailUpdateActivity(user, self)
            elif type == self.ACTIVITY_NEW and user.NtfActivityNew:
                res = sendMailNewActivity(user, self)
            elif type == self.ACTIVITY_CANCEL and user.NtfActivityCancel:
                res = sendMailCancelActivity(user, self)
            elif type == self.ACTIVITY_CONFIRM and user.NtfActivityConfirm:
                res = sendMailConfirmActivity(user, self)
            elif type == self.ACTIVITY_NEW_CUST and user.NtfActivityNewCust:
                res = sendMailNewCustActivity(user, self)
        return True

    def setMailActivityUpdate(self, UserId):
        res = True
        if self.OldFields['Status'] == self.Status:
            res = self.setMailActivity(UserId, self.ACTIVITY_UPDATE)
        elif self.Status == 1:
            res = self.setMailActivity(UserId, self.ACTIVITY_CONFIRM)
        elif self.Status == 2:
            res = self.setMailActivity(UserId, self.ACTIVITY_CANCEL)
        return res

    def afterCommitUpdate(self):
        if self.ProfId and current_user.id != self.ProfId:
            if len(self.Users) == len(self.OldFields['Users']):
                res = self.setNotificationActivityUpdate(self.ProfId)
                if not res: return res
            else:
                res = self.setNotification(
                    "Actividad Modificada. Nuevos Clientes", self.ProfId,
                    self.ACTIVITY_NEW_CUST)
                if not res: return res
        if self.CustId and current_user.id != self.CustId:
            res = self.setNotificationActivityUpdate(self.CustId)
            if not res: return res
        if len(self.Users) == len(self.OldFields['Users']):
            for row in self.Users:
                if row.CustId:
                    res = self.setNotificationActivityUpdate(row.CustId)
                    if not res: return res

        if self.ProfId:
            if len(self.Users) == len(self.OldFields['Users']):
                res = self.setMailActivityUpdate(self.ProfId)
                if not res: return res
            else:
                res = self.setMailActivity(self.ProfId, self.ACTIVITY_NEW_CUST)
                if not res: return res
        if self.CustId:
            res = self.setMailActivityUpdate(self.CustId)
            if not res: return res
        if len(self.Users) == len(self.OldFields['Users']):
            for row in self.Users:
                if row.CustId:
                    res = self.setMailActivityUpdate(row.CustId)
                    if not res: return res

        return True

    def afterCommitInsert(self):
        if self.ProfId and current_user.id != self.ProfId:
            self.setNotification("Nueva Actividad", self.ProfId,
                                 self.ACTIVITY_NEW)
        if self.CustId and current_user.id != self.CustId:
            self.setNotification("Nueva Actividad", self.CustId,
                                 self.ACTIVITY_NEW)
        for row in self.Users:
            if row.CustId:
                self.setNotification("Nueva Actividad", row.CustId,
                                     self.ACTIVITY_NEW)

        if self.ProfId: self.setMailActivity(self.ProfId, self.ACTIVITY_NEW)
        if self.CustId: self.setMailActivity(self.CustId, self.ACTIVITY_NEW)
        for row in self.Users:
            if row.CustId: self.setMailActivity(row.CustId, self.ACTIVITY_NEW)

        return True

    @classmethod
    def getLinksTo(self, record_list):
        res = {
            'CompanyId': {},
            'ProfId': {},
            'ServiceId': {},
            'Type': {},
            'Status': {},
            'CustId': {}
        }
        session = Session()
        if current_user.UserType == 3:
            records = session.query(Company)\
                .filter(Company.id.in_([r.CompanyId for r in record_list]))
        elif current_user.UserType > 0:
            records = session.query(Company).filter_by(
                id=current_user.CompanyId)
        for record in records:
            res['CompanyId'][record.id] = [record.Name, record.Closed]
        session.close()
        session = Session()
        records = session.query(User)
        if current_user.UserType == 3:
            records = records.filter(
                User.id.in_([r.ProfId for r in record_list]))
        elif current_user.UserType > 0:
            records = records.filter(User.CompanyId == current_user.CompanyId,
                                     User.UserType < 3)
        for record in records:
            res['ProfId'][record.id] = [record.Name, record.Closed]

        records = session.query(User)
        if current_user.UserType == 3:
            records = records.filter(
                User.id.in_([r.CustId for r in record_list]))
        elif current_user.UserType > 0:
            #records = records.filter(User.CompanyId==current_user.CompanyId,User.UserType==3)
            records = records.filter(User.UserType == 3)
        for record in records:
            res['CustId'][record.id] = [record.Name, record.Closed]

        try:
            count = record_list.count()
        except:
            count = len(record_list)
        if count == 1 and record_list[0].ProfId:
            records = session.query(UserService)\
                .filter_by(UserId=record_list[0].ProfId)\
                .join(Service,Service.id==UserService.ServiceId)\
                .with_entities(Service.id,Service.Name)
        else:
            records = session.query(UserService) \
                .join(Service, Service.id == UserService.ServiceId) \
                .filter(Service.CompanyId.in_([r.CompanyId for r in record_list]))\
                .with_entities(Service.id,Service.Name)
        for record in records:
            res['ServiceId'][record.id] = [record.Name, 0]

        res['Type'][self.TYPE_MEETING] = ['Cita', 0]
        res['Type'][self.TYPE_COURSE] = ['Curso', 0]
        res['Type'][self.TYPE_EVENT] = ['Evento', 0]
        res['Type'][self.TYPE_BLOCK] = ['Bloqueo de Horarios', 0]

        res['Status'][self.REQUESTED] = ['Solicitada', 0]
        res['Status'][self.CANCELLED] = ['Confirmada', 0]
        res['Status'][self.CONFIRMED] = ['Cancelada', 0]

        session.close()
        return res

    @classmethod
    def getRecordTitle(self):
        return ['ProfId', 'CustId', 'ServiceId']

    @classmethod
    def getEvents(self):
        return {'ProfId': {'AfterChange': 'updateLinkTo()'}}
Example #6
0
class Company(Base, Record):
    __tablename__ = 'company'
    id = Column(Integer, primary_key=True)
    Active = Column(Integer)
    Name = Column(String(40))
    Phone = Column(String(40))
    Email = Column(String(40))
    WebSite = Column(String(40))
    Comment = Column(MediumText())
    City = Column(String(100))
    Address = Column(String(100))
    ImageProfile = Column(String(100))
    OnlinePayment = Column(Integer)
    KeyPayco = Column(String(50))
    Closed = Column(Integer)

    @classmethod
    def fieldsDefinition(cls):
        res = Record.fieldsDefinition()
        res['id'] = {
            'Type': 'text',
            'Hidde': True,
            'Label': 'Código',
            'Input': 'integer',
            'Readonly': 1
        }
        res['Active'] = {
            'Type': 'integer',
            'Label': 'Activo',
            'Input': 'checkbox',
            'Level': [0]
        }
        res['Name'] = {'Type': 'text', 'Label': 'Nombre', 'Input': 'text'}
        res['Phone'] = {'Type': 'text', 'Label': 'Teléfono', 'Input': 'text'}
        res['Email'] = {'Type': 'text', 'Label': 'Email', 'Input': 'text'}
        res['WebSite'] = {'Type': 'text', 'Label': 'Web Site', 'Input': 'text'}
        res['Comment'] = {
            'Type': 'text',
            'Label': 'Comentario',
            'Input': 'textarea',
            'rows': '4'
        }
        res['Address'] = {
            'Type': 'text',
            'Label': 'Dirección',
            'Input': 'text'
        }
        res['City'] = {'Type': 'text', 'Label': 'Ciudad', 'Input': 'text'}
        res['ImageProfile'] = {
            'Type': 'text',
            'Label':
            'Imagen de Perfil. Tamaño sugerido: 300px x 300px. Peso máximo: 150kb',
            'Input': 'fileinput'
        }
        res['OnlinePayment'] = {
            'Type': 'integer',
            'Label': 'Habilitar Pagos en línea',
            'Input': 'checkbox'
        }
        res['KeyPayco'] = {
            'Type': 'text',
            'Label': 'Clave ePayco',
            'Input': 'text'
        }
        res['Closed'] = {
            'Type': 'integer',
            'Label': 'Cerrado',
            'Input': 'checkbox',
            'Level': [0]
        }
        return res

    @classmethod
    def htmlView(cls):
        Tabs = {}
        Tabs[0] = {"Name":"", "Fields": [[0,["Active"]],[1,["Name"]],[2,["Address","City"]],[3,["Phone"]],[4,["Email"]],[5,["WebSite"]],[6,["Comment"]] \
            ,[7,["ImageProfile"]],[8,["KeyPayco","OnlinePayment"]],[9,["Closed"]]]}
        return Tabs

    def defaults(self):
        self.Closed = 0

    def check(self):
        if not self.Name: return Error("Debe Completar el Nombre")
        return True

    @classmethod
    def canUserDelete(self):
        if current_user.UserType == 0:
            return True

    @classmethod
    def getRecordTitle(self):
        return ['Name']

    @classmethod
    def canUserEdit(cls, record):
        if current_user.UserType == 3:
            return False
        return True

    @classmethod
    def getUserFieldsReadOnly(cls, record, fieldname):
        if current_user.UserType == 3:
            return 2
        return 0
Example #7
0
class Activity(Base, Record):

    __tablename__ = 'activity'
    id = Column(Integer, primary_key=True)
    CustId = Column(Integer, ForeignKey(User.id), nullable=True)
    ProfId = Column(Integer, ForeignKey(User.id), nullable=False)
    CompanyId = Column(Integer, ForeignKey(Company.id))
    ServiceId = Column(Integer, ForeignKey(Service.id), nullable=True)
    Type = Column(Integer)
    Comment = Column(String(100))
    Image = Column(String(100))
    MaxPersons = Column(Integer)
    Price = Column(Float)
    Description = Column(MediumText())
    Users = relationship('ActivityUsers', cascade="all, delete-orphan")
    Schedules = relationship('ActivitySchedules', cascade="all, delete-orphan")
    Status = Column(Integer)
    OnlinePayment = Column(Integer)

    StatusList = ['Tomar este curso', 'Anular Inscripción']

    ACTIVITY_NEW = 0
    ACTIVITY_UPDATE = 1
    ACTIVITY_CANCEL = 2
    ACTIVITY_CONFIRM = 3
    ACTIVITY_NEW_CUST = 4
    ACTIVITY_NEAR = 5

    REQUESTED = 0
    CONFIRMED = 1
    CANCELLED = 2

    def __init__(self):
        super(self.__class__, self).__init__()
        #super().__init__()

    @classmethod
    def fieldsDefinition(cls):
        res = Record.fieldsDefinition()
        res['id'] = {'Type': 'integer', 'Hidde': True}
        res['CustId'] = {'Type': 'integer', 'Label': 'Cliente', 'Input': 'combo','LinkTo':{'Table':'User','Show':['Name']\
            ,'Method':'getCustomer','Params':"{'favorite':True}" \
            ,'Filters': {'UserType':[3]},'Params':"{'favorite':True}"},'ShowIf':['Type',["0"],-1]}
        res['ProfId'] = {'Type': 'integer', 'Label': 'Profesional', 'Input': 'combo','LinkTo':{'Table':'User','Show':['Name'] \
            ,'Filters': {'UserType':[0,1,2]}}}
        res['CompanyId'] = {
            'Type': 'text',
            'Label': 'Empresa',
            'Input': 'combo',
            'LinkTo': {
                'Table': 'Company',
                'Show': ['Name']
            }
        }
        res['ServiceId'] = {'Type': 'text', 'Label': 'Servicio', 'Input': 'combo','LinkTo':{'Table':'Service','Show':['Name']} \
            ,'AfterChange':'setServicePrice()'}
        res['Comment'] = {
            'Type': 'text',
            'Label': 'Comentario',
            'Input': 'text'
        }
        res['Type'] = {'Type': 'integer', 'Label': 'Tipo de actividad', 'Input': 'combo' \
            ,'Values': {0: 'Cita',1: 'Curso',2:'Evento'},'OnChange':'updateLinkTo()'}
        if current_user.UserType == 3:
            res['Type']['Hidde'] = True
        res['Users'] = {
            'Type': [],
            'Class': 'ActivityUsers',
            'fieldsDefinition': ActivityUsers.fieldsDefinition(),
            'Level': [0, 1, 2],
            'htmlView': ActivityUsers.htmlView()
        }
        res['Schedules'] = {
            'Type': [],
            'Label': 'Horarios',
            'Class': 'ActivitySchedules',
            'fieldsDefinition': ActivitySchedules.fieldsDefinition(),
            'Level': [0, 1, 2, 3],
            'htmlView': ActivitySchedules.htmlView()
        }
        res['Image'] = {
            'Type': 'text',
            'Label': 'Imagen',
            'Input': 'fileinput',
            'Level': [0, 1, 2]
        }
        res['MaxPersons'] = {
            'Type': 'integer',
            'Label': 'Cupos',
            'Input': 'integer',
            'Level': [0, 1, 2]
        }
        res['Price'] = {
            'Type': 'float',
            'Label': 'Valor',
            'Input': 'number',
            'Level': [0, 1, 2, 3]
        }
        res['Description'] = {
            'Type': 'text',
            'Label': 'Descripción',
            'Input': 'textarea',
            'rows': '4',
            'Level': [0, 1, 2]
        }
        res['Status'] = {
            'Type': 'integer',
            'Label': 'Estado',
            'Input': 'combo',
            'Values': {
                0: 'Solicitada',
                1: 'Confirmada',
                2: 'Cancelada'
            },
            'Level': [0, 1, 2, 3]
        }
        res['OnlinePayment'] = {
            'Type': 'integer',
            'Label': 'Habilitar Pagos en línea',
            'Input': 'checkbox',
            'Level': [0, 1, 2, 3]
        }
        return res

    @classmethod
    def htmlView(cls):
        Tabs = {}
        Tabs[0] = {"Name":"Información", "Fields": [[0,["CompanyId","ProfId"]],[4,["Type","Comment"]],[2,["CustId","ServiceId","Status"]] \
            ,[5,["Price","OnlinePayment"]]]}
        Tabs[1] = {"Name": "Horarios", "Fields": [[0, ["Schedules"]]]}
        Tabs[2] = {
            "Name": "Curso/Evento",
            'Level': [0, 1, 2],
            "Fields": [[0, ["MaxPersons", "Image"]], [1, ["Description"]]],
            'ShowIf': ['Type', ["1", "2"], -1]
        }
        Tabs[3] = {
            "Name": "Clientes",
            'Level': [0, 1, 2],
            "Fields": [[0, ["Users"]]],
            'ShowIf': ['Type', ["1", "2"], -1]
        }
        return Tabs

    @classmethod
    def getEventList(cls,
                     UserId=None,
                     CompanyId=None,
                     limit=None,
                     order_by=None,
                     desc=None):
        UserProf = aliased(User)
        session = Session()
        records = session.query(cls) \
            .filter(or_(cls.Type==1,cls.Type==2)) \
            .join(ActivitySchedules,cls.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate>=today()) \
            .join(Company,cls.CompanyId==Company.id)\
            .join(UserProf,cls.ProfId==UserProf.id)\
            .outerjoin(Service,cls.ServiceId==Service.id)\
            .with_entities(cls.Comment,UserProf.id.label('ProfId'),ActivitySchedules.TransDate,ActivitySchedules.StartTime \
            ,ActivitySchedules.EndTime,cls.id,cls.Status,Company.id.label('CompanyId')\
            ,Service.id.label('ServiceId'))
        if UserId:
            records = records.filter(cls.ProfId == UserId)
        if CompanyId:
            records = records.filter(cls.CompanyId == CompanyId)
        if order_by and desc:
            records = records.order_by(ActivitySchedules.TransDate.desc())
        elif order_by:
            records = records.order_by(ActivitySchedules.TransDate)
        else:
            records = records.order_by(ActivitySchedules.TransDate)
        if limit: records = records.limit(limit)
        session.close()
        return records

    @classmethod
    def getRecordList(cls,
                      TableClass,
                      custId=None,
                      limit=None,
                      order_by=None,
                      desc=None,
                      ProfId=None,
                      Alias=False):
        if Alias:
            UserProf = aliased(User)
            UserCust = aliased(User)

        session = Session()
        records = session.query(cls)
        if current_user.UserType == 3:
            records = records.filter_by(CustId=current_user.id)
        if custId and current_user.UserType in (1, 2):
            records = records.filter_by(CompanyId=current_user.CompanyId,
                                        CustId=custId)
        if current_user.UserType == 2:
            records = records.filter_by(ProfId=current_user.id)
        records = records.join(ActivitySchedules,cls.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate>=today())
        if Alias:
            records = records.join(UserProf,cls.ProfId==UserProf.id)\
                .outerjoin(UserCust,cls.CustId==UserCust.id)\
                .outerjoin(Service,cls.ServiceId==Service.id)
        if current_user.UserType == 0:
            records = records.filter(or_(ProfId == None, cls.ProfId == ProfId))
        if not Alias:
            records = records.with_entities(cls.Comment,cls.ProfId,ActivitySchedules.TransDate,ActivitySchedules.StartTime \
                ,ActivitySchedules.EndTime,cls.id,cls.Status,cls.CustId,cls.CompanyId,cls.ServiceId,cls.Type)
        else:
            records = records.with_entities(cls.Comment, UserProf.id.label('ProfId'), ActivitySchedules.TransDate \
                ,ActivitySchedules.StartTime , ActivitySchedules.EndTime, cls.id, cls.Status, UserCust.id.label('CustId')\
                , cls.CompanyId, Service.id.label('ServiceId'), cls.Type)
        if not custId and current_user.UserType in (1, 2):
            records = records.filter(
                Activity.CompanyId == current_user.CompanyId)
        if order_by and desc:
            records = records.order_by(ActivitySchedules.TransDate.desc())
        elif order_by:
            records = records.order_by(ActivitySchedules.TransDate)
        if limit: records = records.limit(limit)
        session.close()
        return records

    @classmethod
    def getRecordListCalendar(cls,
                              TableClass,
                              custId=None,
                              limit=None,
                              order_by=None,
                              desc=None,
                              ProfId=None):
        records = cls.getRecordList(TableClass,
                                    custId,
                                    limit,
                                    order_by,
                                    desc,
                                    ProfId,
                                    Alias=True)
        return records

    @classmethod
    def getUserFieldsReadOnly(cls, record, fieldname):
        if current_user.UserType == 1:
            if fieldname in ['Type']:
                return 1  #solo insertar nuevos
            elif fieldname in ['CompanyId']:
                return 2  # nunca
        if current_user.UserType == 2:
            if fieldname in ['CustId', 'Type']:
                return 1  #solo insertar nuevos
            elif fieldname in ('ProfId', 'CompanyId'):
                return 2  # nunca
        if current_user.UserType == 3:
            if fieldname in ['Comment']:
                return 1  #solo insertar nuevos
            elif fieldname in ('ProfId', 'CompanyId', 'TransDate', 'StartTime',
                               'EndTime', 'CustId', 'Type', 'Status', 'Price'):
                return 2  # nunca
        return 0  # siempre

    @classmethod
    def recordListFilters(cls):
        return ['Type', 'ServiceId', 'Status', 'ProfId']

    def defaults(self):
        if current_user.UserType in (0, 1, 2):
            self.ProfId = current_user.id
        self.Status = 0
        self.CompanyId = current_user.CompanyId

    def check(self):
        #if not self.ServiceId:
        #    return Error("Debe Elegir un Servicio")
        if not len(self.Schedules):
            return Error("Debe ingresar horarios")
        if self.Type in (1, 2) and not self.Comment:
            return Error("Debe ingresar Nombre del Curso o Evento")
        res = self.checkSchedules()
        if not res: return res
        return True

    def getOverlapHeader(self, UserId, TransDate, StartTime, EndTime,
                         ActivityUser):
        session = Session()
        records = session.query(Activity) \
            .filter(Activity.Status!=2,ActivityUser==UserId,Activity.id!=self.id) \
            .join(ActivitySchedules,Activity.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate==TransDate,~ or_(ActivitySchedules.EndTime<=StartTime,ActivitySchedules.StartTime>=EndTime)) \
            .join(User,ActivityUser==User.id)\
            .with_entities(User.Name,ActivitySchedules.TransDate,ActivitySchedules.StartTime \
            ,ActivitySchedules.EndTime,Activity.id,Activity.Status)
        session.close()
        if records.count() > 0:
            return True
        return False

    def getOverlapCustRow(self, UserId, TransDate, StartTime, EndTime):
        session = Session()
        records = session.query(Activity) \
            .filter(Activity.Status!=2,Activity.id!=self.id) \
            .join(ActivitySchedules,Activity.id==ActivitySchedules.activity_id)\
            .filter(ActivitySchedules.TransDate==TransDate,~ or_(ActivitySchedules.EndTime<=StartTime,ActivitySchedules.StartTime>=EndTime)) \
            .join(ActivityUsers,Activity.id==ActivityUsers.activity_id)\
            .filter(ActivityUsers.CustId==UserId)\
            .join(User,ActivityUsers.CustId==User.id)\
            .with_entities(User.Name,ActivitySchedules.TransDate,ActivitySchedules.StartTime \
            ,ActivitySchedules.EndTime,Activity.id,Activity.Status)
        session.close()
        if records.count() > 0:
            return True
        return False

    def checkSchedules(self):
        if self.ProfId:
            for row in self.Schedules:
                res = self.getOverlapHeader(self.ProfId, row.TransDate,
                                            row.StartTime, row.EndTime,
                                            Activity.ProfId)
                if res: return Error('Superposición de Horarios')
                res = self.getOverlapCustRow(self.ProfId, row.TransDate,
                                             row.StartTime, row.EndTime)
                if res: return Error('Superposición de Horarios')
        if self.CustId:
            for row in self.Schedules:
                res = self.getOverlapHeader(self.CustId, row.TransDate,
                                            row.StartTime, row.EndTime,
                                            Activity.CustId)
                if res: return Error('Superposición de Horarios')
                res = self.getOverlapCustRow(self.CustId, row.TransDate,
                                             row.StartTime, row.EndTime)
                if res: return Error('Superposición de Horarios')
        for crow in self.Users:
            if crow.CustId:
                for row in self.Schedules:
                    res = self.getOverlapHeader(crow.CustId, row.TransDate,
                                                row.StartTime, row.EndTime,
                                                Activity.CustId)
                    if res: return Error('Superposición de Horarios')
                    res = self.getOverlapCustRow(crow.CustId, row.TransDate,
                                                 row.StartTime, row.EndTime)
                    if res: return Error('Superposición de Horarios')
        return True

    @classmethod
    def canUserCreate(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def canUserDelete(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def canUserAddRow(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def canUserDeleteRow(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def customGetFieldsDefinition(cls, record, res):
        if current_user.UserType == 3:
            res['Type']['Input'] = 'Hidde'
            res['OnlinePayment']['Input'] = 'Hidde'
        if current_user.UserType != 3 and record.Type != 0:
            res['Comment']['Label'] = 'Nombre de Curso/Evento'
        return res

    def setNotification(self, comment, user_id, type):
        ntf = Notification()
        ntf.defaults()
        ntf.UserId = user_id
        if self.Comment:
            ntf.Comment = "%s: %s" % (comment, self.Comment)
        else:
            ntf.Comment = comment
        ntf.Action = ""
        session = Session()
        res = ntf.save(session)
        if not res: return res
        return True

    def setNotificationActivityUpdate(self, UserId):
        res = True
        if self.OldFields['Status'] == self.Status:
            res = self.setNotification("Actividad Modificada", UserId,
                                       self.ACTIVITY_UPDATE)
        elif self.Status == 1:
            res = self.setNotification("Actividad Confirmada", UserId,
                                       self.ACTIVITY_CONFIRM)
        elif self.Status == 2:
            res = self.setNotification("Actividad Cancelada", UserId,
                                       self.ACTIVITY_CANCEL)
        return res

    def setMailActivity(self, user_id, type):
        user = User.getRecordById(user_id)
        if user:
            if type == self.ACTIVITY_UPDATE and user.NtfActivityChange:
                res = sendMailUpdateActivity(user, self)
            elif type == self.ACTIVITY_NEW and user.NtfActivityNew:
                res = sendMailNewActivity(user, self)
            elif type == self.ACTIVITY_CANCEL and user.NtfActivityCancel:
                res = sendMailCancelActivity(user, self)
            elif type == self.ACTIVITY_CONFIRM and user.NtfActivityConfirm:
                res = sendMailConfirmActivity(user, self)
            elif type == self.ACTIVITY_NEW_CUST and user.NtfActivityNewCust:
                res = sendMailNewCustActivity(user, self)
        return True

    def setMailActivityUpdate(self, UserId):
        res = True
        if self.OldFields['Status'] == self.Status:
            res = self.setMailActivity(UserId, self.ACTIVITY_UPDATE)
        elif self.Status == 1:
            res = self.setMailActivity(UserId, self.ACTIVITY_CONFIRM)
        elif self.Status == 2:
            res = self.setMailActivity(UserId, self.ACTIVITY_CANCEL)
        return res

    def afterCommitUpdate(self):
        if self.ProfId and current_user.id != self.ProfId:
            if len(self.Users) == len(self.OldFields['Users']):
                res = self.setNotificationActivityUpdate(self.ProfId)
                if not res: return res
            else:
                res = self.setNotification(
                    "Actividad Modificada. Nuevos Clientes", self.ProfId,
                    self.ACTIVITY_NEW_CUST)
                if not res: return res
        if self.CustId and current_user.id != self.CustId:
            res = self.setNotificationActivityUpdate(self.CustId)
            if not res: return res
        if len(self.Users) == len(self.OldFields['Users']):
            for row in self.Users:
                if row.CustId:
                    res = self.setNotificationActivityUpdate(row.CustId)
                    if not res: return res

        if self.ProfId:
            if len(self.Users) == len(self.OldFields['Users']):
                res = self.setMailActivityUpdate(self.ProfId)
                if not res: return res
            else:
                res = self.setMailActivity(self.ProfId, self.ACTIVITY_NEW_CUST)
                if not res: return res
        if self.CustId:
            res = self.setMailActivityUpdate(self.CustId)
            if not res: return res
        if len(self.Users) == len(self.OldFields['Users']):
            for row in self.Users:
                if row.CustId:
                    res = self.setMailActivityUpdate(row.CustId)
                    if not res: return res

        return True

    def afterCommitInsert(self):
        if self.ProfId and current_user.id != self.ProfId:
            self.setNotification("Nueva Actividad", self.ProfId,
                                 self.ACTIVITY_NEW)
        if self.CustId and current_user.id != self.CustId:
            self.setNotification("Nueva Actividad", self.CustId,
                                 self.ACTIVITY_NEW)
        for row in self.Users:
            if row.CustId:
                self.setNotification("Nueva Actividad", row.CustId,
                                     self.ACTIVITY_NEW)

        if self.ProfId: self.setMailActivity(self.ProfId, self.ACTIVITY_NEW)
        if self.CustId: self.setMailActivity(self.CustId, self.ACTIVITY_NEW)
        for row in self.Users:
            if row.CustId: self.setMailActivity(row.CustId, self.ACTIVITY_NEW)

        return True

    def getLinkToFromRecord(self, TableClass):
        if TableClass == Service:
            session = Session()
            if self.ProfId:
                records = session.query(UserService)\
                    .filter_by(UserId=self.ProfId)\
                    .join(Service,UserService.ServiceId==Service.id)\
                    .with_entities(Service.id,Service.Name)
            else:
                records = session.query(UserService).join(Service,UserService.ServiceId==Service.id)\
                    .filter_by(CompanyId=self.CompanyId)\
                    .with_entities(Service.id,Service.Name)

            session.close()
            return records
        else:
            return TableClass.getRecordList(TableClass)

    @classmethod
    def getRecordTitle(self):
        return ['ProfId', 'CustId', 'ServiceId']
Example #8
0
class Notification(Base, Record):

    __tablename__ = 'notification'
    id = Column(Integer, primary_key=True)
    UserId = Column(Integer, ForeignKey(User.id), nullable=True)
    Status = Column(Integer)
    Comment = Column(String(255))
    Action = Column(String(255))
    TransDate = Column(DateTime)
    Description = Column(MediumText())

    def __init__(self):
        super(self.__class__, self).__init__()
        #super().__init__()

    @classmethod
    def fieldsDefinition(cls):
        res = Record.fieldsDefinition()
        res['id'] = {'Type': 'integer', 'Hidde': True}
        res['UserId'] = {'Type': 'integer', 'Hidde': True}
        res['Comment'] = {
            'Type': 'text',
            'Label': 'Comentario',
            'Input': 'text',
            'Readonly': 1
        }
        res['Action'] = {'Type': 'text', 'Hidde': True}
        res['Status'] = {
            'Type': 'integer',
            'Label': 'Estado',
            'Input': 'combo',
            'Values': {
                0: 'No Leída',
                1: 'Leída'
            }
        }
        res['TransDate'] = {
            'Type': 'datetime',
            'Label': 'Fecha',
            'Input': 'datetime',
            'Readonly': 1
        }
        res['Description'] = {
            'Type': 'text',
            'Label': 'Descripción',
            'Input': 'textarea',
            'rows': '4',
            'Readonly': 1
        }
        return res

    @classmethod
    def htmlView(cls):
        Tabs = {}
        Tabs[0] = {
            "Fields": [[0, ["Comment"]], [1, ["Status"]], [2, ["Fecha"]],
                       [3, ["Description"]]]
        }
        return Tabs

    def defaults(self):
        self.TransDate = now()
        self.Status = 0

    @classmethod
    def canUserCreate(self):
        return False

    @classmethod
    def canUserDelete(cls):
        return False

    @classmethod
    def getRecordList(cls, TableClass, limit=None, order_by=None, desc=None):
        session = Session()
        records = session.query(cls).filter_by(
            UserId=current_user.id).order_by(Notification.TransDate.desc())
        session.close()
        return records

    def afterSaveJS(self):
        return 'getNotifications()'
Example #9
0
class User(Base, Record, UserMixin):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    Email = Column(String(50))
    Password = Column(String(20))
    Active = Column(Integer)
    UserType = Column(Integer)
    CompanyId = Column(Integer, ForeignKey(Company.id))
    Name = Column(String(40))
    Title = Column(String(40))
    FindMe = Column(Integer)
    EditSchedule = Column(Integer)
    FixedSchedule = Column(Integer)
    MinTime = Column(Integer)
    MaxTime = Column(Integer)
    ShowDays = Column(Integer)
    Phone = Column(String(40))
    Comment = Column(MediumText())
    City = Column(String(100))
    Address = Column(String(100))
    ImageProfile = Column(String(100))
    NtfActivityCancel = Column(Integer)
    NtfActivityNew = Column(Integer)
    NtfActivityChange = Column(Integer)
    NtfActivityReminder = Column(Integer)
    NtfReminderDays = Column(Integer)
    NtfReminderHours = Column(Integer)
    ShowFromDays = Column(Integer)
    NtfActivityConfirm = Column(Integer)
    NtfActivityNewCust = Column(Integer)
    Closed = Column(Integer)
    CreatedDate = Column(Date)

    Schedules = relationship('UserSchedule', cascade="all, delete-orphan")

    #def __repr__(self):
    #    return "<User(Active='%s', AcessGroup='%s', Password='******')>" % (self.Active, self.AcessGroup, self.Password)

    @classmethod
    def fieldsDefinition(cls):
        res = Record.fieldsDefinition()
        res['id'] = {'Type': 'integer', 'Hidde': True}
        res['Email'] = {'Type': 'text', 'Label': 'Email', 'Input': 'text'}
        res['Password'] = {
            'Type': 'text',
            'Label': 'Password',
            'Input': 'password'
        }
        res['Active'] = {
            'Type': 'integer',
            'Label': 'Activo',
            'Input': 'checkbox',
            'Level': [0]
        }
        res['UserType'] = {'Type': 'integer', 'Label': 'Tipo de Usuario', 'Input': 'combo', \
            'Values': {0: 'Super',1: 'Administrador',2: 'Profesional',3: 'Cliente'},\
            'ValuesLevel':{0:[0,1,2,3],1:[1,2,3],2:[3],3:[]},'ShowIf':['UserType',["0","1","2"],-1]}
        res['CompanyId'] = {'Type': 'integer', 'Label': 'Empresa', 'Input': 'combo','Level':[0]\
            ,'LinkTo':{'Table':'Company','Show':['Name']},'ShowIf':['UserType',["0","1","2"],-1]}
        res['Name'] = {'Type': 'text', 'Label': 'Nombre', 'Input': 'text'}
        res['Title'] = {
            'Type': 'text',
            'Label': 'Profesión',
            'Input': 'text',
            'Level': [0, 1, 2]
        }
        res['FindMe'] = {
            'Type': 'integer',
            'Label': 'Aparecer en Buscador',
            'Input': 'checkbox',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['FixedSchedule'] = {
            'Type': 'integer',
            'Label': 'Horarios Fijos',
            'Input': 'checkbox',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['MinTime'] = {
            'Type': 'integer',
            'Label': 'Tiempo Mínimo',
            'Input': 'integer',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['MaxTime'] = {
            'Type': 'integer',
            'Label': 'Tiempo Máximo',
            'Input': 'integer',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['ShowDays'] = {
            'Type': 'integer',
            'Label': 'Disponibilidad Hasta (Cantidad de días)',
            'Input': 'integer',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['ShowFromDays'] = {
            'Type': 'integer',
            'Label': 'Disponibilidad Desde (Cantidad de días)',
            'Input': 'integer',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['Phone'] = {'Type': 'text', 'Label': 'Teléfono', 'Input': 'text'}
        res['Comment'] = {
            'Type': 'text',
            'Label': 'Descripción',
            'Input': 'textarea',
            'rows': '4',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['Address'] = {
            'Type': 'text',
            'Label': 'Dirección',
            'Input': 'text'
        }
        res['City'] = {'Type': 'text', 'Label': 'Ciudad', 'Input': 'text'}
        res['EditSchedule'] = {'Type': 'integer', 'Label': 'Editar Agenda', 'Input': 'combo', \
            'Values': {0: 'SI',1: 'NO'},'Level':[0,1],'ShowIf':['UserType',["0","1","2"],-1]}
        res['Schedules'] = {'Type':[],'Label':'Horarios','Class':'UserSchedule',\
            'fieldsDefinition': UserSchedule.fieldsDefinition(),'Level':[0,1,2],'ShowIf':['UserType',["0","1","2"],-1]}
        res['Favorite'] = {'Type': 'integer', 'Label': 'Agregar a Favoritos', 'Input': 'button','Level':[0,1,2],'Persistent':False, \
            'Method':'getFavorite()','onClick': 'setFavorite(this,"1")','Class':'btn btn-primary btn-rounded waves-effect waves-light m-t-20' }
        res['ImageProfile'] = {'Type': 'text', 'Label': 'Imagen de Perfil', 'Input': 'fileinput' ,\
                               'SubLabel':'Tamaño sugerido: 300px x 300px. Peso máximo: 150kb'}
        res['NtfActivityNew'] = {
            'Type': 'integer',
            'Label': 'Nueva Actividad',
            'Input': 'checkbox'
        }
        res['NtfActivityCancel'] = {
            'Type': 'integer',
            'Label': 'Actividad Cancelada',
            'Input': 'checkbox'
        }
        res['NtfActivityChange'] = {
            'Type': 'integer',
            'Label': 'Actividad Modificada',
            'Input': 'checkbox'
        }
        res['NtfActivityReminder'] = {
            'Type': 'integer',
            'Label': 'Recordatorio de Actividad ',
            'Input': 'checkbox'
        }
        res['NtfReminderDays'] = {
            'Type': 'integer',
            'Label': 'Días de Antelación para Recordatorio',
            'Input': 'integer'
        }
        res['NtfReminderHours'] = {
            'Type': 'integer',
            'Label': 'Horas de Antelación para Recordatorio',
            'Input': 'integer'
        }
        res['NtfActivityConfirm'] = {
            'Type': 'integer',
            'Label': 'Actividad Confirmada',
            'Input': 'checkbox'
        }
        res['NtfActivityNewCust'] = {
            'Type': 'integer',
            'Label': 'Nuevos Clientes',
            'Input': 'checkbox',
            'Level': [0, 1, 2],
            'ShowIf': ['UserType', ["0", "1", "2"], -1]
        }
        res['Closed'] = {
            'Type': 'integer',
            'Label': 'Cerrado',
            'Input': 'checkbox',
            'Level': [0]
        }
        res['CreatedDate'] = {'Type': 'date', 'Hidde': True}
        return res

    @classmethod
    def htmlView(cls):
        Tabs = {}
        Tabs[0] = {"Name":"Información del Usuario", "Fields": [[0,["Name","Phone"]],[3,["Address","City"]] \
            ,[6,["Comment"]],[7,["Title","ImageProfile"]]]}
        Tabs[1] = {"Name":"Configuración del Usuario", "Fields": [[0,["Email","Password"]],[2,["UserType","Closed"]] \
            ,[4,["CompanyId","EditSchedule"]],[6,["FindMe"]],[7,["Favorite"]]]}
        Tabs[2] = {"Name":"Agenda","Fields": [[0,["ShowFromDays","ShowDays"]],[1,["FixedSchedule"]],[2,["MaxTime","MinTime"]],[3,["Schedules"]]]\
            ,'ShowIf':['UserType',["0","1","2"],-1]}
        Tabs[3] = {"Name":"Notificaciones por correo", "Fields": [[0,["NtfActivityNew","NtfActivityCancel"]] \
            ,[2,["NtfActivityConfirm","NtfActivityNewCust"]],[2,["NtfActivityChange"]]]}
        return Tabs

    def filterFields(self, fields):
        #filtro de campo por tipo de usuario
        filters = {
            3: [
                'Title', 'FindMe', 'FixedSchedule', 'MinTime', 'MaxTime',
                'EditSchedule', 'Schedules', 'ShowDays', 'ShowFromDays',
                'Comment'
            ]
        }
        if self.UserType in filters:
            filters = filters[self.UserType]
            for fn in filters:
                if fn in fields:
                    del fields[fn]
        if (current_user.id == self.id) and (self.EditSchedule):
            del fields['Schedules']
        if self.id and current_user.UserType != 0:
            del fields['Password']

    @classmethod
    def getUserFromDataBase(cls, id):
        user = cls.getRecordById(id)
        if user:
            return user

    @classmethod
    def getUserIdByEmail(cls, email):
        session = Session()
        record = session.query(cls).filter_by(Email=email).first()
        if not record:
            return
        id = record.id
        session.close()
        return id

    def defaults(self):
        self.syncVersion = 0
        self.UserType = 3
        self.Closed = 0
        self.NtfActivityConfirm = 1
        self.NtfActivityCancel = 1
        self.NtfActivityChange = 1
        self.NtfActivityNew = 1
        self.CreatedDate = today()

    @classmethod
    def addNewUser(cls, email, password, name):
        session = Session()
        new_user = User(Password=password)
        new_user.syncVersion = 0
        new_user.UserType = 3
        new_user.Closed = 0
        new_user.NtfActivityConfirm = 1
        new_user.NtfActivityCancel = 1
        new_user.NtfActivityChange = 1
        new_user.NtfActivityNew = 1
        new_user.Name = name
        new_user.Email = email
        new_user.CreatedDate = today()
        session.add(new_user)
        try:
            session.commit()
            from dondefluir.MailTools import sendNewUserMail
            sendNewUserMail(email, name, password)
        except Exception as e:
            session.rollback()
            session.close()
            return Error(str(e))
        user = session.query(User).filter_by(Email=email).first()
        session.close()
        if user:
            return User(user.id, user.Password, user.Active, user.UserType,
                        user.CompanyId)

    @classmethod
    def get(cls, username):
        user_data = cls.getUserFromDataBase(username)
        return user_data

    def __init__(self,
                 id=None,
                 Password=None,
                 Active=0,
                 UserType=3,
                 CompanyId=None,
                 EditSchedule=None):
        self.id = id
        self.Password = Password
        self.Active = Active
        self.UserType = UserType
        self.CompanyId = CompanyId
        self.EditSchedule = EditSchedule

    def check(self):
        if hasattr(self, "_new") and not self.id:
            return Error("Completar Código")
        if self.UserType == 3:
            self.CompanyId = None
        if current_user.UserType in (1, 2) and self.UserType in (1, 2, 3):
            self.CompanyId = current_user.CompanyId
        if current_user.UserType in (1, 2) and not self.CompanyId:
            return Error("Completar Empresa")
        return True

    @classmethod
    def getRecordList(cls, TableClass, limit=None, order_by=None, desc=None):
        if current_user.UserType == 1:
            session = Session()
            records = session.query(cls).filter(
                cls.CompanyId == current_user.CompanyId, cls.UserType >= 1)
            session.close()
        elif current_user.UserType == 2:
            session = Session()
            records = session.query(cls).filter(cls.CompanyId==current_user.CompanyId, \
                or_(cls.UserType==3,cls.id==current_user.id))
            session.close()
        else:
            records = Record.getRecordList(TableClass)
        return records

    @classmethod
    def canUserCreate(self):
        if current_user.UserType in (0, 1, 2):
            return True

    @classmethod
    def canUserDelete(self):
        if current_user.UserType == 0:
            return True

    @classmethod
    def canUserEdit(self, record):
        if current_user.id == record.id:
            return True
        elif record.UserType == None:
            return True
        elif current_user.UserType < record.UserType:
            return True
            return False

    @classmethod
    def getUserFieldsReadOnly(cls, record, fieldname):
        if fieldname == "Favorite":
            return
        if record and record.id == current_user.id:
            return
        if current_user.UserType == 1:
            if record and record.UserType == 3:
                return 1  #solo insertar nuevos
        if current_user.UserType == 2:
            if record and record.UserType in (0, 1, 2):
                return 2  #nunca
            if record and record.UserType == 3:
                return 1  #solo insertar nuevos

    @classmethod
    def customGetFieldsDefinition(cls, record, res):
        if record and record.id == current_user.id:
            res['UserType']['Hidde'] = True
        return res

    def getFavorite(self):
        from dondefluir.db.UserFavorite import UserFavorite
        session = Session()
        record = session.query(UserFavorite).filter_by(
            UserId=current_user.id, FavoriteId=self.id).first()
        if record and record.Checked:
            return 1
        return 0

    def getField(self, fieldname):
        if getattr(self, fieldname): return getattr(self, fieldname)
        elif self.CompanyId:
            compay = Company.getRecordById(self.CompanyId)
            if company and getattr(company, fieldname):
                return getattr(company, fieldname)

    @classmethod
    def getRecordTitle(self):
        return ['Name']