# -*- coding: utf-8 # Copyright 2006 by Meelis Mets from Products.Archetypes.public import BaseSchema, Schema from Products.Archetypes.public import StringField, LinesField, DateTimeField, TextField, BooleanField, ComputedField from Widgets import TwoWayReferenceField from Products.Archetypes.public import LinesWidget, TextAreaWidget, IdWidget, StringWidget, SelectionWidget, CalendarWidget, RichWidget, ReferenceWidget, BooleanWidget, ComputedWidget from Products.Archetypes.public import BaseContent, OrderedBaseFolder, registerType from Globals import InitializeClass from Products.CMFCore.utils import getToolByName from AccessControl import ClassSecurityInfo, Unauthorized from config import PROJECT_NAME from Permissions import * import re schema = BaseSchema + Schema(( TwoWayReferenceField('listOfReferences', required = False, searchable = False, relationship = 'competency references', accessor = 'getListOfReferences', mutator = 'setListOfReferences', widget = ReferenceWidget( visible = {'view':'invisible', 'edit':'invisible'}, ), ), )) base_schema = schema + Schema(( TextField('description', accessor='getDescription', validators = ('isTidyHtmlWithCleanup',), default_output_type = 'text/x-html-safe', allowable_content_types = ('text/html',), widget = RichWidget( label="Description", description="", label_msgid='label_description', description_msgid='description_description', visible={'view':'visible','edit':'visible'}, i18n_domain="eportfolio", rows = 10 ), ), )) competencies_schema = base_schema competency_standard_schema = schema + Schema(( TextField('staticbody', accessor='getStaticBody', validators = ('isTidyHtmlWithCleanup',), default_output_type = 'text/x-html-safe', allowable_content_types = ('text/html',), widget = RichWidget( label="Static body", description="This is static body, you can create competencis page view here or use dynamically generated body. Dynamically generated body will be shown if 'Use this static body' option below are checked.", label_msgid='label_staticbody', description_msgid='description_staticbody', visible={'view':'visible','edit':'visible'}, i18n_domain="eportfolio", rows = 10 ), ), BooleanField('usestaticbody', accessor = 'getUseStaticBody', widget = BooleanWidget( label = 'Use this static body', label_msgid = 'label_usestaticbody', description = '', description_msgid = 'desc_usestaticbody', visible = {'view': 'invisible', 'edit':'visible'}, i18n_domain="eportfolio" ), ), BooleanField('usedynamicbody', accessor = 'getUseDynamicBody', widget = BooleanWidget( label = 'Use dynamic body', label_msgid = 'label_usedynamicbody', description = '', description_msgid = 'desc_usedynamicbody', visible = {'view': 'invisible', 'edit':'visible'}, i18n_domain="eportfolio" ), ), )) competency_group_schema = base_schema + Schema(( BooleanField('plainText', accessor = 'getPlainText', widget = BooleanWidget( label = 'Plain text', label_msgid = 'label_plaintext', description = 'Check if this object is only title or subtitle with description not a competency', description_msgid = 'desc_plaintext', visible = {'view': 'invisible', 'edit':'visible'}, i18n_domain="eportfolio" ), ), ComputedField('competencystandardid', accessor='getCompetencyStandardId', searchable=1, index='KeywordIndex:schema', widget = ComputedWidget( label="Competency standard id", visible = {'view':'invisible', 'edit':'invisible'} ), ), ComputedField('competencystandardtitle', accessor='getCompetencyStandardTitle', searchable=1, index='KeywordIndex:schema', widget = ComputedWidget( label="Competency standard title", visible = {'view':'invisible', 'edit':'invisible'} ), ), )) competency_schema = base_schema class CompetencyManager(BaseContent): """ User's competency manager """ meta_type = "CompetencyManager" archetype_name = "CompetencyManager" global_allow = 0 allowed_content_types = () security = ClassSecurityInfo() schema = schema actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/user_competency_manager', 'permissions': ('View',), }, { 'id':'edit', 'name':'Edit', 'action':'string:${object_url}/base_edit', 'permissions': ('Manage portal content',), }, { 'id':'metadata', 'name':'Properties', 'action':'string:${object_url}/base_metadata', 'permissions': ('Manage Portal',), }, ) def __init__(self, id): self.id = id self.largeIcon = "comp.gif" self._competency = {} self._competency_others = {} self.hidden_list = [] def getLargeIcon(self): """ returns large icon name """ return self.largeIcon def getHiddenList(self): """ returns hiddenlist """ if not hasattr(self,'hidden_list'): self.hidden_list = [] return self.hidden_list def addToHiddenList(self, id): """add cs to hidden list""" if not id in self.hidden_list: self.hidden_list.append(id) self._p_changed = 1 return self.REQUEST.RESPONSE.redirect(self.absolute_url()) def removeFromHiddenList(self, REQUEST): """remove cs from hidden list""" ids = REQUEST.get('com_for_showing') css = self.getCompetencyStandards() new_hidden_list = [] old_hidden_list = self.getHiddenList() if ids: if isinstance(ids,str): ids = [ids] else: ids = [] for cs in css: if cs.id not in ids: new_hidden_list.append(cs.id) self.hidden_list = new_hidden_list self._p_changed = 1 return self.REQUEST.RESPONSE.redirect(self.absolute_url()+'/preferences_view') def getCompetencyStandards(self): """ returns a competency tree """ cc = getattr(self.aq_parent.aq_parent, 'competency') return cc.objectValues('CompetencyStandard') def getCompetencyTree(self): """ returns a competency tree """ cc = getattr(self.aq_parent.aq_parent, 'competency') msg = '' level = 0 for c in cc.objectValues('CompetencyStandard'): if not c.id in self.getHiddenList(): msg += self._competencyHelper(c, '', level+1) return msg def _competencyHelper(self, obj, msg, level): next_objects = obj.objectValues('CompetencyGroup') has_competencies = obj.objectValues('Competency') display = 'none' if level == 1 or level == 2: display = 'block' msg += '
' % (display, str(level)) if self.isPlainText(obj): msg += '

