# -*- coding: utf-8 -*- # # File: PopulationTeleService.py # # Copyright (c) 2007 by CommunesPlone # Generator: ArchGenXML Version 1.5.3 dev/svn # http://plone.org/products/archgenxml # # GNU General Public License (GPL) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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. # __author__ = """Gauthier BASTIEN , Stephan GEULETTE """ __docformat__ = 'plaintext' from AccessControl import ClassSecurityInfo from Products.Archetypes.atapi import * from Products.TeleServices.GenericTeleService import GenericTeleService from Products.TeleServices.config import * ##code-section module-header #fill in your manual code here from Products.CMFCore.utils import getToolByName from Products.PlacelessTranslationService import utranslate from Products.validation.interfaces.IValidator import IValidator from Products.validation import validation from DateTime.DateTime import DateTime import logging logger = logging.getLogger('TeleServices') #this validator check the demandtype #a demandTypeTerm having the properties 'eidRequired' True means that the user has to be connected with his eid card #a member that connect with his eid card has the role 'MemberWithEid' #see product BelgianEidAuthPlugin on www.communesplone.org class isMemberWithEidValidator: #On vérifie le numéro de carte d'identité belge __implements__ = (IValidator, ) def __init__(self, name): self.name = name def __call__(self, value, *args, **kwargs): #we check if the current user is connected with his eid card, so has the 'MemberWithEid' role #we get the object demandTerm corresponding to the value instance = kwargs.get('instance', False) tst = getToolByName(instance, 'portal_teleservices') demandTypeTerm = tst.getTermObject('PopulationTeleService', 'DemandTypeTerm', value) if demandTypeTerm.getEidRequired(): mtool = getToolByName(instance, 'portal_membership') member = mtool.getAuthenticatedMember() if member.has_role('MemberWithEid') or tst.isTeleServicesManager(instance): return True else: # print 'Must be connected with eid' return "You must be connected with your eID card to order this document." return True validation.register(isMemberWithEidValidator('isMemberWithEid')) class isBelgianNationalRegOrValidDateValidator: #On vérifie le numéro de carte d'identité belge __implements__ = (IValidator, ) def __init__(self, name): self.name = name def __call__(self, value, *args, **kwargs): from Products.validation import validation validNR = validDate = True #be sure value is a String, not a DataTime for example... value = str(value) v = validation.validatorFor('isBelgianNR') if v(value, 0) != True: #if True is returned, the test is successfull, otherwise, there was a validation problem validNR = False v = validation.validatorFor('isValidDate') if v(value, 0) != True: #if True is returned, the test is successfull, otherwise, there was a validation problem validDate = False if not validNR and not validDate: return "Enter a valid national register number or a valid birthdate." return True validation.register(isBelgianNationalRegOrValidDateValidator('isBelgianNROrDate')) ##/code-section module-header schema = Schema(( StringField( name='title', widget=StringWidget( label='Title', label_msgid='TeleServices_label_title', i18n_domain='TeleServices', ), accessor='Title', searchable= 'True', default_method="getFormattedTitle" ), StringField( name='demandType', widget=SelectionWidget( label='Demandtype', label_msgid='TeleServices_label_demandType', i18n_domain='TeleServices', ), searchable= 'True', vocabulary='listPopulationDemandTypes', validators=('isMemberWithEid',), required=True, default_method='getUserDemandType' ), StringField( name='motivation', widget=SelectionWidget( description="The motivation will be specified on the document.", format="select", label='Motivation', label_msgid='TeleServices_label_motivation', description_msgid='TeleServices_help_motivation', i18n_domain='TeleServices', ), required=True, vocabulary='listPopulationMotivations', searchable= 'True', default_method='setMotivationDefaultValue' ), StringField( name='destination', widget=SelectionWidget( format="select", label='Destination', label_msgid='TeleServices_label_destination', i18n_domain='TeleServices', ), required=True, vocabulary='listPopulationDestinations', searchable= 'True', default_method='setDestinationDefaultValue' ), TextField( name='comment', widget=TextAreaWidget( description="Give some details about your demand.", label='Comment', label_msgid='TeleServices_label_comment', description_msgid='TeleServices_help_comment', i18n_domain='TeleServices', ), optional=True, searchable= 'True', default_method='checkIfCommentInOptionalFields' ), IntegerField( name='copies', default="1", widget=IntegerField._properties['widget']( label='Copies', label_msgid='TeleServices_label_copies', i18n_domain='TeleServices', ), required=True, searchable= 'True' ), FloatField( name='amount', default="0", widget=DecimalWidget( label='Amount', label_msgid='TeleServices_label_amount', i18n_domain='TeleServices', ), searchable= 'True', validators=('isDecimal',) ), StringField( name='structuredCommunication', index="FieldIndex:brains", widget=StringWidget( label='Structuredcommunication', label_msgid='TeleServices_label_structuredCommunication', i18n_domain='TeleServices', ), write_permission="TeleServices: Manage TeleServices", searchable=1 ), StringField( name='accountNumber', widget=StringWidget( label='Accountnumber', label_msgid='TeleServices_label_accountNumber', i18n_domain='TeleServices', ), write_permission="TeleServices: Manage TeleServices", searchable= 'True' ), StringField( name='paymentMode', widget=SelectionWidget( format="select", label='Paymentmode', label_msgid='TeleServices_label_paymentMode', i18n_domain='TeleServices', ), required=True, vocabulary='listPaymentModes', searchable= 'True', default_method='setPaymentModeDefaultValue' ), TextField( name='officialComment', widget=TextAreaWidget( label='Officialcomment', label_msgid='TeleServices_label_officialComment', i18n_domain='TeleServices', ), optional=True, write_permission="TeleServices: Review state", searchable= 'True', default_method='checkIfOfficialCommentInOptionalFields' ), StringField( name='childName', widget=StringWidget( label='Childname', label_msgid='TeleServices_label_childName', i18n_domain='TeleServices', ), required=True, optional=True, searchable= 'True', default_method='checkIfChildNameInOptionalFields' ), StringField( name='childSurname', widget=StringWidget( label='Childsurname', label_msgid='TeleServices_label_childSurname', i18n_domain='TeleServices', ), required=True, optional=True, searchable= 'True', default_method='checkIfChildSurnameInOptionalFields' ), DateTimeField( name='childBirthDate', widget=CalendarWidget( show_hm=False, format='%d/%m/%Y', starting_year= 1989, future_years= 0, label='Childbirthdate', label_msgid='TeleServices_label_childBirthDate', i18n_domain='TeleServices', ), required=True, optional=True, searchable= 'True', default_method='checkIfChildBirthDateInOptionalFields' ), TextField( name='childContactPerson', widget=TextAreaWidget( description="Enter the personal details of a person to contact in case of emergency.", label='Childcontactperson', label_msgid='TeleServices_label_childContactPerson', description_msgid='TeleServices_help_childContactPerson', i18n_domain='TeleServices', ), required=True, optional=True, searchable= 'True', default_method='checkIfChildContactPersonInOptionalFields' ), StringField( name='deceasedBirthDateOrNationalRegister', widget=StringWidget( description="Enter the national register number or the birthdate", label='Deceasedbirthdateornationalregister', label_msgid='TeleServices_label_deceasedBirthDateOrNationalRegister', description_msgid='TeleServices_help_deceasedBirthDateOrNationalRegister', i18n_domain='TeleServices', ), searchable= 'True', default_method='checkIfDeceasedBirthDateOrNationalRegisterInOptionalFields', validators=('isBelgianNROrDate',), required=True, optional=True ), StringField( name='deceasedName', widget=StringWidget( label='Deceasedname', label_msgid='TeleServices_label_deceasedName', i18n_domain='TeleServices', ), required=True, optional=True, searchable= 'True', default_method='checkIfDeceasedNameInOptionalFields' ), StringField( name='deceasedName2', widget=StringWidget( label='Deceasedname2', label_msgid='TeleServices_label_deceasedName2', i18n_domain='TeleServices', ), required=True, optional=True, searchable= 'True', default_method="checkIfDeceasedName2InOptionalFields" ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema PopulationTeleService_schema = BaseSchema.copy() + \ getattr(GenericTeleService, 'schema', Schema(())).copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class PopulationTeleService(BaseContent, GenericTeleService): """ """ security = ClassSecurityInfo() __implements__ = (getattr(BaseContent,'__implements__',()),) + (getattr(GenericTeleService,'__implements__',()),) # This name appears in the 'add' box archetype_name = 'PopulationTeleService' meta_type = 'PopulationTeleService' portal_type = 'PopulationTeleService' allowed_content_types = [] + list(getattr(GenericTeleService, 'allowed_content_types', [])) filter_content_types = 0 global_allow = 1 #content_icon = 'PopulationTeleService.gif' immediate_view = 'base_view' default_view = 'base_view' suppl_views = () typeDescription = "PopulationTeleService" typeDescMsgId = 'description_edit_populationteleservice' actions = ( {'action': "string:${object_url}/populationteleservice_view", 'category': "object", 'id': 'view', 'name': 'View', 'permissions': ("View",), 'condition': 'python:1' }, ) _at_rename_after_creation = True schema = PopulationTeleService_schema ##code-section class-header #fill in your manual code here ##/code-section class-header # Methods security.declarePublic('getFormattedTitle') def getFormattedTitle(self): """ Return title : demandtype """ # tool = getToolByName(self, 'translation_service') vocab = self.getField('demandType').Vocabulary(self) return self.displayValue(vocab, self.getDemandType()) security.declarePublic('getUserDemandType') def getUserDemandType(self): """ Get first the demandType property on the object. If not exists, call the getDemandTypeFromRequest from portal_teleservices to try to populate the DemandType selection box. """ savedDemandType = None #check necessary for edit form if hasattr(self, 'demandType'): savedDemandType = getattr(self, 'demandType') if savedDemandType != None: return savedDemandType else: return self.portal_teleservices.getDemandTypeFromRequest() security.declarePublic('checkDestinationVocabFromDemandType') def checkDestinationVocabFromDemandType(self): """ we check if a vocabulary exists for destination """ if self.listPopulationDestinations()[0] != DEFAULT_VOCAB_VALUE: return True else: return False security.declarePublic('checkMotivationVocabFromDemandType') def checkMotivationVocabFromDemandType(self): """ we check if a vocabulary exists for motivation """ if self.listPopulationMotivations()[0] != DEFAULT_VOCAB_VALUE: return True else: return False security.declarePublic('calculatePrice') def calculatePrice(self): """ Calculate the price of the demand (demandType + motivation + destination) """ tst = getToolByName(self, 'portal_teleservices') total = 0 demandTypeTerm = tst.getTermObject('PopulationTeleService', 'DemandTypeTerm', self.getDemandType()) if demandTypeTerm != None: try: if hasattr(demandTypeTerm, 'price'): total += ( demandTypeTerm.getPrice() * self.getCopies() ) if self.checkMotivationVocabFromDemandType(): motivationTerm = tst.getTermObject('PopulationTeleService', 'MotivationTerm', self.getMotivation()) if motivationTerm == None: logger.warn("MotivationTerm with id %s not found" % self.getMotivation()) elif hasattr(motivationTerm, 'price'): total += ( motivationTerm.getPrice() * self.getCopies() ) if self.checkDestinationVocabFromDemandType(): destinationTerm = tst.getTermObject('PopulationTeleService', 'DestinationTerm', self.getDestination()) if destinationTerm == None: logger.warn("DestinationTerm with id %s not found" % self.getDestination()) elif hasattr(destinationTerm, 'price'): #how to calculate the sent price ? following the copies number ? #total += ( destinationTerm.getPrice() * self.getCopies() ) total += ( destinationTerm.getPrice() ) return total except: logger.warn('Error calculating price') return -1 else: logger.warn("DemandTypeTerm with id %s not found" % self.getDemandType()) return -1 security.declarePublic('noPaymentTransmit') def noPaymentTransmit(self): """ Transmit a demand if no payment is required for treatment This method is used for the automatic transition from waiting_payment """ tst = getToolByName(self, 'portal_teleservices') #changed this to self.calculatePrice()... #amount = self.getAmount() amount = self.calculatePrice() if amount == 0: return True destinationTerm = tst.getTermObject('PopulationTeleService', 'DestinationTerm', self.getDestination()) paymentRequiredFlag = False if destinationTerm == None: logger.warn("DestinationTerm with id %s not found" % self.getDestination()) elif not hasattr(destinationTerm, 'paymentRequired'): logger.warn("DestinationTerm with id %s have no property 'paymentRequired'" % self.getDestination()) elif destinationTerm.getPaymentRequired() == False: return True return False security.declarePublic('listPopulationDemandTypes') def listPopulationDemandTypes(self): """ This will return the vocab containing the on_line DemandTypeTerms found in portal_teleservices """ return self.portal_teleservices.listTermsVocab('PopulationTeleService', 'DemandTypeTerm', ['on_line']) security.declarePublic('listPopulationMotivations') def listPopulationMotivations(self): """ This will return the vocab containing the MotivationTerm found in portal_teleservices for a particular DemandTypeTerm """ tst = self.portal_teleservices dt_obj = tst.getTermObject('PopulationTeleService', 'DemandTypeTerm', self.getDemandType()) return tst.listRefVocab(dt_obj, 'motivationTerms', ['enabled']) security.declarePublic('listPopulationDestinations') def listPopulationDestinations(self): """ This will return the vocab containing the DestinationTerm found in portal_teleservices for a particular DemandTypeTerm """ tst = self.portal_teleservices dt_obj = tst.getTermObject('PopulationTeleService', 'DemandTypeTerm', self.getDemandType()) return tst.listRefVocab(dt_obj, 'destinationTerms', ['enabled']) security.declarePublic('setDestinationDefaultValue') def setDestinationDefaultValue(self): """ """ return DEFAULT_VOCAB_VALUE security.declarePublic('setMotivationDefaultValue') def setMotivationDefaultValue(self): """ """ return DEFAULT_VOCAB_VALUE security.declarePublic('setPaymentModeDefaultValue') def setPaymentModeDefaultValue(self): """ """ return DEFAULT_VOCAB_VALUE security.declarePublic('listPaymentModes') def listPaymentModes(self): """ we link a vocabulary to the String field so we save the key and display the value """ return self.portal_teleservices.listAvailablePaymentModes() security.declarePublic('checkIfOfficialCommentInOptionalFields') def checkIfOfficialCommentInOptionalFields(self): """ check if the officialComment field is enabled for the current DemandType """ return self.checkIfInOptionalFields(field="officialComment") security.declarePublic('checkIfCommentInOptionalFields') def checkIfCommentInOptionalFields(self): """ check if the Comment field is enabled for the current DemandType """ return self.checkIfInOptionalFields(field="comment") security.declarePublic('checkIfInOptionalFields') def checkIfInOptionalFields(self, field): """ return DEFAULT_NO_VALUE if the field is not enabled in DemandTypeTerm.optionalFields """ #we get the demandtype term dtt = self.portal_teleservices.getTermObject('PopulationTeleService', 'DemandTypeTerm', self.getDemandType()) if field in dtt.getOptionalFields(): return '' else: return DEFAULT_NO_VALUE security.declarePublic('checkIfChildNameInOptionalFields') def checkIfChildNameInOptionalFields(self): """ check if the ChildName field is enabled for the current DemandType """ return self.checkIfInOptionalFields(field="childName") security.declarePublic('checkIfChildSurnameInOptionalFields') def checkIfChildSurnameInOptionalFields(self): """ check if the ChildSurname field is enabled for the current DemandType """ return self.checkIfInOptionalFields(field="childSurname") security.declarePublic('checkIfChildBirthDateInOptionalFields') def checkIfChildBirthDateInOptionalFields(self): """ check if the ChildBirthDate field is enabled for the current DemandType """ dtt = self.portal_teleservices.getTermObject('PopulationTeleService', 'DemandTypeTerm', self.getDemandType()) if 'childBirthDate' in dtt.getOptionalFields(): return '' else: return DEFAULT_DATE_NO_VALUE security.declarePublic('checkFieldDisplayInPopulationTeleserviceView') def checkFieldDisplayInPopulationTeleserviceView(self, fieldName, fieldValue): """ check if a populationteleservice attribute can be displayed in populationteleservice_view """ if fieldName in ('title', 'id', 'excludeFromNav'): return False elif fieldValue in (None,'', DEFAULT_NO_VALUE, DEFAULT_DATE_NO_VALUE): #we cannot put 0 here because No is also removed return False elif fieldName == 'amount' and fieldValue == 0: return False else: return True security.declarePublic('checkIfChildContactPersonInOptionalFields') def checkIfChildContactPersonInOptionalFields(self): """ check if the ChildContactPerson field is enabled for the current DemandType """ return self.checkIfInOptionalFields(field="childContactPerson") security.declarePublic('checkIfDeceasedBirthDateOrNationalRegisterInOptionalFields') def checkIfDeceasedBirthDateOrNationalRegisterInOptionalFields(self): """ check if the deceasedBirthDateOrNationalRegister field is enabled for the current DemandType """ dtt = self.portal_teleservices.getTermObject('PopulationTeleService', 'DemandTypeTerm', self.getDemandType()) if 'deceasedBirthDateOrNationalRegister' in dtt.getOptionalFields(): return '' else: return DEFAULT_DATE_NO_VALUE security.declarePublic('checkIfDeceasedNameInOptionalFields') def checkIfDeceasedNameInOptionalFields(self): """ check if the deceasedName field is enabled for the current DemandType """ return self.checkIfInOptionalFields(field="deceasedName") security.declarePublic('checkIfDeceasedName2InOptionalFields') def checkIfDeceasedName2InOptionalFields(self): """ check if the deceasedName2 field is enabled for the current DemandType """ return self.checkIfInOptionalFields(field="deceasedName2") registerType(PopulationTeleService, PROJECTNAME) # end of class PopulationTeleService ##code-section module-footer #fill in your manual code here ##/code-section module-footer