def userupdate(event): """ Handler for User Login in Site """ tools = UtilMyvindula() user_login = tools.membership.getAuthenticatedMember() # alert_first_access = tools.site.restrictedTraverse('@@myvindula-conf-userpanel').check_alert_first_access() # enable_chat = tools.site.restrictedTraverse('vindula-chat-config').enableConf() user_schema = ModelsDadosFuncdetails() user_id = tools.Convert_utf8(user_login.getUserName()) #Procurando perfil do usuario user_instance = ModelsDadosFuncdetails().get_DadosFuncdetails_byInstance(user_id) #Se nao tiver perfil, cria o perfil if not user_instance: dados = {u'username':user_id, u'email':user_login.getProperty('email'), u'name':user_id} if user_login.getProperty('fullname'): dados['name'] = user_login.getProperty('fullname') user_schema.createUserProfile(dados) # else: # user_data = tools.get_prefs_user(user_id) # if ((not user_data.get('name')) or (not user_data.get('date_birth')) or\ # (not user_data.get('phone_number')) or (not user_data.get('email'))): # tools.setLogger('info',"Dados Incompletos no myvindula")
def __init__(self, username, *args, **kwargs): self.username = username self.fields = ModelsConfgMyvindula().get_configurationAll() self.fields_private = self.fields.find(ativo_onlyuser=True) redis_conn = get_redis_connection() key = 'vindula:user-profile:%s' % username if redis_conn.hmget(key,'username')[0] != None: for field in redis_conn.hkeys(key): setattr(self,field,redis_conn.hmget(key,field)[0]) del(redis_conn) else: if self.fields.count() > 0: user_data = ModelsDadosFuncdetails().get_DadosFuncdetails_byInstance(self.username) for field in self.fields: value = user_data.get(field.name) if field.type == 'BooleanField': if value == 'on': value = True else: value = False setattr(self, field.name,value) continue #TODO: Verificar pq isso esta acontecendo if not isinstance(self.username,unicode) and not isinstance(self.username,str): self.username = self.username.username
def is_deleted(self): username = self.username if username and isinstance(username, str): username = self.username.decode('utf-8') data = ModelsDadosFuncdetails().store.find(ModelsDadosFuncdetails, ModelsDadosFuncdetails.username==self.username.decode('utf-8')) L_field = [] for field in data: if field.deleted == True: L_field.append(True) if len(L_field) == data.count(): return True return False
def getValuesByFieldName(self, field_name, is_object=False): values = ModelsDadosFuncdetails.get_DadosFuncdetails_byFieldName(field_name) items = {} for value in values: if is_object: try: value = eval(value.value) value = value[0] except (SyntaxError, NameError): value = value.value value = uuidToObject(value) else: value = value.value if items.get(value): items[value] += 1 else: items[value] = 1 return items
def getValuesByFieldName(self, field_name, is_object=False, qtd=5): values = ModelsDadosFuncdetails.get_DadosFuncdetails_byFieldName(field_name) items = {} for value in values: if is_object: try: value = eval(value.value) value = value[0] except(SyntaxError, NameError): value = value.value value = uuidToObject(value) else: value = value.value if items.get(value): items[value] += 1 else: items[value] = 1 od = OrderedDict(sorted(items.items(), key=lambda t: t[1])) items = od.items() items.reverse() items = OrderedDict(items[:qtd]) return items
def registration_processes(self,context,user,manage=False,delete=False): campos = {} lista_itens = {} if not isinstance(context, dict): if not context: context = getSite() form = context.request # var tipo 'dict' que guarda todas as informacoes do formulario (keys,items,values) form_keys = form.keys() # var tipo 'list' que guarda todas as chaves do formulario (keys) else: form = context form['name'] = form.get('fullname', form.get('username', None)) form['form.submited'] = ['Submited'] form_keys = form.keys() user_id = self.Convert_utf8(user) # id_instance = 0 # if user_id: # user_instance = ModelsInstanceFuncdetails().get_InstanceFuncdetails(user_id) # if not user_instance: # id_instance = ModelsInstanceFuncdetails().set_InstanceFuncdetails(user_id) # else: # id_instance = user_instance.id fields = ModelsConfgMyvindula().get_configurationAll() if fields: for field in fields: M={} M['required'] = field.required M['type'] = field.type M['label'] = field.label M['decription'] = field.decription M['ordem'] = field.order_position M['mascara'] = field.mask if field.type == 'img': M['instance_id'] = user_id campos[field.name] = M if field.type == 'choice' or\ field.type == 'list': items = field.choices.splitlines() valores=[] # TODO: Otimizar este codigo, podemos dizer que estah muito lento e incorreto. for i in items: if i == "###unidadesorganizacionais###": unidades = self.get_unidade_organizacional_text() for unidade in unidades: valores.append([unidade[0],unidade[1]]) else: valores.append([i, i]) lista_itens[field.name] = valores conf = {} for item in campos.keys(): try: conf[item] = ModelsConfgMyvindula().getConfig_edit(item) except:conf[item] = True # divisao dos dicionarios "errors" e "convertidos" form_data = { 'errors': {}, 'data': {}, 'campos':campos, 'lista_itens':lista_itens, 'departametos': ModelsDepartment().get_department(), 'username' : user_id, 'config_myvindula':conf, 'manage':manage,} # se clicou no botao "Voltar" if 'form.voltar' in form_keys: if 'id_instance' in form_keys and isForm: context.request.response.redirect(success_url+'/view-form') else: context.request.response.redirect(getSite().portal_url() + '/@@usergroup-userprefs') # se clicou no botao "Salvar" elif 'form.submited' in form_keys: if not user_id: campos['username'] = {'required': True, 'type' : self.to_utf8, 'label':''} #Remove o campos departamento da validação if 'vin_myvindula_department' in campos.keys(): campos.pop('vin_myvindula_department') #Remove o campos img da validação camposAux = copy(campos) for item in camposAux: D = camposAux[item] if D.get('type') == 'img': campos.pop(item) # Inicia o processamento do formulario # chama a funcao que valida os dados extraidos do formulario (valida_form) if not isinstance(context, dict): form = context.request.form else: form = context errors, data = valida_form_dinamic(context, campos, form) if not errors: # if not user_id: # id_instance = ModelsInstanceFuncdetails().set_InstanceFuncdetails(data.get('username')) # user_id = data.get('username') # data.pop('username') if 'vin_myvindula_department' in form_keys or 'departaments_old' in form_keys: L = [] ModelsDepartment().del_department(user_id) portalGroup = getSite().portal_groups portalCatalog = getSite().portal_catalog if form.get('vin_myvindula_department', None): if not type(form.get('vin_myvindula_department', None)) == list: L.append(form.get('vin_myvindula_department', None)) else: L = form.get('vin_myvindula_department', None) deparataments_old = form.get('departaments_old', []) #Adiciona o usuario do grupo da estrutura organizacional dep_adicionados = set(L) - set(deparataments_old) for departament in dep_adicionados: D={} D['UID'] = unicode(departament,'utf-8') D['funcdetails_id'] = user_id ModelsDepartment().set_department(**D) obj_org = portalCatalog(portal_type='OrganizationalStructure', UID=departament) if obj_org: obj_org = obj_org[0].getObject() #Adiciona o usuário no campo Employees if user_id not in obj_org.getEmployees(): tuple_employees = list(obj_org.employees) tuple_employees.append(user_id) obj_org.employees = tuple(tuple_employees) #Adiciona o usuário no campo Permissao de Visualizacao if user_id not in obj_org.getGroups_view(): tuple_Groups_view = list(obj_org.Groups_view) tuple_Groups_view.append(user_id) obj_org.Groups_view = tuple(tuple_Groups_view) if user_id not in portalGroup.getGroupById(departament+'-view').getAllGroupMemberIds(): portalGroup.getGroupById(departament+'-view').addMember(user_id) #Exclui o usuario do grupo da estrutura organizacional dep_excluidos = set(deparataments_old) - set(L) for departament in dep_excluidos: ModelsDepartment().del_department(user=unicode(user_id), depUID=unicode(departament,'utf-8')) obj_org = portalCatalog(portal_type='OrganizationalStructure', UID=departament) if obj_org: obj_org = obj_org[0].getObject() if user_id != obj_org.getManager(): #Removendo o usuário no campo Employees if user_id in obj_org.getEmployees(): tuple_employees = list(obj_org.employees) tuple_employees.remove(user_id) obj_org.employees = tuple(tuple_employees) #Removendo o usuário no campo Permissao de Visualizacao if user_id in obj_org.getGroups_view(): tuple_Groups_view = list(obj_org.Groups_view) tuple_Groups_view.remove(user_id) obj_org.Groups_view = tuple(tuple_Groups_view) if user_id in portalGroup.getGroupById(departament+'-view').getAllGroupMemberIds(): portalGroup.getGroupById(departament+'-view').removeMember(user_id) else: self.setStatusMessage("error","O usuário é gestor do departamento %s, ele não pode ser removido." % obj_org.Title()) self.setRedirectPage('/@@user-information?userid='+user_id) form_data['errors'] = errors form_data['data'] = data return form_data for item in data.keys(): field_name = self.Convert_utf8(item) valor = data[item] result_campo = ModelsDadosFuncdetails().get_DadosFuncdetails_byInstanceAndFieldName(user_id,field_name) if result_campo: result_campo.value = valor.strip() result_campo.date_modified = datetime.now() self.db.store.commit() else: if valor: D={} #D['vin_myvindula_instance_id'] = id_instance D['username'] = user_id D['field'] = field_name D['value'] = self.Convert_utf8(valor) ModelsDadosFuncdetails().set_DadosFuncdetails(**D) #Redirect back to the front page with a status message self.setStatusMessage("info","Perfil editado com sucesso.") if manage: self.setRedirectPage('/@@usergroup-userprefs') else: self.setRedirectPage('/myvindulalistuser') else: form_data['errors'] = errors form_data['data'] = data return form_data # se for um formulario de edicao elif user_id:# and id_instance: #data_value = ModelsInstanceFuncdetails().get_InstanceDadosFuncdetails(user_id) data_value = self.get_prefs_user(user_id) # D = {} # if data_value: # for campo in campos.keys(): # for data in data_value: # if data.vin_myvindula_confgfuncdetails_fields == campo: # D[campo] = data.valor data_value['vin_myvindula_department'] = ModelsDepartment().get_departmentByUsername(user_id) form_data['data'] = data_value return form_data else: return form_data
def get_FuncDetailsByField(fields={}, case_sensitive=False, if_empty_return_all=True): L_username = [] L_retorno = [] expressions = [] expression_name = [] campos = [] data = [] data_username = [] for item in fields.items(): field, value = item[0], item[1] if value: if field == 'name': if not isinstance(value, unicode): value = unicode(value, 'utf-8') expression_name += [ModelsDadosFuncdetails.value.like(value,case_sensitive=case_sensitive)] expression_name += [ModelsDadosFuncdetails.username.like(value,case_sensitive=case_sensitive)] else: if isinstance(value, list): for val in value: expressions += [ModelsDadosFuncdetails.value.like(unicode(val, 'utf-8'),case_sensitive=case_sensitive)] else: expressions += [ModelsDadosFuncdetails.value.like(unicode(value, 'utf-8'),case_sensitive=case_sensitive)] campos += [unicode(field, 'utf-8')] if campos and expressions: data = ModelsDadosFuncdetails().store.find(ModelsDadosFuncdetails, ModelsConfgMyvindula.name.is_in(campos), ModelsDadosFuncdetails.field_id==ModelsConfgMyvindula.id, ModelsDadosFuncdetails.deleted==False, Or(*expressions),) if expression_name: data_username = ModelsDadosFuncdetails().store.find(ModelsDadosFuncdetails, ModelsConfgMyvindula.name.is_in([u'name', u'nickname']), ModelsDadosFuncdetails.field_id==ModelsConfgMyvindula.id, ModelsDadosFuncdetails.deleted==False, Or(*expression_name),) if (data and data.count() > 0) or (data_username and data_username.count() > 0): L_username_aux = [] L_username_aux2 = [] for item in data: if not item.username in L_username_aux: L_username_aux.append(item.username) for item in data_username: if not item.username in L_username_aux2: L_username_aux2.append(item.username) #verifica se a busca foi feita tanto por nome quando pelos outros filtros if expressions and expression_name: if L_username_aux and L_username_aux2: for i in L_username_aux: if (i in L_username_aux2) and (i not in L_username): L_username.append(i) #verifica se a busca foi feita apenas por filtro elif expressions: L_username = L_username_aux #verifica se a busca foi feita apenas por nome e username else: L_username = L_username_aux2 elif if_empty_return_all: #Pegando os usuarios com distinct select = Select(ModelsDadosFuncdetails.username, ModelsDadosFuncdetails.deleted==False, distinct=True) data = ModelsDadosFuncdetails().store.execute(select) for item in data: L_username.append(item[0]) key = generate_cache_key('FuncDetails:get_FuncDetailsByField', L_retorno=str(L_username), fields=str(fields)) sorted_user_list = get_redis_cache(key) if not sorted_user_list: for user in L_username: L_retorno.append(FuncDetails(user)) sorted_user_list = sorted(L_retorno, key=por_name) try: set_redis_cache(key,'FuncDetails:get_FuncDetailsByField:keys',sorted_user_list,600) except: sorted_user_list = [i.username for i in L_retorno] set_redis_cache(key,'FuncDetails:get_FuncDetailsByField:keys',sorted_user_list,600) return sorted_user_list
def get_AllFuncUsernameList(filter=None,b_size=None,b_start=None,sorted_by=por_name,reverse=False,search_all_fields=True): #Nao usar o b_size, b_start #TODO: Consertar a forma que esta sendo ordenada a lista #TODO: Melhorar, ainda nao está bom, tempo melhorado de 11 para 2 sec key = generate_cache_key(domain='FuncDetails:get_AllFuncUsernameList', filter=filter, b_size=b_size, b_start=b_start, sorted_by=str(sorted_by), search_all_fields=str(search_all_fields)) L_username = get_redis_cache(key) if not L_username: L_username = [] L_retorno = [] if b_size != None and b_start != None: b_start = int(b_start) b_size = b_start + int(b_size) else: b_start = None b_size = None if filter: #Ajustando filtro para o caso de busca #por mais de uma palavra Ex: '%palavra1%palavra2%' filter = filter.split(' ') filter = '%'.join(filter) data = [] if search_all_fields: data = ModelsDadosFuncdetails().store.find(ModelsDadosFuncdetails, ModelsDadosFuncdetails.deleted==False, ModelsDadosFuncdetails.value.like('%'+filter+'%',case_sensitive=False)) else: #Faz a busca só pelos campos de NOME, EMAIL E APELIDO! fields = ModelsConfgMyvindula().store.find(ModelsConfgMyvindula, ModelsConfgMyvindula.deleted==False, ModelsConfgMyvindula.name.is_in([u'nickname', u'name', u'email'])) id_fields = [] for field in fields: id_fields.append(field.id) if id_fields: data = ModelsDadosFuncdetails().store.find(ModelsDadosFuncdetails, ModelsDadosFuncdetails.deleted==False, ModelsDadosFuncdetails.field_id.is_in(id_fields), ModelsDadosFuncdetails.value.like('%'+filter+'%',case_sensitive=False)) if data and data.count() > 0: for item in data: if not item.username in L_username: L_username.append(item.username) else: #Pegando os usuarios com distinct select = Select(ModelsDadosFuncdetails.username, ModelsDadosFuncdetails.deleted==False, distinct=True) data = ModelsDadosFuncdetails().store.execute(select) for item in data: L_username.append(item[0]) for user in L_username[b_start:b_size]: L_retorno.append(FuncDetails(user)) #O reverse é utilizado para quando se trata de um campo de DATA L_username = [i.username for i in sorted(L_retorno, key=sorted_by, reverse=reverse)] set_redis_cache(key,'FuncDetails:get_AllFuncUsernameList:keys',L_username,1800) return L_username
def get_AllFuncFakeList(filter=None): L_username = [] data = ModelsDadosFuncdetails().store.find(ModelsDadosFuncdetails) if filter: data = data.find(ModelsDadosFuncdetails.value.like('%'+filter+'%',case_sensitive=False)) return range(data.count())