'+obj.Title()+'

' msg += '

'+obj.getDescription()+'

' else: if level>1: if next_objects: msg += '' if has_competencies: msg += ''+obj.Title()+'' else: msg += ''+obj.Title()+'' msg += '

'+obj.getDescription()+'

' if level==1: msg += ''+obj.Title()+'' if str(self.Creator())==str(self.REQUEST.get('AUTHENTICATED_USER')): trs = getToolByName(self, 'translation_service') msg += ' ['+trs.utranslate('eportfolio', 'Hide', self, self).encode('utf-8')+']' if obj.getUseDynamicBody(): msg += '
'+obj.getStaticBody() for c in next_objects: msg += self._competencyHelper(c, '', level+1) msg += '
' return msg def isPlainText(self, obj): """is object a cempetency""" if hasattr(obj, 'getPlainText'): return obj.getPlainText() return False def getGradeFor(self, uid): try: return self._competency[uid]['grade'] except KeyError: pass return -1 def getSelfCommentFor(self, uid): try: return self._competency[uid]['comment'] except KeyError: pass return "" def getTitleFor(self, uid): rc = getToolByName(self, 'uid_catalog') obj = rc(UID=str(uid)) if len(obj)==0: return "error" return obj[0].Title def getDescFor(self, uid): rc = getToolByName(self, 'uid_catalog') obj = rc(UID=str(uid)) if len(obj)==0: return "error" return obj[0].getObject().getDescription() def getCompetenciesFor(self, uid): """ cet competencies """ rc = getToolByName(self, 'uid_catalog') obj = rc(UID=str(uid)) if len(obj)==0: return "error" return obj[0].getObject().objectValues('Competency') def getOthersCommentFor(self, uid): # self._competency_others[uid][user][tm]([grade, comment]) res = [] try: u = self._competency_others[uid] except: return [] for x in u.keys(): for y in u[x].keys(): res.append([y, x, u[x][y]['grade'], u[x][y]['comment']]) return res security.declareProtected(MODIFY_CONTENT, 'saveComments') def saveComments(self, REQUEST): """ saving grades and comments """ comp_uid = REQUEST.get('comp_uid', None) if comp_uid is None: raise 'Something wrong?? Cant find buttons?' gr = int(REQUEST.get('hinnang', -1)) if not self._competency.has_key(comp_uid): self._competency[comp_uid] = {} self._competency[comp_uid]['grade'] = gr com = REQUEST.get('comp_comm', '') self._competency[comp_uid]['comment'] = com self._p_changed = True return REQUEST.RESPONSE.redirect(self.absolute_url()) def other_saveComments(self, REQUEST): """ saving others opinion """ user = str(REQUEST.get('AUTHENTICATED_USER')) comp_uid = REQUEST.get('comp_uid', None) if comp_uid is None: raise 'Something wrong?? Cant find buttons?' gr = int(REQUEST.get('hinnang', -1)) com = REQUEST.get('comp_comm', '') import time tm = time.time() if not self._competency_others.has_key(comp_uid): self._competency_others[comp_uid] = {} if not self._competency_others[comp_uid].has_key(user): self._competency_others[comp_uid][user] = {} self._competency_others[comp_uid][user][tm] = {'grade':gr, 'comment':com} self._p_changed = True return REQUEST.RESPONSE.redirect(self.absolute_url()) def reflectCompetency(self,REQUEST): """reflects competency""" self.makeNewPlogEntry(REQUEST, "Self-estimate", "reflection") def planCompetency(self,REQUEST): """reflects competency""" self.makeNewPlogEntry(REQUEST, "Goal", "plan") def makeNewPlogEntry(self,REQUEST,category,type): user = str(REQUEST.AUTHENTICATED_USER) homefolder = self.portal_membership.getHomeFolder(user) blog_ob = getattr(homefolder, 'blog') comp_uid = REQUEST.get('comp_uid') rc = getToolByName(self, 'uid_catalog') comp_obj = rc(UID=str(comp_uid)) if not len(comp_obj)==0: nr = 1 while hasattr(blog_ob,str(comp_obj[0].id)+'-'+type+'-'+str(nr)): nr = nr + 1 comp_id = str(comp_obj[0].id)+'-'+type+'-'+str(nr) #trs = getToolByName(self, 'translation_service') #comp_title = trs.utranslate('eportfolio', 'Titleless', self, self) comp_title = '' if not hasattr(blog_ob, comp_id): from Blog import BlogEntry entry = BlogEntry(comp_id) blog_ob._setObject(entry.id, entry) entry_ob=getattr(blog_ob,entry.id) entry_ob.setTitle(comp_title) entry_ob.categories=(category,) #entry_ob.setRefToTask(self.UID()) entry_ob.reindexObject() else: entry_ob = getattr(blog_ob,comp_id) return REQUEST.RESPONSE.redirect(entry_ob.absolute_url()+'/edit') return REQUEST.RESPONSE.redirect(self.absolute_url()) def getCompetencyData(self): """get reflection""" data = {'plans':[],'reflections':[]} owner = self.Creator() homefolder = self.portal_membership.getHomeFolder(owner) blog_ob = getattr(homefolder, 'blog') comp_uid = self.REQUEST.get('show') rc = getToolByName(self, 'uid_catalog') comp_obj = rc(UID=str(comp_uid)) if not len(comp_obj)==0: for entry in blog_ob.objectValues('BlogEntry'): good_for_refl = False good_for_plans = False if str(comp_obj[0].id)+'-reflection-' in entry.id: good_for_refl = True if str(comp_obj[0].id)+'-plan-' in entry.id: good_for_plans = True if entry.getBody(): body = re.sub('<.*?>', '', entry.getBody()).strip() if not body: # it doesn't have a body, we'll skip this one good_for_refl = good_for_plans = False if good_for_plans: data['plans'].append(entry) if good_for_refl: data['reflections'].append(entry) return data def get_n_of_other(self, uid): """ how many comments by other users... """ try: u = self._competency_others[uid] except KeyError: return 0 count = 0 for x in u.keys(): count += len(u[x].keys()) return count def getReferencesToObjects(self, uid, type): """ Gives list of references """ # STRUCTURE [[Competency UID, Type, Object UID],...] res = [] field = self.Schema().get('listOfReferences') uc = getToolByName(self, 'uid_catalog') references = field.getValue(self) #Throw out unneeded rererences temp_references = [] for reference in references: results = uc(UID=reference[2]) if results: temp_references.append(reference) print "TO TEMP_REFERENCES:", temp_references print "TO REFERENCES:", references field.setValue(self, temp_references) for reference in temp_references: if reference[1] == type and reference[0] == uid: results = uc(UID=reference[2]) brain = results[0] object = brain.getObject() res.append(object) return res def getReferencesForObject(self, uid): """ Gives competency references for object """ res = [] field = self.Schema().get('listOfReferences') uc = getToolByName(self, 'uid_catalog') references = field.getValue(self) # Throw out the unneeded references temp_references = [] for reference in references: results = uc(UID=reference[0]) if results: temp_references.append(reference) print "FOR TEMP_REFERENCES:", temp_references print "FOR REFERENCES:", references field.setValue(self, temp_references) for reference in temp_references: if reference[2] == uid: results = uc(UID=reference[0]) brain = results[0] object = brain.getObject() res.append(object) return res def setReferencesToObjects(self, REQUEST): """ Sets list of references """ uid = REQUEST.get('competency_uid') type = REQUEST.get('object_type') objects = REQUEST.get('object_uid') res = [] field = self.Schema().get('listOfReferences') existing = field.getValue(self) # Deleting same type and competency UID elements before add temporary = [] for x in existing: if x[0] == uid and x[1] == type: pass else: temporary.append(x) res = temporary if objects: for object in objects: newObject = [] newObject.append(uid) newObject.append(type) newObject.append(object) res.append(newObject) field.setValue(self, res) return REQUEST.RESPONSE.redirect(self.absolute_url()+'/competency?show='+uid) def setReferencesForAnswers(self, answer_uid, competencies): """ Sets competencies for answer based on competencies for tasks """ type = 'task' comp_uids = [] res = [] for competency in competencies: comp_uids.append(competency.UID()) field = self.Schema().get('listOfReferences') existing = field.getValue(self) # As this operation can only be done when answer is created - there is not need for checking the duplicates. res = existing if comp_uids: for comp in comp_uids: newCompetency = [] newCompetency.append(comp) newCompetency.append(type) newCompetency.append(answer_uid) res.append(newCompetency) field.setValue(self, res) #def setReferencesForEntry(self, competency_uid, entry): # """ Sets competencies for answer based on competencies for tasks """ # type = 'entry' # res = [] # field = self.Schema().get('listOfReferences') # existing = field.getValue(self) # res = existing # if competency_uid: # newCompetency = [] # newCompetency.append(comp) # newCompetency.append(type) # newCompetency.append(answer_uid) # res.append(newCompetency) # # field.setValue(self, res) def setReferencesFromObjects(self, REQUEST): """ Sets list of references from object """ uid = REQUEST.get('object_uid') type = REQUEST.get('object_type') competencies = REQUEST.get('competency_uid') redirectng_url = REQUEST.get('previous_url') res = [] field = self.Schema().get('listOfReferences') existing = field.getValue(self) # Deleting same etype and objec UID elements before add temporary = [] for x in existing: if x[2] == uid and x[1] == type: pass else: temporary.append(x) res = temporary if competencies: for competency in competencies: newCompetency = [] newCompetency.append(competency) newCompetency.append(type) newCompetency.append(uid) res.append(newCompetency) field.setValue(self, res) return REQUEST.RESPONSE.redirect(redirectng_url) def checkObjectLinked(self, competency_uid, type, object_uid): """ Checks if object is linked """ field = self.Schema().get('listOfReferences') references = field.getValue(self) tested = [] tested.append(competency_uid) tested.append(type) tested.append(object_uid) if tested in references: checked = True else: checked = False return checked #def cleanUpReferences(self): # """ Deletes all references """ # field = self.Schema().get('listOfReferences') # empty_mass = [] # field.setValue(self, empty_mass) registerType(CompetencyManager, PROJECT_NAME) class Competencies(OrderedBaseFolder): """ contains competencies """ meta_type = "Competencies" archetype_name = "Competencies" global_allow = 0 allowed_content_types = ('CompetencyStandard',) filter_content_types = True security = ClassSecurityInfo() schema = competencies_schema largeIcon = 'forms.gif' actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/competencies_view', 'permissions': ('View',), }, ) def getCompetencyTree(self): """ returns a competency tree """ msg = '' level = 0 for c in self.objectValues('CompetencyStandard'): msg += self._competencyHelper(c, '', level+1) return msg def _competencyHelper(self, obj, msg, level): msg += '
' user = str(self.REQUEST.AUTHENTICATED_USER) member = self.portal_membership.getMemberById(user) if self.isPlainText(obj) and 'Manager' not in member.getRolesInContext(self): msg += '

