def gen_class(klass, schema=None): """generats and registers the klass """ if schema is not None: klass.schema = schema.copy() registerType(klass, 'Archetypes') content_types, constructors, ftis = process_types(listTypes(), PKG_NAME)
def registerCriterion(criterion, orig=None, indices=()): if orig is not None: indices = criteria._criterionRegistry.indicesByCriterion( orig.meta_type) if isinstance(indices, str): indices = (indices,) indices = tuple(indices) if indices == (): indices = criteria.ALL_INDICES implementedBy = getattr( atct_ifaces.IATTopicCriterion, 'implementedBy', None) if implementedBy is None: # BBB Plone 3 implementedBy = ( atct_ifaces.IATTopicCriterion.isImplementedByInstancesOf) assert implementedBy(criterion) atapi.registerType(criterion, 'collective.formcriteria') crit_id = criterion.meta_type criteria._criterionRegistry[crit_id] = criterion criteria._criterionRegistry.portaltypes[ criterion.portal_type] = criterion criteria._criterionRegistry.criterion2index[crit_id] = indices for index in indices: value = criteria._criterionRegistry.index2criterion.get( index, ()) criteria._criterionRegistry.index2criterion[ index] = value + (crit_id,)
def test_handler(self): portal = self.layer['portal'] setRoles(portal, TEST_USER_ID, ['Manager']) login(portal, TEST_USER_NAME) portal.invokeFactory('Document', 'referenced') vocabulary = ReferenceableVocabulary(portal.referenced) ref_schema = ATDocument.schema.copy() + \ Schema( (StringField( name='folderCategory', enforceVocabulary=True, vocabulary=vocabulary, ), )) class WithReferencedField(ATDocument): schema = ref_schema registerType(WithReferencedField, 'p.a.referenceintegrity') from plone.app.referenceintegrity import vocabularies source = WithReferencedField('source') source = source.__of__(self.layer['portal']) source.initializeArchetype() vocabularies.modifiedArchetype(source, None) references = source.getReferences(relationship=vocabularyRelationship) self.assertEquals([portal.referenced], references)
def initialize(context): """ Zope 2 """ # Register AT Content-Types atapi.registerType(NavigationManager.NavigationManager, PROJECTNAME) atapi.registerType(NavigationItem.NavigationItem, PROJECTNAME) # Register custom content-types content_types, constructors, ftis = atapi.process_types( atapi.listTypes(PROJECTNAME), PROJECTNAME) # Initialize portal tools cmfutils.ToolInit( PROJECTNAME +' Tools', tools=(NavigationManager.NavigationManager,), icon='tool.gif' ).initialize(context) cmfutils.ContentInit( PROJECTNAME + ' Content', content_types=content_types, permission="Add portal content", extra_constructors=constructors, fti=ftis).initialize(context)
def register(): """ Register custom widgets and content-types """ registerWidget(EEAReferenceBrowserWidget, title='EEA Reference Browser', description=(('Reference widget that allows you to browse ' 'or search the portal for objects to refer to.')), used_for=('Products.Archetypes.Field.ReferenceField',)) registerType(EEARefBrowserDemo, PROJECTNAME)
def afterSetUp(self): ATSiteTestCase.afterSetUp(self) atapi.registerType(Dummy, 'Archetypes') content_types, constructors, ftis = atapi.process_types(atapi.listTypes(), PKG_NAME) portal = self.portal dummy = Dummy(oid='dummy') # put dummy in context of portal dummy = dummy.__of__(portal) portal.dummy = dummy dummy.initializeArchetype() self._dummy = dummy
def afterSetUp(self): ATSiteTestCase.afterSetUp(self) registerType(Dummy, "Archetypes") content_types, constructors, ftis = process_types(listTypes(), PKG_NAME) portal = self.portal dummy = Dummy(oid="dummy") # put dummy in context of portal dummy = dummy.__of__(portal) portal.dummy = dummy dummy.initializeArchetype() self._dummy = dummy
def initialize(context): """Initializer called when used as a Zope 2 product. """ from eea.versions.tests.sample import content atapi.registerType(content.SampleData, config.PROJECTNAME) content_types, constructors, _ftis = atapi.process_types( atapi.listTypes(config.PROJECTNAME), config.PROJECTNAME) for atype, constructor in zip(content_types, constructors): utils.ContentInit('%s: %s' % (config.PROJECTNAME, atype.portal_type), content_types=(atype, ), permission=config.DEFAULT_ADD_CONTENT_PERMISSION, extra_constructors=(constructor,), ).initialize(context)
def register(self, criterion, indices): if type(indices) is StringType: indices = (indices,) indices = tuple(indices) if indices == (): indices = ALL_INDICES assert IATTopicCriterion.implementedBy(criterion) registerType(criterion, PROJECTNAME) crit_id = criterion.meta_type self[crit_id] = criterion self.portaltypes[criterion.portal_type] = criterion self.criterion2index[crit_id] = indices for index in indices: value = self.index2criterion.get(index, ()) self.index2criterion[index] = value + (crit_id,)
items[x]['ExpiryDate'] = "No date avaliable" else: items[x]['ExpiryDate'] = data.asdatetime().strftime(self.date_format_short) if obj.isOutOfDate(): items[x]['WeeksToExpire'] = "Out of date" else: date = int(str(obj.getWeeksToExpire()).split(',')[0].split(' ')[0]) weeks,days = divmod(date,7) items[x]['WeeksToExpire'] = str(weeks)+" weeks"+" "+str(days)+" days" if obj.getMethod(): items[x]['Method'] = obj.getMethod().Title() items[x]['replace']['Method'] = "<a href='%s'>%s</a>" % \ (obj.getMethod().absolute_url(), items[x]['Method']) else: items[x]['Method'] = '' items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items schema = ATFolderSchema.copy() class Instruments(ATFolder): implements(IInstruments) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish = True, moveDiscussion = False) atapi.registerType(Instruments, PROJECTNAME)
{'id':'all', 'title': _('All'), 'columns': ['Name', 'Email', 'Phone', 'Fax']}, ] def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['Name'] = obj.getName() items[x]['Email'] = obj.getEmailAddress() items[x]['Phone'] = obj.getPhone() items[x]['Fax'] = obj.getFax() items[x]['replace']['Name'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Name']) return items schema = ATFolderSchema.copy() class ReferenceSuppliers(ATFolder): implements(IReferenceSuppliers) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish = True, moveDiscussion = False) atapi.registerType(ReferenceSuppliers, PROJECTNAME)
# Zope imports from zope.interface import implements # Archetypes imports from Products.Archetypes.atapi import OrderedBaseFolder from Products.Archetypes.atapi import registerType # easyshop imports from easyshop.core.config import PROJECTNAME from easyshop.core.interfaces import IGroupsContainer class GroupsContainer(OrderedBaseFolder): """A simple container to hold groups. """ implements(IGroupsContainer) registerType(GroupsContainer, PROJECTNAME)
GroupSpecialistSchema['imageReference'].storage = atapi.AnnotationStorage() schemata.finalizeATCTSchema(GroupSpecialistSchema, moveDiscussion=False) class GroupSpecialist(base.ATCTContent): """ @author: David Hietpas @version: 1.1 """ implements(IGroupSpecialist) meta_type = "GroupSpecialist" schema = GroupSpecialistSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') def listUsers(self): """ Returns a tuple listing of users for the Portal Catalog. @return: tuple """ return self.getField('listUsers').get(self) atapi.registerType(GroupSpecialist, PROJECTNAME)
from weka.content import contentMessageFactory as _ from weka.content.interfaces import IFeatureFolder from weka.content.config import PROJECTNAME FeatureFolderSchema = folder.ATFolderSchema.copy() + atapi.Schema(( # -*- Your Archetypes field definitions here ... -*- )) # Set storage on fields copied from ATFolderSchema, making sure # they work well with the python bridge properties. FeatureFolderSchema['title'].storage = atapi.AnnotationStorage() FeatureFolderSchema['description'].storage = atapi.AnnotationStorage() schemata.finalizeATCTSchema(FeatureFolderSchema, folderish=True, moveDiscussion=False) class FeatureFolder(folder.ATFolder): """A folder holding recommendations or features""" implements(IFeatureFolder) portal_type = "Feature Folder" schema = FeatureFolderSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') atapi.registerType(FeatureFolder, PROJECTNAME)
""" Return the current list of task types """ types = [ ('Calibration', safe_unicode(_('Calibration')).encode('utf-8')), ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')), ('Preventive', safe_unicode(_('Preventive')).encode('utf-8')), ('Repair', safe_unicode(_('Repair')).encode('utf-8')), ('Validation', safe_unicode(_('Validation')).encode('utf-8')) ] return DisplayList(types) def getCriteria(self): criteria = "" criterias = self.getScheduleCriteria() if criterias and len(criterias) > 0: crit = criterias[0] if crit['fromenabled'] == True and crit['fromdate']: criteria += _('From') + " " + crit['fromdate'] + " " if crit['repeatenabled'] == True and crit['repeatunit'] and crit[ 'repeatperiod']: criteria += _( "repeating every") + " " + crit['repeatunit'] + " " + _( crit['repeatperiod']) + " " if crit['repeatuntilenabled'] == True and crit['repeatuntil']: criteria += _("until") + " " + crit['repeatuntil'] return criteria atapi.registerType(InstrumentScheduledTask, PROJECTNAME)
(BaseSQLStorage, ()), (GadflySQLStorage, ()), (MySQLSQLStorage, ()), (PostgreSQLStorage, ()), ] PROJECTNAME = 'Archetypes.tests' #class EM(ExtensibleMetadata): pass #registerType(EM, PROJECTNAME) class BC(BaseContent): pass registerType(BC, PROJECTNAME) class BF(BaseFolder): pass registerType(BF, PROJECTNAME) class OBF(OrderedBaseFolder): pass registerType(OBF, PROJECTNAME)
), ), )) # class containing parameters related to how questions in a quiz are selected class BaseQuestionSelectionParameters(ATCTContent, HistoryAwareMixin): """Container for question selection parameters.""" schema = BaseQuestionSelectionParametersSchema _at_rename_after_creation = True security = ClassSecurityInfo() security.declarePrivate('tryWorkflowAction') def tryWorkflowAction(self, action, ignoreErrors=False, comment=None): """change the action on the lecture""" #wtool = getToolByName(self, 'portal_workflow') wtool = self.portal_workflow wf = wtool.getWorkflowsFor(self)[0] if wf.isActionSupported(self, action): if comment is None: #userId = getSecurityManager().getUser().getId() comment = 'State changed' wtool.doActionFor(self, action, comment=comment) elif not ignoreErrors: raise TypeError('Unsupported workflow action %s for object %s.' % (repr(action), repr(self))) atapi.registerType(BaseQuestionSelectionParameters, PROJECTNAME)
'title': _('All'), 'contentFilter': {}, 'columns': ['Title', 'getStartDate', 'getEndDate'] }, ] def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) items[x]['getStartDate'] = self.ulocalized_time(obj.getStartDate()) items[x]['getEndDate'] = self.ulocalized_time(obj.getEndDate()) return items schema = ATFolderSchema.copy() class EpidemiologicalYears(ATFolder): implements(IEpidemiologicalYears) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(EpidemiologicalYears, PROJECTNAME)
from Products.ATContentTypes.content import schemata from Products.Archetypes import atapi from baobab.lims.config import PROJECTNAME from plone.app.folder.folder import ATFolder, ATFolderSchema from zope.interface.declarations import implements from baobab.lims.interfaces import IVirusSamples schema = ATFolderSchema.copy() class VirusSamples(ATFolder): implements(IVirusSamples) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(VirusSamples, PROJECTNAME)
""" """ security = ClassSecurityInfo() implements(ICourse) meta_type = portal_type = 'FSDCourse' # moved schema setting after finalizeATCTSchema, so the order of the fieldsets # is preserved. Also after updateActions is called since it seems to overwrite the schema # changes. # Move the description field, but not in Plone 2.5 since it's already in the metadata tab. # Although, # decription and relateditems are occasionally showing up in the "default" schemata. Move them # to "metadata" just to be safe. if 'categorization' in Course_schema.getSchemataNames(): Course_schema.changeSchemataForField('description', 'categorization') else: Course_schema.changeSchemataForField('description', 'metadata') Course_schema.changeSchemataForField('relatedItems', 'metadata') _at_rename_after_creation = True schema = Course_schema # Methods security.declareProtected(View, 'getRemoteUrl') def getRemoteUrl(self): return self.website atapi.registerType(Course, config.PROJECTNAME) # end of class Course
from slc.seminarportal.config import PROJECTNAME SPSpeechVenueFolderSchema = folder.ATFolderSchema.copy() + atapi.Schema(( # -*- Your Archetypes field definitions here ... -*- )) # Set storage on fields copied from ATFolderSchema, making sure # they work well with the python bridge properties. SPSpeechVenueFolderSchema['title'].storage = atapi.AnnotationStorage() SPSpeechVenueFolderSchema['description'].storage = atapi.AnnotationStorage() schemata.finalizeATCTSchema(SPSpeechVenueFolderSchema, folderish=True, moveDiscussion=False) class SPSpeechVenueFolder(folder.ATFolder): """Folder containing Speech Venues""" implements(ISpeechVenueFolder) portal_type = "SPSpeechVenueFolder" schema = SPSpeechVenueFolderSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') atapi.registerType(SPSpeechVenueFolder, PROJECTNAME)
atapi.ReferenceField('related', relationship='related', multiValued=True, widget=atapi.ReferenceWidget(), keepReferencesOnCopy=True), atapi.ReferenceField('rel2', relationship='rel2', multiValued=True, widget=atapi.ReferenceWidget(), keepReferencesOnCopy=True), ), marshall=PrimaryFieldMarshaller()) + TemplateMixin.schema class DDocument(TemplateMixin, atapi.BaseContent): """An extensible Document (test) type""" schema = schema archetype_name = "Demo Doc" actions = TemplateMixin.actions def manage_afterPUT(self, data, marshall_data, file, context, mimetype, filename, REQUEST, RESPONSE): """For unit tests """ self.called_afterPUT_hook = True atapi.registerType(DDocument, PKG_NAME)
# Zope imports from zope.interface import implements # Archetypes imports from Products.ATContentTypes.content.folder import ATFolder from Products.Archetypes.atapi import registerType # easyshop imports from easyshop.core.config import PROJECTNAME from easyshop.core.interfaces import IFormatable from easyshop.core.interfaces import ISearchResultContainer class SearchResultContainer(ATFolder): """ """ implements(ISearchResultContainer, IFormatable) registerType(SearchResultContainer, PROJECTNAME)
# This name appears in the 'add' box archetype_name = 'Speech' meta_type = 'Speech' portal_type = 'Speech' allowed_content_types = [] + list( getattr(Highlight, 'allowed_content_types', [])) filter_content_types = 0 global_allow = 1 immediate_view = 'base_view' default_view = 'highlight_view' suppl_views = () typeDescription = "Speech" typeDescMsgId = 'description_edit_speech' _at_rename_after_creation = True schema = Speech_schema content_icon = 'speech_icon.gif' # LinguaPlone doesn't check base classes for mutators security.declareProtected(ModifyPortalContent, 'setThemes') def setThemes(self, value, **kw): """ Use the tagging adapter to set the themes. """ # value = filter(None, value) value = [val for val in value if val] tagging = IThemeTagging(self) tagging.tags = value registerType(Speech, PROJECTNAME)
# Zope imports from zope.interface import implements # Archetypes imports from Products.Archetypes.atapi import OrderedBaseFolder from Products.Archetypes.atapi import registerType # easyshop imports from easyshop.core.config import PROJECTNAME from easyshop.core.interfaces import IStockInformationContainer class StockInformationContainer(OrderedBaseFolder): """A simple container to hold stock information. """ implements(IStockInformationContainer) registerType(StockInformationContainer, PROJECTNAME)
description = atapi.ATFieldProperty('description') # -*- Your ATSchema to Python Property Bridges Here ... -*- institution = atapi.ATFieldProperty('institution') theme = atapi.ATFieldProperty('theme') commune = atapi.ATFieldProperty('commune') url = atapi.ATFieldProperty('url') fichier = atapi.ATFieldProperty('fichier') numero = atapi.ATFieldProperty('numero') date = atapi.ATFieldProperty('date') text = atapi.ATFieldProperty('text') document_type = atapi.ATFieldProperty('document_type') def getDefaultTime(self): # function to return the current date and time return DateTime() atapi.registerType(DocLegis, PROJECTNAME) def exclude_from_nav(obj, event): obj.setExcludeFromNav(True)
return DT2dt(value) def _end_date(self): value = self['startDate'] if value is None: return self.start_date return DT2dt(value) def _duration(self): return 0 #self.end_date - self.start_date """ Helpers to share interface with Events (and thus use vcs_view, ics_view et.al.) """ def getEventType(self): return ("Editors Meeting",) def event_url(self): return self.absolute_url() def contact_name(self): return None def contact_phone(self): return None def contact_email(self): return None atapi.registerType(EditorsMeeting, PROJECTNAME)
required=True, storage=atapi.AnnotationStorage(), widget=atapi.StringWidget( label=_(u'Year URI'), description=_(u'Uniform Resource Identifier for the year predicate.'), ), ), )) finalizeATCTSchema(PublicationSchema, folderish=False, moveDiscussion=True) class Publication(base.Source): '''Publication.''' implements(IPublication) portal_type = 'Publication' _at_rename_after_creation = True schema = PublicationSchema titleURI = atapi.ATFieldProperty('titleURI') descURI = atapi.ATFieldProperty('descURI') abstractURI = atapi.ATFieldProperty('abstractURI') authorURI = atapi.ATFieldProperty('authorURI') issueURI = atapi.ATFieldProperty('issueURI') journalURI = atapi.ATFieldProperty('journalURI') pmidURI = atapi.ATFieldProperty('pmidURI') pubURLURI = atapi.ATFieldProperty('pubURLURI') volumeURI = atapi.ATFieldProperty('volumeURI') yearURI = atapi.ATFieldProperty('yearURI') atapi.registerType(Publication, PROJECTNAME)
states.sort() return atapi.DisplayList(zip(states, states)) def getWorkflowTransitions(self): wf_trans = [] pw = getToolByName(self, 'portal_workflow') for wf_id in pw.getWorkflowIds(): wf = pw.getWorkflowById(wf_id) if not wf: continue for wf_tr in wf.transitions.values(): if wf_tr.after_script_name in AVAILABLE_WF_SCRIPTS: wf_trans.append( ("%s#%s" % (wf_id, wf_tr.id), "%s : %s (%s)" % (wf_id, wf_tr.id, wf_tr.title_or_id()))) return atapi.DisplayList(wf_trans) def setPingTransitions(self, value, **kw): """Add 'Ping sitemap' afterscript for selected workflow transitions. """ self.getField('pingTransitions').set(self, value) def setBlackout_list(self, value, **kw): """Clean-up whitespaces and empty lines.""" val = filter(None, map(string.strip, value)) self.getField('blackout_list').set(self, val) atapi.registerType(Sitemap, PROJECTNAME)
# Don't allow any context actions self.request.set("disable_border", 1) def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['Volume'] = obj.getVolume() items[x]['Unit'] = obj.getUnit() items[x]['Price'] = obj.getPrice() items[x]['VATAmount'] = obj.getVATAmount() items[x]['TotalPrice'] = obj.getTotalPrice() items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items schema = ATFolderSchema.copy() class LabProducts(ATFolder): implements(ILabProducts) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(LabProducts, PROJECTNAME)
'inactive_state': 'inactive' }, 'transitions': [ { 'id': 'activate' }, ], 'columns': ['Title', 'Description'] }) items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items schema = ATFolderSchema.copy() class SampleMatrices(ATFolder): implements(ISampleMatrices) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(SampleMatrices, PROJECTNAME)
(Pdb) self.UID() '2000b779359475adf1cd599ab3d5f96f' (Pdb) translation.UID() '2000b779359475adf1cd599ab3d5f96f' (Pdb) self == translation False (Pdb) type(self) <type 'ImplicitAcquirerWrapper'> (Pdb) type(translation) <type 'ImplicitAcquirerWrapper'> (Pdb) aq_inner(self) == aq_inner(translation) False (Pdb) aq_base(self) == aq_base(translation) True We override the if statement here and use aq_base to fix the problem and if necessary then call the original setLanguage method. """ translation = self.getTranslation(value) if self.hasTranslation(value): if aq_base(translation) == aq_base(self): return else: raise AlreadyTranslated, translation.absolute_url() super(SPSeminar, self).setLanguage(value) atapi.registerType(SPSeminar, PROJECTNAME)
"""Returns the total number of containers that belong to this facility """ return len(self.get_layout_containers()) def get_available_positions(self): """Returns the number of available containers """ return self.get_capacity() def get_layout_containers(self): """Returns the containers that belong to this facility and implement IStorageLayoutContainer """ return filter(lambda obj: IStorageLayoutContainer.providedBy(obj), self.objectValues()) def get_samples_capacity(self): """Returns the total number of samples this facility can store """ return sum(map(lambda con: con.get_samples_capacity(), self.get_layout_containers())) def get_samples_utilization(self): """Returns the total number of samples this facility actually stores """ return sum(map(lambda con: con.get_samples_utilization(), self.get_layout_containers())) registerType(StorageFacility, PRODUCT_NAME)
# # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright 2018-2019 by it's authors. # Some rights reserved, see README and LICENSE. """BatchFolder contains AR Batches. """ from AccessControl import ClassSecurityInfo from Products.ATContentTypes.content import schemata from Products.Archetypes import atapi from bika.lims.config import PROJECTNAME from bika.lims.interfaces import IBatchFolder, IHaveNoBreadCrumbs from plone.app.folder import folder from zope.interface import implements schema = folder.ATFolderSchema.copy() class BatchFolder(folder.ATFolder): implements(IBatchFolder, IHaveNoBreadCrumbs) schema = schema displayContentsTab = False security = ClassSecurityInfo() schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(BatchFolder, PROJECTNAME)
schemata.finalizeATCTSchema( CampaignSchema, folderish=False, moveDiscussion=False ) class Campaign(ATCTContent): """Monkey campaign""" implements(ICampaign) meta_type = "Campaign" schema = CampaignSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') @property def api_key(self): return self.getCampaign_api_key() @property def from_name(self): return self.getCampaign_from_name() @property def from_email(self): return self.getCampaign_from_email() atapi.registerType(Campaign, PROJECTNAME)
'columns': ['Title', 'Description']}, {'id': 'inactive', 'title': _('Dormant'), 'contentFilter': {'inactive_state': 'inactive'}, 'transitions': [{'id': 'activate'}, ], 'columns': ['Title', 'Description']} ] def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue items[x]['replace']['Title'] = \ "<a href='%s'>%s</a>" % (items[x]['url'], items[x]['Title']) return items schema = ATFolderSchema.copy() class SampleMatrices(ATFolder): implements(ISampleMatrices) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(SampleMatrices, PROJECTNAME)
If p_from_group_in_charge is True, we get certifiedSignatures from the first defined self.groupsInCharge.''' group_signatures = self.getField('certifiedSignatures').get( self, **kwargs) if computed: tool = api.portal.get_tool('portal_plonemeeting') cfg = tool.getMeetingConfig(context) computedSignatures = cfg.getCertifiedSignatures(computed=True) # get certified signatures from first of the defined groupsInCharge groups_in_charge = self.getGroupsInCharge() if from_group_in_charge and groups_in_charge: tool = api.portal.get_tool('portal_plonemeeting') group_in_charge = getattr(tool, groups_in_charge[0]) computedSignatures.update( computeCertifiedSignatures( group_in_charge.getCertifiedSignatures())) # if we have certified signatures defined on this MeetingGroup # update MeetingConfig signatures regarding what is defined here if group_signatures: computedSignatures.update( computeCertifiedSignatures(group_signatures)) # listify signatures, for backward compatibility, we need a list of pair # of function/name, like ['function1', 'name1', 'function2', 'name2'] group_signatures = listifySignatures(computedSignatures) return group_signatures registerType(MeetingGroup, PROJECTNAME)
'contentFilter': {'inactive_state': 'active'}, 'transitions': [{'id': 'deactivate'}, ], 'columns': ['Title', 'Description']}, {'id': 'inactive', 'title': _('Dormant'), 'contentFilter': {'inactive_state': 'inactive'}, 'transitions': [{'id': 'activate'}, ], 'columns': ['Title', 'Description']}] def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if 'obj' in items[x]: items[x]['replace']['Title'] = \ "<a href='%s'>%s</a>" % (items[x]['url'], items[x]['Title']) return items schema = ATFolderSchema.copy() class SampleConditions(ATFolder): implements(ISampleConditions) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(SampleConditions, PROJECTNAME)
)) CollageSchema = CollageSchema + CommonCollageSchema.copy() # move description to main edit page CollageSchema['description'].schemata = 'default' # support show in navigation feature and at marshalling # speciel case set folderish to False since we want related items to be used finalizeATCTSchema(CollageSchema, folderish=False, moveDiscussion=False) class Collage(LayoutContainer, ATCTMixin, atapi.OrderedBaseFolder): # FIXME: Do we always need Zope 2 style interfaces ? __implements__ = (getattr(atapi.OrderedBaseFolder,'__implements__',()), getattr(ATCTMixin, '__implements__',())) schema = CollageSchema _at_rename_after_creation = True security = ClassSecurityInfo() implements(ICollage, INonStructuralFolder) def SearchableText(self): return self.aggregateSearchableText() atapi.registerType(Collage, 'Collage')
exclude=exclude) security.declareProtected(View, 'selectedViewFields') def selectedViewFields(self): """ Get which metadata field are selected. Override as it is used by the tabular_view and there, we do not display the additional fields or it breaks the view.""" tool = getToolByName(self, ATCT_TOOLNAME) metadatas = [metadata.index for metadata in tool.getEnabledMetadata()] _mapping = {} for field in self.listMetaDataFields().items(): if not field[0] in metadatas: continue _mapping[field[0]] = field return [ _mapping[field] for field in self.customViewFields if field in metadatas ] security.declareProtected(View, 'selectedViewFields') def displayCatalogQuery(self): """ Return the stored query as a readable catalog query.""" return parseFormquery(self, self.query) registerType(DashboardCollection, PROJECTNAME)
""" Custom content-types """ from Products.CMFCore import utils as cmfutils from Products.Archetypes.atapi import process_types, listTypes from eea.progressbar.config import ( PROJECTNAME, ADD_CONTENT_PERMISSION ) from Products.Archetypes.atapi import registerType from eea.progressbar.content.tool import ProgressTool from eea.progressbar.content.contenttype import ProgressContentType registerType(ProgressTool, PROJECTNAME) registerType(ProgressContentType, PROJECTNAME) def initialize(context): """ Zope 2 """ content_types, constructors, ftis = process_types( listTypes(PROJECTNAME), PROJECTNAME) cmfutils.ToolInit(PROJECTNAME+' Tools', tools=[ProgressTool], icon='content/tool.png' ).initialize(context) cmfutils.ContentInit( PROJECTNAME + ' Content', content_types=content_types,
""" security = ClassSecurityInfo() schema = schema _at_rename_after_creation = True def initializeArchetype(self, **kwargs): """Overwritten hook """ atapi.BaseContent.initializeArchetype(self, **kwargs) def setEmail(self, value): """ """ self.email = value self.title = value # reindex to set title for catalog self.reindexObject() def Title(self): """Overwritten accessor for Title """ title_str = self.getEmail() if self['firstname'] or self['lastname']: title_str += ' - ' + ' '.join( [self.getLastname(), self.getFirstname()]) return title_str atapi.registerType(ENLSubscriber, config.PROJECTNAME)
(items[x]['url'], items[x]['Title']) if items[x]['ManagerEmail']: items[x]['replace']['ManagerEmail'] = "<a href='%s'>%s</a>"%\ ('mailto:%s' % items[x]['ManagerEmail'], items[x]['ManagerEmail']) return items schema = ATFolderSchema.copy() class Departments(ATFolder): implements(IDepartments) displayContentsTab = False schema = schema def getContacts(self): pc = getToolByName(self, 'portal_catalog') bc = getToolByName(self, 'bika_catalog') bsc = getToolByName(self, 'bika_setup_catalog') # fallback - all Lab Contacts pairs = [] for contact in bsc(portal_type = 'LabContact', inactive_state = 'active', sort_on = 'sortable_title'): pairs.append((contact.UID, contact.Title)) return DisplayList(pairs) schemata.finalizeATCTSchema(schema, folderish = True, moveDiscussion = False) atapi.registerType(Departments, PROJECTNAME)
else: items[x]['Owner'] = self.context.bika_setup.laboratory.Title() return items schema = ATFolderSchema.copy() class SamplePoints(ATFolder): implements(ISamplePoints) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(SamplePoints, PROJECTNAME) class ajax_SamplePoints(BrowserView): """ The autocomplete data source for sample point selection widgets. Returns a JSON list of sample point titles. Request parameters: - sampletype: if specified, it's expected to be the title of a SamplePoint object. Optionally, the string 'Lab: ' might be prepended, to distinguish between Lab and Client objects. - term: the string which will be searched against all SamplePoint titles.
items[x]['WeeksToExpire'] = _("Out of date") else: weeks, days = obj.getWeeksToExpire() weeks_to_expire = _("{} weeks and {} day(s)".format(str(weeks), str(days))) items[x]['WeeksToExpire'] = weeks_to_expire methods = obj.getMethods() urls = [] titles = [] for method in methods: url = method.absolute_url() title = method.Title() titles.append(title) urls.append("<a href='{0}'>{1}</a>".format(url, title)) items[x]["Methods"] = ", ".join(titles) items[x]["replace"]["Methods"] = ", ".join(urls) items[x]["replace"]["Title"] = "<a href='{0}'>{1}</a>".format( obj.absolute_url(), obj.Title()) return items schema = ATFolderSchema.copy() class Instruments(ATFolder): implements(IInstruments) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish = True, moveDiscussion = False) atapi.registerType(Instruments, PROJECTNAME)
# -*- Your Archetypes field definitions here ... -*- )) # Set storage on fields copied from ATFolderSchema, making sure # they work well with the python bridge properties. SectionSchema['title'].storage = atapi.AnnotationStorage() SectionSchema['description'].storage = atapi.AnnotationStorage() schemata.finalizeATCTSchema( SectionSchema, folderish=True, moveDiscussion=False ) class Section(folder.ATFolder): """A section of an issue in a journal""" implements(ISection) meta_type = "Section" schema = SectionSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') # -*- Your ATSchema to Python Property Bridges Here ... -*- atapi.registerType(Section, PROJECTNAME)
('getClientSampleID', _('Client Sample ID')), ('getSampleTypeTitle', _('Sample Type')), ('getSamplePointTitle', _('Sample Point')), ('getDateSampled', _('Date Sampled')), ('created', _('Date Created')), ('getDateReceived', _('Date Received')), ('getDatePublished', _('Date Published')), ('Creator', _p('Creator')), )) security.declareProtected(View, 'results') def results(self, batch=True, b_start=0, b_size=None, sort_on=None, brains=False, catalog_name='bika_catalog'): """Get results""" if sort_on is None: sort_on = self.getSort_on() if b_size is None: b_size = self.getLimit() return self.getQuery(batch=batch, b_start=b_start, b_size=b_size, sort_on=sort_on, brains=brains, catalog_name='bika_catalog') atapi.registerType(AnalysisRequestQuery, PROJECTNAME)
""" widget = self.getRejectionReasons() # widget will be something like: # [{'checkbox': u'on', 'textfield-2': u'b', 'textfield-1': u'c', 'textfield-0': u'a'}] if len(widget) > 0: checkbox = widget[0].get('checkbox', False) return True if checkbox == 'on' and len(widget[0]) > 1 else False else: return False def _getNumberOfRequiredVerificationsVocabulary(self): """ Returns a DisplayList with the available options for the multi-verification list: '1', '2', '3', '4' :return: DisplayList with the available options for the multi-verification list """ items = [(1, '1'), (2, '2'), (3, '3'), (4, '4')] return IntDisplayList(list(items)) def getIDServerValuesHTML(self): number_generator = getUtility(INumberGenerator) keys = number_generator.keys() values = number_generator.values() results = [] for i in range(len(keys)): results.append('%s: %s' % (keys[i], values[i])) return "\n".join(results) registerType(BikaSetup, PROJECTNAME)
"contentFilter": {"inactive_state": "inactive"}, "transitions": [{"id": "activate"}], "columns": ["Title", "Description"], }, {"id": "all", "title": _("All"), "contentFilter": {}, "columns": ["Title", "Description"]}, ] def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key("obj"): continue obj = items[x]["obj"] items[x]["Description"] = obj.Description() items[x]["replace"]["Title"] = "<a href='%s'>%s</a>" % (items[x]["url"], items[x]["Title"]) return items schema = ATFolderSchema.copy() class CaseSyndromicClassifications(ATFolder): implements(ICaseSyndromicClassifications) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(CaseSyndromicClassifications, PROJECTNAME)
'index': 'description', 'toggle': True}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter':{}, 'columns': ['Title', 'Description']}, ] def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) items[x]['Description'] = obj.Description() return items schema = ATFolderSchema.copy() class AttachmentTypes(ATFolder): implements(IAttachmentTypes) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish = True, moveDiscussion = False) atapi.registerType(AttachmentTypes, PROJECTNAME)
items[x]['Description'] = obj.Description() if obj.aq_parent.portal_type == 'Client': items[x]['Owner'] = obj.aq_parent.Title() else: items[x]['Owner'] = self.context.bika_setup.laboratory.Title() return items schema = ATFolderSchema.copy() class StorageLocations(ATFolder): implements(IStorageLocations) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish = True, moveDiscussion = False) atapi.registerType(StorageLocations, PROJECTNAME) class ajax_StorageLocations(BrowserView): """ The autocomplete data source for storage location selection widgets. Returns a JSON list of storage location titles. Request parameters: - term: the string which will be searched against all Storage Location titles. - _authenticator: The plone.protect authenticator. """ def filter_list(self, items, searchterm):
label=_("Default Priority?"), description=_("Check this box if this is the default priority"), ), ), )) schema['description'].widget.visible = True @indexer(IARPriority) def sortable_title_with_sort_key(instance): sort_key = instance.getSortKey() stitle = sortable_title(instance, instance.Title()) if sort_key: return "{:010.3f}{}".format(sort_key, stitle) return stitle class ARPriority(BaseContent): security = ClassSecurityInfo() schema = schema displayContentsTab = False implements(IARPriority) _at_rename_after_creation = True def _renameAfterCreation(self, check_auto_id=False): renameAfterCreation(self) atapi.registerType(ARPriority, PROJECTNAME)
'columns': ['Title', 'Description']}, ] def before_render(self): """Before template render hook """ super(DrugProhibitionsView, self).before_render() # Don't allow any context actions on Drug Prohibitions folder self.request.set("disable_border", 1) def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['Description'] = obj.Description() items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items schema = ATFolderSchema.copy() class DrugProhibitions(ATFolder): implements(IDrugProhibitions) displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish = True, moveDiscussion = False) atapi.registerType(DrugProhibitions, PROJECTNAME)
security.declarePrivate('_unlinkUser') def _unlinkUser(self): """Remove the UID of the current Contact in the User properties and update all relevant own properties. """ KEY = "linked_contact_uid" # Nothing to do if no user is linked if not self.hasUser(): return False user = self.getUser() # Unset the UID from the User Property user.setMemberProperties({KEY: ""}) logger.info("Unlinked Contact UID from User {}".format( user.getProperty(KEY, ""))) # Unset the Username self.setUsername(None) # Unset the Email self.setEmailAddress(None) # somehow the `getUsername` index gets out of sync self.reindexObject() return True atapi.registerType(Contact, PROJECTNAME)
# Copyright 2011-2016 by it's authors. # Some rights reserved. See LICENSE.txt, AUTHORS.txt. from AccessControl import ClassSecurityInfo from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.config import ManageInvoices, PROJECTNAME from bika.lims.interfaces import IInvoiceFolder, IHaveNoBreadCrumbs from Products.Archetypes import atapi from Products.Archetypes.public import * from Products.ATContentTypes.content import folder from Products.ATContentTypes.content import schemata from Products.CMFCore import permissions from Products.CMFCore.utils import UniqueObject from ZODB.POSException import ConflictError from zope.interface import implements schema = folder.ATFolderSchema.copy() schema['id'].widget.visible = {'edit':'hidden', 'view':'invisible'} schema['title'].widget.visible = {'edit':'hidden', 'view':'invisible'} class InvoiceFolder(folder.ATFolder): implements(IInvoiceFolder, IHaveNoBreadCrumbs) displayContentsTab = False schema = schema security = ClassSecurityInfo() atapi.registerType(InvoiceFolder, PROJECTNAME)
"edit": "visible", "view": "visible", } ), ), )) schema['id'].required = False schema['title'].required = False class ARReport(BaseFolder): """An AnalysisRequest report, containing the report itself in pdf and html format. It includes information about the date when was published, from whom, the report recipients (and their emails) and the publication mode """ implements(IARReport) security = ClassSecurityInfo() displayContentsTab = False schema = schema _at_rename_after_creation = True def _renameAfterCreation(self, check_auto_id=False): from bika.lims.idserver import renameAfterCreation renameAfterCreation(self) atapi.registerType(ARReport, PROJECTNAME)
self.company_employees.remove(user_id) except ValueError: pass objectEventNotify(CompanyShareNotify(self, user_id, add_user=False)) super(Company, self).manage_delLocalRoles(userids=userids) def hasContentLeadImage(self): field = self.getField(IMAGE_FIELD_NAME) if field is not None: value = field.get(self) return not not value def setCity(self, value, **kwargs): if value: value = value.title().strip() self.getField('city').set(self, value, **kwargs) def setWebsite(self, value, **kwargs): if value: value = value.lower() self.getField('website').set(self, value, **kwargs) def CreatorFullname(self): creator = self.Creator() membership = getToolByName(self, 'portal_membership') author = membership.getMemberInfo(creator) return author and author['fullname'] or creator atapi.registerType(Company, PROJECTNAME)
'contentFilter': {}, 'columns': ['Title', 'Description', 'SortKey'] }, ] def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if 'obj' not in items[x]: continue obj = items[x]['obj'] items[x]['Description'] = obj.Description() items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items schema = ATFolderSchema.copy() class SubGroups(ATFolder): implements(ISubGroups) security = ClassSecurityInfo() displayContentsTab = False schema = schema schemata.finalizeATCTSchema(schema, folderish=True, moveDiscussion=False) atapi.registerType(SubGroups, PROJECTNAME)
raise except Exception, e: LOG.error('Failed sending email from %s to %s' % (fromAddress, address)) LOG.error("Reason: %s: %r" % (e.__class__.__name__, str(e))) # end if # end for #security.declarePrivate('pathQuote') def pathQuote(self, string=''): """ Returns a string which is save to use as a filename. @param string some string """ SPACE_REPLACER = '_' # Replace any character not in [a-zA-Z0-9_-] with SPACE_REPLACER ALLOWED_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-' ret = '' for c in string: if(c in ALLOWED_CHARS): ret += c else: ret += SPACE_REPLACER return ret registerType(ECABTool, config.PROJECTNAME)
# TODO: Use better method to redirect after transition self.REQUEST.response.write( "<script>window.location.href='%s'</script>" % (self.absolute_url() + '/stickers/?items=' + self.getId())) def workflow_script_store(self): """ store order """ self.setDateStored(DateTime()) self.reindexObject() security.declareProtected(View, 'getProductUIDs') def getProductUIDs(self): """ return the uids of the products referenced by order items """ uids = [] for orderitem in self.objectValues('OrderItem'): product = orderitem.getProduct() if product is not None: uids.append(orderitem.getProduct().UID()) return uids security.declarePublic('current_date') def current_date(self): """ return current date """ return DateTime() atapi.registerType(Order, PROJECTNAME)