def edit(self, o): if self.relation_editor_list is not None: if self.context_getter_id: o = getattr(o, self.context_getter_id)() portal = o.getPortalObject() relation_object_list = [] for value, uid, display_text, relation_key, item_key in \ self.relation_editor_list: if uid is not None: if isinstance(uid, StringType) and \ uid.startswith(NEW_CONTENT_PREFIX): # Create a new content portal_type = uid[len(NEW_CONTENT_PREFIX):] portal_module = None for p_item in self.portal_type_item: if p_item[0] == portal_type: portal_module = portal.getDefaultModuleId( p_item[0]) if portal_module is not None: portal_module_object = getattr( portal, portal_module) kw = {} kw[self.key] = value.replace('%', '') kw['portal_type'] = portal_type new_object = portal_module_object.newContent(**kw) relation_object_list.append(new_object) else: raise else: relation_object_list.append( portal.portal_catalog.getObject(uid)) # Edit relation if self.relation_setter_id: relation_setter = getattr(o, self.relation_setter_id) relation_setter((), portal_type=self.portal_type_list) relation_setter(relation_object_list, portal_type=self.portal_type_list) else: # we could call a generic method which create the setter method name if len(relation_object_list) == 1: set_method_name = '_set%sValue' % \ convertToUpperCase(self.base_category) getattr(o, set_method_name)(relation_object_list[0], portal_type=self.portal_type_list, checked_permission='View') else: set_method_name = '_set%sValueList' % \ convertToUpperCase(self.base_category) getattr(o, set_method_name)(relation_object_list, portal_type=self.portal_type_list, checked_permission='View')
def _generatePreferenceToolAccessorHolder(portal_type_name, accessor_holder_list): """ Generate a specific Accessor Holder that will be put on the Preference Tool. (This used to happen in ERP5Form.PreferenceTool._aq_dynamic) We iterate over all properties that do exist on the system, select the preferences out of those, and generate the getPreferred.* accessors in erp5.accessor_holder.portal_type.PORTAL_TYPE.PORTAL_TYPE. """ import erp5.accessor_holder.portal_type accessor_holder_module = getattr(erp5.accessor_holder.portal_type, portal_type_name) try: return accessor_holder_module.PreferenceTool except AttributeError: # The accessor holder does not already exist pass preference_tool_accessor_holder = AccessorHolderType('PreferenceTool') for accessor_holder in accessor_holder_list: for prop in accessor_holder._properties: if not prop.get('preference'): continue # XXX read_permission and write_permissions defined at # property sheet are not respected by this. # only properties marked as preference are used # properties have already been 'converted' and _list is appended # to list_types properties attribute = prop['id'] if attribute.endswith('_list'): attribute = prop['base_id'] attr_list = ['get%s' % convertToUpperCase(attribute)] if prop['type'] == 'boolean': attr_list.append('is%s' % convertToUpperCase(attribute)) if prop['type'] in list_types or prop['multivalued']: attr_list.append('get%sList' % convertToUpperCase(attribute)) read_permission = prop.get('read_permission') for attribute_name in attr_list: method = PreferenceMethod(attribute_name, prop.get('default')) preference_tool_accessor_holder.registerAccessor( method, read_permission) accessor_holder_module.registerAccessorHolder( preference_tool_accessor_holder) return preference_tool_accessor_holder
def edit(self, o): if self.relation_editor_list is not None: if self.context_getter_id: o = getattr(o, self.context_getter_id)() portal = o.getPortalObject() relation_object_list = [] for value, uid, display_text, relation_key, item_key in \ self.relation_editor_list: if uid is not None: if isinstance(uid, StringType) and \ uid.startswith(NEW_CONTENT_PREFIX): # Create a new content portal_type = uid[len(NEW_CONTENT_PREFIX):] portal_module = None for p_item in self.portal_type_item: if p_item[0] == portal_type: portal_module = portal.getDefaultModuleId(p_item[0]) if portal_module is not None: portal_module_object = getattr(portal, portal_module) kw ={} kw[self.key] = value.replace('%', '') kw['portal_type'] = portal_type new_object = portal_module_object.newContent(**kw) relation_object_list.append(new_object) else: raise else: relation_object_list.append(portal.portal_catalog.getObject(uid)) # Edit relation if self.relation_setter_id: relation_setter = getattr(o, self.relation_setter_id) relation_setter((), portal_type=self.portal_type_list) relation_setter(relation_object_list, portal_type=self.portal_type_list) else: # we could call a generic method which create the setter method name if len(relation_object_list) == 1: set_method_name = '_set%sValue' % \ convertToUpperCase(self.base_category) getattr(o, set_method_name)(relation_object_list[0], portal_type=self.portal_type_list, checked_permission='View') else: set_method_name = '_set%sValueList' % \ convertToUpperCase(self.base_category) getattr(o, set_method_name)(relation_object_list, portal_type=self.portal_type_list, checked_permission='View')
def defMethodGetter(key, method=None): key = convertToUpperCase(key) name = 'Default%sGetter' % key if method is None: method = methodcaller('get' + key) def __call__(self, instance, *args, **kw): o = DefaultGetter.__call__(self, instance, **kw) if o is None: return args[0] if args else None return method(o) psyco.bind(__call__) globals()[name] = type(name, (DefaultGetter, ), {'__call__': __call__}) name = '%sListGetter' % key def __call__(self, instance, *args, **kw): r = ListGetter.__call__(self, instance, **kw) return [method(x) for x in r] if r or not args else args[0] psyco.bind(__call__) globals()[name] = type(name, (ListGetter, ), {'__call__': __call__}) name = '%sSetGetter' % key def __call__(self, instance, *args, **kw): r = ListGetter.__call__(self, instance, **kw) return list({method(x) for x in r}) if r or not args else args[0] psyco.bind(__call__) globals()[name] = type(name, (ListGetter, ), {'__call__': __call__})
def defMethodGetter(key, method=None): key = convertToUpperCase(key) name = 'Default%sGetter' % key if method is None: method = methodcaller('get' + key) def __call__(self, instance, *args, **kw): o = DefaultGetter.__call__(self, instance, **kw) if o is None: return args[0] if args else None return method(o) psyco.bind(__call__) globals()[name] = type(name, (DefaultGetter,), {'__call__': __call__}) name = '%sListGetter' % key def __call__(self, instance, *args, **kw): r = ListGetter.__call__(self, instance, **kw) return map(method, r) if r or not args else args[0] psyco.bind(__call__) globals()[name] = type(name, (ListGetter,), {'__call__': __call__}) name = '%sSetGetter' % key def __call__(self, instance, *args, **kw): r = ListGetter.__call__(self, instance, **kw) return list({method(x) for x in r}) if r or not args else args[0] psyco.bind(__call__) globals()[name] = type(name, (ListGetter,), {'__call__': __call__})
def _generatePreferenceToolAccessorHolder(portal_type_name, accessor_holder_list): """ Generate a specific Accessor Holder that will be put on the Preference Tool. (This used to happen in ERP5Form.PreferenceTool._aq_dynamic) We iterate over all properties that do exist on the system, select the preferences out of those, and generate the getPreferred.* accessors in erp5.accessor_holder.portal_type.PORTAL_TYPE.PORTAL_TYPE. """ import erp5.accessor_holder.portal_type accessor_holder_module = getattr(erp5.accessor_holder.portal_type, portal_type_name) try: return accessor_holder_module.PreferenceTool except AttributeError: # The accessor holder does not already exist pass preference_tool_accessor_holder = AccessorHolderType("PreferenceTool") for accessor_holder in accessor_holder_list: for prop in accessor_holder._properties: if not prop.get("preference"): continue # XXX read_permission and write_permissions defined at # property sheet are not respected by this. # only properties marked as preference are used # properties have already been 'converted' and _list is appended # to list_types properties attribute = prop["id"] if attribute.endswith("_list"): attribute = prop["base_id"] attr_list = ["get%s" % convertToUpperCase(attribute)] if prop["type"] == "boolean": attr_list.append("is%s" % convertToUpperCase(attribute)) if prop["type"] in list_types: attr_list.append("get%sList" % convertToUpperCase(attribute)) read_permission = prop.get("read_permission") for attribute_name in attr_list: method = PreferenceMethod(attribute_name, prop.get("default")) preference_tool_accessor_holder.registerAccessor(method, read_permission) accessor_holder_module.registerAccessorHolder(preference_tool_accessor_holder) return preference_tool_accessor_holder
def initializeAccessors(klass): klass.security = ClassSecurityInfo() klass.security.declareObjectPublic() for attr in klass.attribute_list: name = 'get' + convertToUpperCase(attr) setattr(klass, name, Getter(attr)) klass.security.declarePublic(name) InitializeClass(klass)
def getPreference(self, pref_name, default=_marker): """ get the preference on the most appopriate Preference object. """ method = getattr(self, 'get%s' % convertToUpperCase(pref_name), None) if method is not None: return method(default) if default is _marker: return None return default
def initializeAccessors(klass): klass.security = ClassSecurityInfo() klass.security.declareObjectPublic() for attr in klass.attribute_list: name = 'get' + convertToUpperCase(attr) setattr(klass, name, Getter(attr)) klass.security.declarePublic(name) InitializeClass(klass)
def ExpressionMixin(property_reference='expression'): """ Mixin for a common pattern where ERP5 objects stores a TALES Expression as text. Usage examples: Python Script/SQL Method: expression_property (reference=expression) GuardableMixin: guard_expression_property (reference=guard_expression) CMFCore.Expression already stores the Expression text as 'text' property and create a volatile for the instance, so this may seem redundant and we may have stored an Expression instance directly on the object. However this would make exported objects depend on CMFCore.Expression and not storing "directly" user input. """ property_reference_uppercase = convertToUpperCase(property_reference) volatile_attribute_name = '_v_' + property_reference + '_instance' def _setter(self, value): """ _set<PropertyReference>() """ try: delattr(self, volatile_attribute_name) except AttributeError: pass getattr(self, '_baseSet' + property_reference_uppercase)(value) def getter(self, default=None): """ get<PropertyReference>Instance() """ try: return getattr(self, volatile_attribute_name) except AttributeError: expression = getattr(self, 'get' + property_reference_uppercase)() # Check if the expression is not None, because Expression(<expression>) # raises an error in case `expression` is empty or None. if expression: result = Expression(expression) else: result = None setattr(self, volatile_attribute_name, result) return result class ExpressionMixin: security = ClassSecurityInfo() _setter.__name__ = '_set' + property_reference_uppercase setattr(ExpressionMixin, _setter.__name__, _setter) getter.__name__ = 'get' + property_reference_uppercase + 'Instance' setattr(ExpressionMixin, getter.__name__, getter) ExpressionMixin.security.declareProtected( Permissions.AccessContentsInformation, getter.__name__) InitializeClass(ExpressionMixin) return ExpressionMixin
def isDetailed(self): for prop in PropertySheet.InternetProtocolAddress._properties: property_id = prop['id'] tester_name = 'has%s' % convertToUpperCase(property_id) tester_method = getattr(self, tester_name) value = tester_method() if value: return True return False
def isDetailed(self): for prop in PropertySheet.InternetProtocolAddress._properties: property_id = prop['id'] tester_name = 'has%s' % convertToUpperCase(property_id) tester_method = getattr(self, tester_name) value = tester_method() if value: return True return False
def isDetailed(self): for prop in self.portal_property_sheets.\ InternetProtocolAddress.objectValues( portal_type="Standard Property"): property_id = prop.getReference() tester_name = 'has%s' % convertToUpperCase(property_id) tester_method = getattr(self, tester_name) value = tester_method() if value: return True return False
def fromText(self, coordinate_text): """Save given data then continue parsing (deprecated because computed values are stored) """ self._setCoordinateText(coordinate_text) kw_dict = self._splitCoordinateText(coordinate_text) for name, value in kw_dict.iteritems(): setter_name = 'set%s' % convertToUpperCase(name) setter_method = getattr(self, setter_name) setter_method(value)
def fromText(self, coordinate_text): """Save given data then continue parsing (deprecated because computed values are stored) """ self._setCoordinateText(coordinate_text) kw_dict = self._splitCoordinateText(coordinate_text) for name, value in kw_dict.iteritems(): setter_name = 'set%s' % convertToUpperCase(name) setter_method = getattr(self, setter_name) setter_method(value)
def getQuantityStepList(self, *args, **kw): """ Return predicate step related to a price_parameter """ # We need to keep compatibility with generated accessor price_parameter = kw.get("price_parameter", "base_price") if price_parameter == "base_price": method_name = "_baseGetQuantityStepList" else: method_name = "get%sList" % convertToUpperCase("%s_quantity_step" % price_parameter) return getattr(self, method_name)()
def getQuantityStepList(self, *args, **kw): """ Return predicate step related to a price_parameter """ # We need to keep compatibility with generated accessor price_parameter = kw.get('price_parameter', "base_price") if price_parameter in ("base_price", "slice_base_price"): method_name = "_baseGetQuantityStepList" else: method_name = 'get%sList' % \ convertToUpperCase("%s_quantity_step" % price_parameter) return getattr(self, method_name)() or []
def createAlarmStep(self): def makeCallAlarm(alarm): def callAlarm(*args, **kwargs): sm = getSecurityManager() self.login() try: alarm.activeSense(params=kwargs) self.commit() finally: setSecurityManager(sm) return callAlarm for alarm in self.portal.portal_alarms.contentValues(): if alarm.isEnabled(): setattr(self, 'stepCall' + convertToUpperCase(alarm.getId()) \ + 'Alarm', makeCallAlarm(alarm))
def createAlarmStep(self): def makeCallAlarm(alarm): def callAlarm(*args, **kwargs): sm = getSecurityManager() self.login() try: alarm.activeSense(params=kwargs) transaction.commit() finally: setSecurityManager(sm) return callAlarm for alarm in self.portal.portal_alarms.contentValues(): if alarm.isEnabled(): setattr(self, 'stepCall' + convertToUpperCase(alarm.getId()) \ + 'Alarm', makeCallAlarm(alarm))
def asText(self): """ Return the address as a complete formatted string. """ result = Coordinate.asText(self) if result is None: if self.isDetailed(): tmp_list = [] for prop in PropertySheet.InternetProtocolAddress._properties: property_id = prop['id'] getter_name = 'get%s' % convertToUpperCase(property_id) getter_method = getattr(self, getter_name) value = getter_method('') tmp_list.append('%s:%s' % (property_id, value)) result = '\n'.join(tmp_list) else: result = '\n'.join(('%s:%s' % (k, v) for k, v in\ self._splitCoordinateText(self.getCoordinateText()))) return result
def edit(self, o): if self.relation_editor_list is None: return if self.context_getter_id: o = getattr(o, self.context_getter_id)() portal = o.getPortalObject() getDefaultModuleValue = portal.getDefaultModuleValue getObject = portal.portal_catalog.getObject portal_type_set = {x[0] for x in self.portal_type_item} relation_object_list = [] append = relation_object_list.append for ( value, uid, display_text, relation_key, item_key ) in self.relation_editor_list: if isinstance(uid, basestring) and uid.startswith(NEW_CONTENT_PREFIX): portal_type = uid[len(NEW_CONTENT_PREFIX):] if portal_type in portal_type_set: append( getDefaultModuleValue( portal_type, only_visible=True, ).newContent( portal_type=portal_type, **{ self.key: value.replace('%', ''), } ) ) elif uid is not None: append(getObject(uid)) set_method_name = self.relation_setter_id set_method_kw = {} if not set_method_name: # XXX: we could call a generic method which create the setter method name set_method_name = 'set%sValueList' % \ convertToUpperCase(self.base_category) set_method_kw['checked_permission'] = 'View' getattr(o, set_method_name)( relation_object_list, portal_type=self.portal_type_list, **set_method_kw )
def asText(self): """ Return the address as a complete formatted string. """ result = Coordinate.asText(self) if result is None: if self.isDetailed(): tmp_list = [] for prop in PropertySheet.InternetProtocolAddress._properties: property_id = prop['id'] getter_name = 'get%s' % convertToUpperCase(property_id) getter_method = getattr(self, getter_name) value = getter_method('') tmp_list.append('%s:%s' % (property_id, value)) result = '\n'.join(tmp_list) else: result = '\n'.join(('%s:%s' % (k, v) for k, v in\ self._splitCoordinateText(self.getCoordinateText()))) return result
def edit(self, o): if self.relation_editor_list is None: return if self.context_getter_id: o = getattr(o, self.context_getter_id)() portal = o.getPortalObject() getDefaultModuleValue = portal.getDefaultModuleValue getObject = portal.portal_catalog.getObject portal_type_set = {x[0] for x in self.portal_type_item} relation_object_list = [] append = relation_object_list.append for ( value, uid, display_text, relation_key, item_key ) in self.relation_editor_list: if isinstance(uid, basestring) and uid.startswith(NEW_CONTENT_PREFIX): portal_type = uid[len(NEW_CONTENT_PREFIX):] if portal_type in portal_type_set: append( getDefaultModuleValue( portal_type, only_visible=True, ).newContent( portal_type=portal_type, **{ self.key: value.replace('%', ''), } ) ) elif uid is not None: append(getObject(uid)) set_method_name = self.relation_setter_id set_method_kw = {} if not set_method_name: # XXX: we could call a generic method which create the setter method name set_method_name = 'set%sValueList' % \ convertToUpperCase(self.base_category) set_method_kw['checked_permission'] = 'View' getattr(o, set_method_name)( relation_object_list, portal_type=self.portal_type_list, **set_method_kw )
def asText(self): """ Return the address as a complete formatted string. """ result = Coordinate.asText(self) if result is None: if self.isDetailed(): tmp_list = [] for prop in self.portal_property_sheets.\ InternetProtocolAddress.objectValues( portal_type="Standard Property"): property_id = prop.getReference() getter_name = 'get%s' % convertToUpperCase(property_id) getter_method = getattr(self, getter_name) value = getter_method('') tmp_list.append('%s:%s' % (property_id, value)) result = '\n'.join(tmp_list) else: result = '\n'.join(('%s:%s' % (k, v) for k, v in\ self._splitCoordinateText(self.getCoordinateText()))) return result
def discoverMetadata(self, filename=None, user_login=None, input_parameter_dict=None, file_name=None): """ This is the main metadata discovery function - controls the process of discovering data from various sources. The discovery itself is delegated to scripts or uses preference-configurable regexps. The method returns either self or the document which has been merged in the discovery process. filename - this parameter is a file name of the form "AA-BBB-CCC-223-en" user_login - this is a login string of a person; can be None if the user is currently logged in, then we'll get him from session input_parameter_dict - arguments provided to Create this content by user. """ if file_name is not None: filename=file_name # Preference is made of a sequence of 'user_login', 'content', 'filename', 'input' method = self._getTypeBasedMethod('getPreferredDocumentMetadataDiscoveryOrderList') order_list = list(method()) order_list.reverse() # build a dictionary according to the order kw = {} for order_id in order_list: result = None if order_id not in VALID_ORDER_KEY_LIST: # Prevent security attack or bad preferences raise AttributeError, "%s is not in valid order key list" % order_id method_id = 'getPropertyDictFrom%s' % convertToUpperCase(order_id) method = getattr(self, method_id) if order_id in ('filename', 'file_name',): if filename is not None: result = method(filename) elif order_id == 'user_login': if user_login is not None: result = method(user_login) elif order_id == 'input': if input_parameter_dict is not None: result = method(input_parameter_dict) else: result = method() if result is not None: for key, value in result.iteritems(): if value not in (None, ''): kw[key]=value # Prepare the content edit parameters portal_type = None if input_parameter_dict is not None: # User decision take precedence, never try to change this value portal_type = input_parameter_dict.get('portal_type') if not portal_type: # Read discovered portal_type portal_type = kw.pop('portal_type', None) if portal_type and portal_type != self.getPortalType(): # Reingestion is required to update portal_type return self.migratePortalType(portal_type) # Try not to invoke an automatic transition here self._edit(**kw) if not portal_type: # If no portal_type was dicovered, pass self # through to portal_contribution_registry # to guess destination portal_type against all properties. # If returned portal_type is different, then reingest. registry = self.getPortalObject().portal_contribution_registry portal_type = registry.findPortalTypeName(context=self) if portal_type != self.getPortalType(): return self.migratePortalType(portal_type) # Finish ingestion by calling method self.finishIngestion() # XXX - is this really the right place ? self.reindexObject() # XXX - is this really the right place ? # Revision merge is tightly coupled # to metadata discovery - refer to the documentation of mergeRevision method merged_doc = self.mergeRevision() # XXX - is this really the right place ? merged_doc.reindexObject() # XXX - is this really the right place ? return merged_doc # XXX - is this really the right place ?
def discoverMetadata(self, filename=None, user_login=None, input_parameter_dict=None): """ This is the main metadata discovery function - controls the process of discovering data from various sources. The discovery itself is delegated to scripts or uses preference-configurable regexps. The method returns either self or the document which has been merged in the discovery process. filename - this parameter is a file name of the form "AA-BBB-CCC-223-en" user_login - this is a login string of a person; can be None if the user is currently logged in, then we'll get him from session input_parameter_dict - arguments provided to Create this content by user. """ # Preference is made of a sequence of 'user_login', 'content', 'filename', 'input' method = self._getTypeBasedMethod( 'getPreferredDocumentMetadataDiscoveryOrderList') order_list = list(method()) order_list.reverse() # build a dictionary according to the order kw = {} for order_id in order_list: result = None if order_id not in VALID_ORDER_KEY_LIST: # Prevent security attack or bad preferences raise AttributeError, "%s is not in valid order key list" % order_id method_id = 'getPropertyDictFrom%s' % convertToUpperCase(order_id) method = getattr(self, method_id) if order_id in ( 'filename', 'file_name', ): if filename is not None: result = method(filename) elif order_id == 'user_login': if user_login is not None: result = method(user_login) elif order_id == 'input': if input_parameter_dict is not None: result = method(input_parameter_dict) else: result = method() if result is not None: for key, value in result.iteritems(): if value not in (None, ''): kw[key] = value # Prepare the content edit parameters portal_type = None if input_parameter_dict is not None: # User decision take precedence, never try to change this value portal_type = input_parameter_dict.get('portal_type') if not portal_type: # Read discovered portal_type portal_type = kw.pop('portal_type', None) if portal_type and portal_type != self.getPortalType(): # Reingestion is required to update portal_type return self.migratePortalType(portal_type) # Try not to invoke an automatic transition here self._edit(**kw) if not portal_type: # If no portal_type was dicovered, pass self # through to portal_contribution_registry # to guess destination portal_type against all properties. # If returned portal_type is different, then reingest. registry = self.getPortalObject().portal_contribution_registry portal_type = registry.findPortalTypeName(context=self) if portal_type != self.getPortalType(): return self.migratePortalType(portal_type) # Finish ingestion by calling method self.finishIngestion() # XXX - is this really the right place ? self.reindexObject() # XXX - is this really the right place ? # Revision merge is tightly coupled # to metadata discovery - refer to the documentation of mergeRevision method merged_doc = self.mergeRevision( ) # XXX - is this really the right place ? merged_doc.reindexObject() # XXX - is this really the right place ? return merged_doc # XXX - is this really the right place ?
def getPreference(self, pref_name, default=_marker) : """ get the preference on the most appopriate Preference object. """ method = getattr(self, 'get%s' % convertToUpperCase(pref_name), None) if method is not None: return method(default) return default
def getPDFForm(self): """ Returns an PDF Form instance (stored in RAM) """ if self.getDefaultScribusFormValue() is None: return portal_type_name = self.getId().replace(' ', '') pdf_form_name = '%s_view%sAsPdf' % (portal_type_name, portal_type_name) pdf_file = StringIO.StringIO(self.getDefaultPdfFormValue().getData()) pdf_form = PDFForm(pdf_form_name, portal_type_name, pdf_file) pdf_form.manage_upload(pdf_file) import_scribus_file = StringIO.StringIO( self.getDefaultScribusFormValue().getData()) scribus_parser = ScribusParser(import_scribus_file) erp5_properties = scribus_parser.getERP5PropertyDict() def_usePropertySheet = 0 my_prefix = 'my_' prefix_len = len(my_prefix) pages = range(len(erp5_properties)) for page in pages: page_content = erp5_properties[page] for cell_name, field_dict in page_content: # current object is PDF Form if cell_name[:prefix_len] == my_prefix: cell_process_name_list = [] suffix = cell_name[prefix_len:].split('_')[-1] # If properties field are filled in scribus, get Type form # global_properties. Else, guess Type by suffix id (eg: List, Date,...) list_field_type_list = ( 'ListField', 'MultiListField', 'LinesField', ) date_field_type_list = ('DateTimeField', ) suffix_mapping = { 'List': list_field_type_list, 'Date': date_field_type_list } field_type = field_dict.get( 'erp_type', suffix_mapping.get(suffix, [''])[0]) if def_usePropertySheet: # generating PropertySheet and Document, no need to use them to # get field data if field_type in list_field_type_list: TALES = "python: %s " % ', '.join( "here.get%s()" % convertToUpperCase(cell_name[prefix_len:])) elif field_type in date_field_type_list: attributes_dict = field_dict['attributes'] # assign the property input_order input_order = attributes_dict['input_order'] input_order = input_order.replace('y', 'Y') # make the Tales according to the cases date_pattern = '/'.join( ['%%%s' % s for s in list(input_order)]) if not (attributes_dict['date_only']): date_pattern += ' %H:%M' TALES = "python: here.get%s() is not None and here.get%s().strftime('%s') or ''"\ % (convertToUpperCase(cell_name[prefix_len:]), convertToUpperCase(cell_name[prefix_len:]), date_pattern) else: TALES = "python: here.get%s()" %\ convertToUpperCase(cell_name[prefix_len:]) else: if field_type in list_field_type_list: TALES = "python: %s" % ', '.join( "here.getProperty('%s')" % cell_name[prefix_len:]) elif field_type in date_field_type_list: attributes_dict = field_dict['attributes'] # assign the property input_order input_order = attributes_dict['input_order'] input_order = input_order.replace('y', 'Y') # make the Tales according to the cases date_pattern = '/'.join( ['%%%s' % s for s in list(input_order)]) if not (attributes_dict['date_only']): date_pattern += ' %H:%M' TALES = "python: here.getProperty('%s') is not None and here.getProperty('%s').strftime('%s') or ''"\ % (cell_name[prefix_len:], cell_name[prefix_len:], date_pattern) else: TALES = "python: here.getProperty('%s')" % cell_name[ prefix_len:] pdf_form.setCellTALES(cell_name, TALES) import_scribus_file.close() pdf_file.close() self.REQUEST.RESPONSE.setHeader('Content-Type', 'application/pdf') return pdf_form
def upperCase(text): return convertToUpperCase(text.replace('-', '_'))
def getSectionUriList(self, id, **kw): return getattr(self, 'get%sUriList' % convertToUpperCase(id))()
def getRelatedLatest(category): funcname = 'get%sValueList' % convertToUpperCase(category) func = getattr(context, funcname) return [o.getLatestVersionValue() for o in func()]
def getSectionUriList(self, id, **kw): return getattr(self, 'get%sUriList' % convertToUpperCase(id))()
"""This class provides different ways to access source, destination, etc. """ security = ClassSecurityInfo() security.declareProtected(Permissions.AccessContentsInformation, "getTitle") def getTitle(self, default=''): return getattr(aq_base(self), 'title', default) for category in ('source', 'destination', 'source_section', 'destination_section', 'source_payment', 'destination_payment', 'source_function', 'destination_function', 'source_project', 'destination_project', 'source_variation_text', 'destination_variation_text',): getter_id = 'getBaobab%s' % (convertToUpperCase(category)) original_getter_id = 'get%s' % (convertToUpperCase(category)) method = BaobabGetter(getter_id, original_getter_id) setattr(BaobabMixin, getter_id, method) BaobabMixin.security.declareProtected(Permissions.View, getter_id) value_getter_id = getter_id + 'Value' method = BaobabValueGetter(value_getter_id, getter_id) setattr(BaobabMixin, value_getter_id, method) BaobabMixin.security.declareProtected(Permissions.View, value_getter_id) for prop in ('uid', 'title', 'id'): prop_getter_id = getter_id + convertToUpperCase(prop) method = BaobabPropertyGetter(prop_getter_id, value_getter_id, prop) setattr(BaobabMixin, prop_getter_id, method) BaobabMixin.security.declareProtected(Permissions.View, prop_getter_id)
from Products.ERP5Type.Utils import convertToUpperCase related_person_list = [] known_person_uid = {} for base_category in ['natural_parent', 'legal_parent', 'insurance_coverage'] : relation_title = context.getPortalObject().portal_categories[base_category].getTranslatedTitle() relation_method = getattr(context, "get%sRelatedValueList" % convertToUpperCase(base_category)) for person in relation_method( portal_type = 'Person' ) : if person.getUid() not in known_person_uid : known_person_uid[person.getUid()] = 1 related_person_list.append(person.asContext(relation_title = relation_title)) return related_person_list
def getPDFForm(self): """ Returns an PDF Form instance (stored in RAM) """ if self.getDefaultScribusFormValue() is None: return portal_type_name = self.getId().replace(' ','') pdf_form_name ='%s_view%sAsPdf' % (portal_type_name, portal_type_name) pdf_file = StringIO.StringIO(self.getDefaultPdfFormValue().getData()) pdf_form = PDFForm(pdf_form_name, portal_type_name, pdf_file) pdf_form.manage_upload(pdf_file) import_scribus_file = StringIO.StringIO(self.getDefaultScribusFormValue().getData()) scribus_parser = ScribusParser(import_scribus_file) erp5_properties = scribus_parser.getERP5PropertyDict() def_usePropertySheet = 0 my_prefix = 'my_' prefix_len = len(my_prefix) pages = range(len(erp5_properties)) for page in pages: page_content = erp5_properties[page] for cell_name, field_dict in page_content: # current object is PDF Form if cell_name[:prefix_len] == my_prefix: cell_process_name_list = [] suffix = cell_name[prefix_len:].split('_')[-1] # If properties field are filled in scribus, get Type form # global_properties. Else, guess Type by suffix id (eg: List, Date,...) list_field_type_list = ('ListField', 'MultiListField', 'LinesField',) date_field_type_list = ('DateTimeField',) suffix_mapping = {'List' : list_field_type_list, 'Date' : date_field_type_list} field_type = field_dict.get('erp_type', suffix_mapping.get(suffix, [''])[0]) if def_usePropertySheet: # generating PropertySheet and Document, no need to use them to # get field data if field_type in list_field_type_list: TALES = "python: %s " % ', '.join( "here.get%s()" % convertToUpperCase(cell_name[prefix_len:])) elif field_type in date_field_type_list: attributes_dict = field_dict['attributes'] # assign the property input_order input_order = attributes_dict['input_order'] input_order = input_order.replace('y', 'Y') # make the Tales according to the cases date_pattern = '/'.join(['%%%s' % s for s in list(input_order)]) if not(attributes_dict['date_only']): date_pattern += ' %H:%M' TALES = "python: here.get%s() is not None and here.get%s().strftime('%s') or ''"\ % (convertToUpperCase(cell_name[prefix_len:]), convertToUpperCase(cell_name[prefix_len:]), date_pattern) else: TALES = "python: here.get%s()" %\ convertToUpperCase(cell_name[prefix_len:]) else: if field_type in list_field_type_list: TALES = "python: %s" % ', '.join( "here.getProperty('%s')" % cell_name[prefix_len:]) elif field_type in date_field_type_list: attributes_dict = field_dict['attributes'] # assign the property input_order input_order = attributes_dict['input_order'] input_order = input_order.replace('y', 'Y') # make the Tales according to the cases date_pattern = '/'.join(['%%%s' % s for s in list(input_order)]) if not(attributes_dict['date_only']): date_pattern += ' %H:%M' TALES = "python: here.getProperty('%s') is not None and here.getProperty('%s').strftime('%s') or ''"\ % (cell_name[prefix_len:], cell_name[prefix_len:], date_pattern) else: TALES = "python: here.getProperty('%s')" % cell_name[prefix_len:] pdf_form.setCellTALES(cell_name, TALES) import_scribus_file.close() pdf_file.close() self.REQUEST.RESPONSE.setHeader('Content-Type', 'application/pdf') return pdf_form
from Products.ERP5Type.Utils import convertToUpperCase related_person_list = [] known_person_uid = {} for base_category in ['natural_parent', 'legal_parent', 'insurance_coverage']: relation_title = context.getPortalObject( ).portal_categories[base_category].getTranslatedTitle() relation_method = getattr( context, "get%sRelatedValueList" % convertToUpperCase(base_category)) for person in relation_method(portal_type='Person'): if person.getUid() not in known_person_uid: known_person_uid[person.getUid()] = 1 related_person_list.append( person.asContext(relation_title=relation_title)) return related_person_list
def __new__(metacls, name, bases, dictionary): def setterWrapper(accessor_name, property_name): dictionary['security'].declareProtected(Permissions.ModifyPortalContent, accessor_name) def setter(self, property_value): """ Everytime either 'reference', 'version' or 'text_content' are modified when a Component is in modified or validated state, the Component is set to modified state by dynamic class generation interaction workflow, then in this method, the current property value is recorded in order to handle any error returned when checking consistency before the new value is set. At the end, through dynamic class generation interaction workflow, the Component is validated only if checkConsistency returns no error The recorded property will be used upon loading the Component whereas the new value set is displayed in Component view. """ if (self.getValidationState() == 'modified' and not self.isPropertyRecorded(property_name)): self.recordProperty(property_name) return getattr(super(ComponentMixin, self), accessor_name)(property_value) setter.__name__ = accessor_name return setter def getterWrapper(accessor_name, property_name): dictionary['security'].declareProtected(Permissions.AccessContentsInformation, accessor_name) def getter(self, validated_only=False): """ When validated_only is True, then returns the property recorded if the Component has been modified but there was an error upon consistency checking """ if validated_only: try: return self.getRecordedProperty(property_name) # AttributeError when this property has never been recorded before # (_recorded_property_dict) and KeyError if the property has been # recorded before but is not anymore except (AttributeError, KeyError): pass return getattr(super(ComponentMixin, self), accessor_name)() getter.__name__ = accessor_name return getter for property_name in dictionary['_recorded_property_name_tuple']: setter_name = '_set' + convertToUpperCase(property_name) dictionary[setter_name] = setterWrapper(setter_name, property_name) getter_name = 'get' + convertToUpperCase(property_name) dictionary[getter_name] = getterWrapper(getter_name, property_name) # docstring required for publishing any object dictionary['__doc__'] = metacls.__doc__ # ExtensionClass required to avoid metaclasses conflicts when # ghosting/unghosting Portal Types return ExtensionClass.__new__(ExtensionClass, name, bases, dictionary)
def upperCase(text): return convertToUpperCase(text.replace('-', '_'))
def generatePredicate(self, multimembership_criterion_base_category_list=(), membership_criterion_base_category_list=(), criterion_property_list=(), identity_criterion=None, range_criterion=None,): """ This method generates a new temporary predicate based on an ad-hoc interpretation of local properties of an object. For example, a start_range_min property will be interpreted as a way to define a min criterion on start_date. The purpose of this method is to be called from a script called PortalType_asPredicate to ease the generation of Predicates based on range properties. It should be considered mostly as a trick to simplify the development of Predicates and forms. """ new_membership_criterion_category_list = list(self.getMembershipCriterionCategoryList()) new_membership_criterion_base_category_list = list(self.getMembershipCriterionBaseCategoryList()) new_multimembership_criterion_base_category_list = list(self.getMultimembershipCriterionBaseCategoryList()) for base_category in multimembership_criterion_base_category_list: category_list = self.getProperty(base_category + '_list') if category_list is not None and len(category_list)>0: for category in category_list: new_membership_criterion_category_list.append(base_category + '/' + category) if base_category not in new_multimembership_criterion_base_category_list: new_multimembership_criterion_base_category_list.append(base_category) for base_category in membership_criterion_base_category_list: category_list = self.getProperty(base_category + '_list') if category_list is not None and len(category_list)>0: for category in category_list: new_membership_criterion_category_list.append(base_category + '/' + category) if base_category not in new_membership_criterion_base_category_list: new_membership_criterion_base_category_list.append(base_category) new_criterion_property_list = list(self.getCriterionPropertyList()) # We need to build new criteria for asContext, and we should not # modify the original, so we always make copies. Since the usage is # temporary, use dicts instead of persistent mappings. new_identity_criterion = dict(getattr(self, '_identity_criterion', None) or {}) new_identity_criterion.update(identity_criterion or {}) new_range_criterion = dict(getattr(self, '_range_criterion', None) or {}) new_range_criterion.update(range_criterion or {}) # Look at local properties and make it criterion properties for property in criterion_property_list: if property not in self.getCriterionPropertyList() \ and property in self.propertyIds(): new_criterion_property_list.append(property) property_min = property + '_range_min' property_max = property + '_range_max' if getattr(self, 'get%s' % convertToUpperCase(property), None) is not None\ and self.getProperty(property) is not None: new_identity_criterion[property] = self.getProperty(property) elif getattr(self, 'get%s' % convertToUpperCase(property_min), None) is not None: min = self.getProperty(property_min) max = self.getProperty(property_max) new_range_criterion[property] = (min,max) # Return a new context with new properties, like if # we have a predicate with local properties new_self = self.asContext( membership_criterion_category=new_membership_criterion_category_list, membership_criterion_base_category=new_membership_criterion_base_category_list, multimembership_criterion_base_category=new_multimembership_criterion_base_category_list, criterion_property_list=new_criterion_property_list, _identity_criterion=new_identity_criterion, _range_criterion=new_range_criterion) return new_self
for category in ( 'source', 'destination', 'source_section', 'destination_section', 'source_payment', 'destination_payment', 'source_function', 'destination_function', 'source_project', 'destination_project', 'source_variation_text', 'destination_variation_text', ): getter_id = 'getBaobab%s' % (convertToUpperCase(category)) original_getter_id = 'get%s' % (convertToUpperCase(category)) method = BaobabGetter(getter_id, original_getter_id) setattr(BaobabMixin, getter_id, method) BaobabMixin.security.declareProtected(Permissions.View, getter_id) value_getter_id = getter_id + 'Value' method = BaobabValueGetter(value_getter_id, getter_id) setattr(BaobabMixin, value_getter_id, method) BaobabMixin.security.declareProtected(Permissions.View, value_getter_id) for prop in ('uid', 'title', 'id'): prop_getter_id = getter_id + convertToUpperCase(prop) method = BaobabPropertyGetter(prop_getter_id, value_getter_id, prop) setattr(BaobabMixin, prop_getter_id, method) BaobabMixin.security.declareProtected(Permissions.View, prop_getter_id)