'+obj.Title()+'

' else: msg += ''+obj.Title()+'' msg += '

'+obj.getDescription()+'

' msg += '
' for c in obj.objectValues('CompetencyGroup'): msg += self._competencyHelper(c, '', level+1) return msg def isPlainText(self, obj): """is object a cempetency""" if hasattr(obj, 'getPlainText'): return obj.getPlainText() return False def getCompetencyStandards(self): """competency standards""" return self.objectValues('CompetencyStandard') registerType(Competencies, PROJECT_NAME) class CompetencyStandard(Competencies): """ Competency Standard """ _at_rename_after_creation = True meta_type = "CompetencyStandard" archetype_name = "Competency Standard" global_allow = 0 allow_discussion = True allowed_content_types = ('CompetencyGroup',) security = ClassSecurityInfo() schema = competency_standard_schema largeIcon = 'forms.gif' actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/competency_standard_view', 'permissions': ('View',), }, ) def getCompetencyTree(self): """ returns a competency tree """ msg = '' level = 0 for c in self.objectValues('CompetencyGroup'): msg += self._competencyHelper(c, '', level+1) return msg def getCompetencyStandardIdFrom(self): """competency standard""" return self.id def getCompetencyStandardTitleFrom(self): """competency standard""" return self.Title() registerType(CompetencyStandard, PROJECT_NAME) class CompetencyGroup(OrderedBaseFolder): """ Competency group, can contain competency """ _at_rename_after_creation = True meta_type = "CompetencyGroup" archetype_name = "Competency Group" global_allow = 0 allow_discussion = True allowed_content_types = ('Competency','CompetencyGroup') security = ClassSecurityInfo() schema = competency_group_schema largeIcon = 'forms.gif' actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/competency_group_view', 'permissions': ('View',), }, ) def getCompetencies(self): """return all competencies""" return self.objectValues('Competency') def getCompetencyStandardId(self): """competency standard""" return self.getCompetencyStandardIdFrom() def getCompetencyStandardTitle(self): """competency standard""" return self.getCompetencyStandardTitleFrom() def checkRedirect(self, REQUEST): """ check if user is coming from his portfolio, if yes then redirect back """ refer = REQUEST.get('HTTP_REFERER', None) if 'Members' in refer: user = str(REQUEST.AUTHENTICATED_USER) hf = self.portal_membership.getHomeFolder(user) c = getattr(hf, 'competency') return REQUEST.RESPONSE.redirect(c.absolute_url()+'?show='+self.UID()) registerType(CompetencyGroup, PROJECT_NAME) class Competency(BaseContent): """ One Competency, can contain itself again """ #_at_rename_after_creation = True meta_type = "Competency" archetype_name = "Competency" global_allow = 0 allow_discussion = True allowed_content_types = () security = ClassSecurityInfo() schema = competency_schema largeIcon = 'forms.gif' def kalakala(self): """ asd """ return "ok" registerType(Competency, PROJECT_NAME)