def roleset_validator(node, value): oneof = colander.OneOf(USER_MANAGEMENT_ROLES) [oneof(node, item) for item in value]
class Excavation(Base): __tablename__ = 'excavation' __table_args__ = ( {"schema": schema} ) __colanderalchemy_config__ = { 'title': _('Application form for permission to carry out excavation work'), 'plural': _('Excavation forms') } __c2cgeoform_config__ = { 'duplicate': True } id = Column(Integer, primary_key=True, info={ # the `colanderalchemy` property allows to set a custom title for the # column or to use a specific widget. 'colanderalchemy': { 'title': _('Permission Number'), 'widget': HiddenWidget() }}) hash = Column(Text, unique=True, default=lambda: str(uuid4()), info={ 'colanderalchemy': { 'widget': HiddenWidget() }, 'c2cgeoform': { 'duplicate': False }}) reference_number = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Reference Number') }, 'c2cgeoform': { 'duplicate': False }}) request_date = Column(Date, nullable=True, info={ 'colanderalchemy': { 'title': _('Request Date') }}) description = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Description of the Work'), 'widget': deform.widget.TextAreaWidget(rows=3), }}) motif = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Motive for the Work'), 'widget': deform.widget.TextAreaWidget(rows=3), }}) situations = relationship( "Situation", secondary=situation_for_permission, order_by=Situation.name, cascade="save-update,merge,refresh-expire", info={'colanderalchemy': {'exclude': True}}) # by default a Deform sequence widget is used for relationship columns, # which, for example, allows to create new contact persons in a sub-form. contact_persons = relationship( ContactPerson, # make sure persons are deleted when removed from the relation cascade="all, delete-orphan", info={'colanderalchemy': { 'title': _('Contact Persons') }}) location_district_id = Column( Integer, ForeignKey('c2cgeoform_demo.district.id'), info={ 'colanderalchemy': { 'title': _('District'), 'widget': RelationSelect2Widget( District, 'id', 'name', order_by='name', default_value=('', _('- Select -')) ) } } ) # if the name for the options should be internationalized, one # can create columns like 'name_fr' and 'name_de' in the table # 'District'. then in the translation files, the column name # can be "translated" (e.g. the French "translation" for the # column name would be 'name_fr'). to apply the translation use # the label `_('name'))` instead of `name`. location_street = Column(Text, nullable=False, info={ 'colanderalchemy': { 'title': _('Street') }}) location_postal_code = Column(Text, nullable=False, info={ 'colanderalchemy': { 'title': _('Postal Code') }}) location_town = Column(Text, nullable=False, info={ 'colanderalchemy': { 'title': _('Town') }}) # this is a search field to search for an address address_id = Column( Integer, ForeignKey('c2cgeoform_demo.address.id'), info={ 'colanderalchemy': { 'title': _('Address'), 'widget': RelationSearchWidget( url=lambda request: request.route_url('addresses'), model=Address, min_length=1, id_field='id', label_field='label' ) } } ) # to show a map for a geometry column, the column has to be defined as # follows. location_position = Column( geoalchemy2.Geometry('POINT', 4326, management=True), info={ 'colanderalchemy': { 'title': _('Position'), 'typ': colander_ext.Geometry('POINT', srid=4326, map_srid=3857), 'widget': deform_ext.MapWidget() }}) # Person in Charge for the Work responsible_title = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Title'), 'validator': colander.OneOf(['mr', 'mrs']), 'widget': deform.widget.SelectWidget(values=( ('', _('- Select -')), ('mr', _('Mr.')), ('mrs', _('Mrs.')) )) }}) responsible_name = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Name') }}) responsible_first_name = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('First Name') }}) responsible_mobile = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Mobile Phone') }}) responsible_mail = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Mail'), 'validator': colander.Email() }}) responsible_company = Column(Text, nullable=True, info={ 'colanderalchemy': { 'title': _('Company') }}) validated = Column(Boolean, info={ 'colanderalchemy': { 'title': _('Validation'), 'label': _('Validated') }, 'c2cgeoform': { 'duplicate': False }}) # Work footprint work_footprint = Column( geoalchemy2.Geometry('MULTIPOLYGON', 4326, management=True), info={ 'colanderalchemy': { 'title': _('Footprint for the Work'), 'typ': colander_ext.Geometry( 'MULTIPOLYGON', srid=4326, map_srid=3857), 'widget': deform_ext.MapWidget() }}) # Photo photos = relationship( Photo, cascade="all, delete-orphan", info={ 'colanderalchemy': { 'title': _('Photo') }})
class MembershipInfo(colander.Schema): yes_no = ((u'yes', _(u'Yes')), (u'no', _(u'No'))) # at_least_three_works = colander.SchemaNode( # colander.String(), # title=_(u'I have been the (co-)creator of at least three titles ' # 'in one of the functions mentioned under (1)'), # validator=colander.OneOf([x[0] for x in yes_no]), # widget=deform.widget.RadioChoiceWidget(values=yes_no)) ## TODO: inColSocName if member_of_colsoc = yes ## css/jquery: fixed; TODO: validator #def colsoc_validator(node, form): #log.info("validating...........................................") #print(value['member_of_colsoc']) #log.info(node.get('other_colsoc')) #log.info(node.get('other_colsoc-1')) #log.info(node.cstruct_children('other_colsoc')) #log.info(node.get_value('other_colsoc-1')) #log.info(dir(node)) #log.info(node['member_of_colsoc']) #import pdb; pdb.set_trace() #if value['member_of_colsoc'] #exc = colander.Invalid( # form, "if colsoc, give name!") #exc['name_of_colsoc'] = "if colsoc, give name!" #log.info("end----------------------------------------") #pass membership_type = colander.SchemaNode( colander.String(), title=_(u'I want to become a ... (choose membership type)'), description=_(u'choose the type of membership.'), widget=deform.widget.RadioChoiceWidget(values=( (u'normal', _(u'normal member. ' 'Normal members have to be natural persons ' 'who register at least three works with C3S ' 'they created themselves. This applies to composers, ' 'lyricists and remixers. They get a vote.')), (u'investing', _(u'investing member. ' 'Investing members can be natural persons or legal ' 'bodies that do not register works with C3S. ' 'They do not get a vote, but may counsel.'))), )) # member_is_artist = colander.SchemaNode( # colander.String(), # title=_( # u'I am at least one of: composer, lyricist, ' # 'remixer, arranger, producer, DJ (i.e. musician)'), # description=_( # u'You have to be a musician to become a regular member of C3S SCE.' # 'Or choose to become a supporting member.'), # validator=colander.OneOf([x[0] for x in yes_no]), # widget=deform.widget.RadioChoiceWidget( # values=(yes_no), # ), # ) member_of_colsoc = colander.SchemaNode( colander.String(), title= _(u'Currently, I am a member of (at least) one other collecting society.' ), validator=colander.OneOf([x[0] for x in yes_no]), widget=deform.widget.RadioChoiceWidget(values=yes_no), oid="other_colsoc", #validator=colsoc_validator ) name_of_colsoc = colander.SchemaNode( colander.String(), title=_(u'If so, which one(s)? (comma separated)'), description=_( u'Please tell us which collecting societies ' 'you are a member of. ' 'If more than one, please separate them by comma(s).'), missing=unicode(''), oid="colsoc_name", #validator=colander.All( # colsoc_validator, #) ) def statute_validator(node, value): if not value: raise Invalid( node, _(u'You must confirm to have access ' u'to the C3S SCE statute')) got_statute = colander.SchemaNode( #colander.String(), colander.Bool(true_val=u'yes'), title=_(u'I got to read an electronic copy of the ' u'C3S SCE statute'), description=_(u'You must confirm to have access to the statute.'), #widget=deform.widget.CheckboxChoiceWidget( # values=(('yes', _(u'Yes')),)), widget=deform.widget.CheckboxWidget(), #validator=colander.OneOf(['yes', ]), validator=statute_validator, required=True, label=_('Yes'), )
class FieldSequenceComparableSchema(SingleLine): """SingleLine of FieldSequenceComparable value.""" validator = colander.OneOf( [x for x in FieldSequenceComparator.__members__])
class EntityForm(colander.MappingSchema): label = colander.SchemaNode(colander.String()) category = colander.SchemaNode(colander.String(), validator=colander.OneOf(CATEGORIES)) selectors = EntitySelectors() list = colander.SchemaNode(ListRef())
title=_(u'I want to become a ... ' u'(choose membership type, see C3S SCE statute sec. 4)'), description=_(u'choose the type of membership.'), widget=deform.widget.RadioChoiceWidget( values=( (i['name'],i['description']) for i in customization.membership_types ), ), oid='membership_type' ) if customization.enable_colsoc_association: member_of_colsoc = colander.SchemaNode( colander.String(), title=_( u'Currently, I am a member of (at least) one other ' u'collecting society.'), validator=colander.OneOf([x[0] for x in yes_no]), widget=deform.widget.RadioChoiceWidget(values=yes_no), oid="other_colsoc", # validator=colsoc_validator ) name_of_colsoc = colander.SchemaNode( colander.String(), title=_(u'If so, which one(s)? Please separate multiple ' u'collecting societies by comma.'), description=_( u'Please tell us which collecting societies ' u'you are a member of. ' u'If more than one, please separate them by comma.'), missing=unicode(''), oid="colsoc_name", )
class PoolElementsForm(SchemaNode): """The form of the elements attribute returned by the pool sheet.""" schema_type = colander.String validator = colander.OneOf(['paths', 'content', 'omit']) missing = 'paths'
def payment_type_validator(node, kw): payment_types = kw.get('payment_types') return colander.OneOf([payment_type[0] for payment_type in payment_types])
friend = colander.SchemaNode(colander.Tuple()) friend.add( colander.SchemaNode(colander.Int(), validator=colander.Range(0, 9999), name='rank')) friend.add(colander.SchemaNode(colander.String(), name='name')) print(friend.typ) for each_p in friend: print(each_p.typ) phone = colander.SchemaNode( colander.Mapping(), colander.SchemaNode(colander.String(), validator=colander.OneOf(['home', 'work']), name='location')) phone.add(colander.SchemaNode(colander.String(), name='number')) print(phone.typ) for each_p in phone: print(each_p.typ) schema = colander.SchemaNode(colander.Mapping()) schema.add(colander.SchemaNode(colander.String(), name='name')) schema.add( colander.SchemaNode(colander.Int(), name='age', validator=colander.Range(0, 200))) schema.add(colander.SequenceSchema(friend, name='friends')) schema.add(colander.SequenceSchema(phone, name='phones'))
def item_id_validator(node, kw): items = kw.get('items') return colander.OneOf([item[0] for item in items])
def client_id_validator(node, kw): clients = kw.get('clients') return colander.OneOf([client[0] for client in clients])
class Phone(colander.MappingSchema): location = colander.SchemaNode(colander.String(), validator=colander.OneOf(['home', 'work'])) number = colander.SchemaNode(colander.String())
class ProfileSchema(colander.MappingSchema): role = colander.SchemaNode(colander.String(), validator=colander.OneOf(['Healer', 'DPS']), missing=None) listed_3s = colander.SchemaNode(colander.Boolean(), missing=None) listed_2s = colander.SchemaNode(colander.Boolean(), missing=None)
def deferred_company_validator(node, kw): """ Check that the validated name is one of the original choices """ return colander.OneOf(get_companies_choices())
class SaveUpdateSchema(CSRFProtectedSchema, colander.MappingSchema): """An API schema for bodhi.server.services.updates.new_update().""" builds = Builds(colander.Sequence(accept_scalar=True), preparer=[util.splitter]) bugs = Bugs(colander.Sequence(accept_scalar=True), missing=None, preparer=[util.splitter]) close_bugs = colander.SchemaNode( colander.Boolean(), missing=True, ) type = colander.SchemaNode( colander.String(), validator=colander.OneOf(list(UpdateType.values())), ) request = colander.SchemaNode( colander.String(), validator=colander.OneOf(list(UpdateRequest.values())), missing='testing', ) severity = colander.SchemaNode( colander.String(), validator=colander.OneOf(list(UpdateSeverity.values())), missing='unspecified', ) notes = colander.SchemaNode( colander.String(), validator=colander.Length(min=2), ) autokarma = colander.SchemaNode( colander.Boolean(), missing=True, ) stable_karma = colander.SchemaNode( colander.Integer(), validator=colander.Range(min=1), missing=3, ) unstable_karma = colander.SchemaNode( colander.Integer(), validator=colander.Range(max=-1), missing=-3, ) suggest = colander.SchemaNode( colander.String(), validator=colander.OneOf(list(UpdateSuggestion.values())), missing='unspecified', ) edited = colander.SchemaNode( colander.String(), missing='', ) requirements = colander.SchemaNode( colander.String(), missing=None, ) require_bugs = colander.SchemaNode( colander.Boolean(), missing=True, ) require_testcases = colander.SchemaNode( colander.Boolean(), missing=True, )
class DeclarationOfIntent(colander.MappingSchema): """ colander schema for declaration of intent/ application form """ type_of_creator = (('composer', _(u'composer')), ('lyricist', _(u'lyricist')), ('music producer', _(u'music producer')), ('remixer', _(u'remixer')), ('dj', _(u'DJ'))) activity = colander.SchemaNode( deform.Set(allow_empty=True), title=_( u"I'm musically involved in creating at least three songs, " "and I\'m considering to ask C3S to administer the rights " " to some of my songs. I am active as a " "(multiple selection possible)"), widget=deform.widget.CheckboxChoiceWidget(values=type_of_creator), missing=unicode('')) yes_no = ((u'yes', _(u'Yes')), (u'no', _(u'No'))) # at_least_three_works = colander.SchemaNode( # colander.String(), # title=_(u'I have been the (co-)creator of at least three titles ' # 'in one of the functions mentioned under (1)'), # validator=colander.OneOf([x[0] for x in yes_no]), # widget=deform.widget.RadioChoiceWidget(values=yes_no)) member_of_colsoc = colander.SchemaNode( colander.String(), title=_( u'Currently, I am a member of another collecting society.'), validator=colander.OneOf([x[0] for x in yes_no]), widget=deform.widget.RadioChoiceWidget(values=yes_no), ) ## TODO: inColSocName if member_of_colsoc = yes name_of_colsoc = colander.SchemaNode(colander.String(), title=_(u'If so, which one?'), missing=unicode('')) invest_member = colander.SchemaNode( colander.String(), title=_( u'I am considering to join C3S as a supporting member only. ' 'This option is also available to members of other collecting ' 'societies without quitting those.'), validator=colander.OneOf([x[0] for x in yes_no]), widget=deform.widget.RadioChoiceWidget(values=yes_no)) firstname = colander.SchemaNode(colander.String(), title=_(u"(Real) First Name")) lastname = colander.SchemaNode(colander.String(), title=_(u"(Real) Last Name")) email = colander.SchemaNode(colander.String(), title=_(u'Email'), validator=colander.Email()) # address1 = colander.SchemaNode(colander.String(), # title=_(u'Street & No.')) # address2 = colander.SchemaNode(colander.String(), # missing=unicode(''), # title=_(u"address cont'd")) # postCode = colander.SchemaNode(colander.String(), # title=_(u'Post Code')) city = colander.SchemaNode(colander.String(), title=_(u'City')) # region = colander.SchemaNode( # colander.String(), # title=_(u'Federal State / Province / County'), # missing=unicode('')) country = colander.SchemaNode( colander.String(), title=_(u'Country'), default=country_default, widget=deform.widget.SelectWidget(values=country_codes), ) # TODO: # Date of birth (dd/mm/yyyy) (three fields) # size doesn't have any effect?! date_of_birth = colander.SchemaNode( colander.Date(), title=_(u'Date of Birth'), css_class="hasDatePicker", #widget = deform.widget.DatePWidget(), default=datetime.date(2013, 1, 1), validator=Range( min=datetime.date(1913, 1, 1), max=datetime.date(2000, 1, 1), min_err=_(u'${val} is earlier than earliest date ${min}'), max_err=_(u'${val} is later than latest date ${max}'))) opt_band = colander.SchemaNode(colander.String(), title=_(u'optional: Band/Artist name'), missing=u'') opt_URL = colander.SchemaNode(colander.String(), title=_(u'optional: Homepage'), missing=u'') #print(country_codes()) #understood_declaration = colander.SchemaNode( #colander.String(), #title=_(u'I have read and understood the text of the ' #'declaration of intent.'), ## validator=colander.OneOf(), #widget=deform.widget.CheckboxChoiceWidget( #values=(('yes', _(u'Yes')),)), #) #consider_joining = colander.SchemaNode( #colander.String(), #title=_(u'I seriously consider to join the C3S and want to ' #'be notified via e-mail about its foundation.'), ## validator=colander.OneOf([x[0] for x in yes_no]), #widget=deform.widget.CheckboxChoiceWidget( #values=(('yes', _(u'Yes')),)), #) noticed_dataProtection = colander.SchemaNode( colander.String(), title=_(u'I have taken note of the Data Protection Declaration ' 'which is part of this text and can be read separately ' 'at http://www.c3s.cc/disclaimer-en.html and agree with ' 'it. I know that I may revoke this consent at any time.'), # validator=colander.OneOf([x[0] for x in yes_no]), widget=deform.widget.CheckboxChoiceWidget(values=(('yes', _(u'Yes')), )), ) _LOCALE_ = colander.SchemaNode(colander.String(), widget=deform.widget.HiddenWidget(), default=locale_name)
class ListUpdateSchema(PaginatedSchema, SearchableSchema, Cosmetics): """An API schema for bodhi.server.services.updates.query_updates().""" alias = Builds( colander.Sequence(accept_scalar=True), location="querystring", missing=None, preparer=[util.splitter], ) approved_since = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) approved_before = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) bugs = Bugs( colander.Sequence(accept_scalar=True), location="querystring", missing=None, preparer=[util.splitter], ) builds = Builds( colander.Sequence(accept_scalar=True), location="querystring", missing=None, preparer=[util.splitter], ) critpath = colander.SchemaNode( colander.Boolean(true_choices=('true', '1')), location="querystring", missing=None, ) cves = CVEs( colander.Sequence(accept_scalar=True), location="querystring", missing=None, preparer=[util.splitter], ) locked = colander.SchemaNode( colander.Boolean(true_choices=('true', '1')), location="querystring", missing=None, ) modified_since = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) modified_before = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) active_releases = Releases( colander.Boolean(true_choices=('true', '1')), location="querystring", missing=False, ) packages = Packages( colander.Sequence(accept_scalar=True), location="querystring", missing=None, preparer=[util.splitter], ) pushed = colander.SchemaNode( colander.Boolean(true_choices=('true', '1')), location="querystring", missing=None, ) pushed_since = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) pushed_before = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) releases = Releases( colander.Sequence(accept_scalar=True), location="querystring", missing=None, preparer=[util.splitter], ) # This singular version of the plural "releases" is purely for bodhi1 # backwards compat (mostly for RSS feeds) - threebean release = colander.SchemaNode( colander.String(), location="querystring", missing=None, ) request = colander.SchemaNode( colander.String(), location="querystring", missing=None, validator=colander.OneOf(list(UpdateRequest.values())), ) severity = colander.SchemaNode( colander.String(), location="querystring", missing=None, validator=colander.OneOf(list(UpdateSeverity.values())), ) status = colander.SchemaNode( colander.String(), location="querystring", missing=None, validator=colander.OneOf(list(UpdateStatus.values())), ) submitted_since = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) submitted_before = colander.SchemaNode( colander.DateTime(), location="querystring", missing=None, ) suggest = colander.SchemaNode( colander.String(), location="querystring", missing=None, validator=colander.OneOf(list(UpdateSuggestion.values())), ) type = colander.SchemaNode( colander.String(), location="querystring", missing=None, validator=colander.OneOf(list(UpdateType.values())), ) content_type = colander.SchemaNode( colander.String(), location="querystring", missing=None, validator=colander.OneOf(list(ContentType.values())), ) user = colander.SchemaNode( colander.String(), location="querystring", missing=None, ) updateid = Builds( colander.Sequence(accept_scalar=True), location="querystring", missing=None, preparer=[util.splitter], )
import colander import six from pyramid import httpexceptions from pyramid.security import NO_PERMISSION_REQUIRED from cliquet import errors from cliquet import logger from cliquet import Service from cliquet.utils import merge_dicts, build_request, build_response valid_http_method = colander.OneOf( ('GET', 'HEAD', 'DELETE', 'TRACE', 'POST', 'PUT', 'PATCH')) def string_values(node, cstruct): """Validate that a ``colander.Mapping`` only has strings in its values. .. warning:: Should be associated to a ``colander.Mapping`` schema node. """ are_strings = [isinstance(v, six.string_types) for v in cstruct.values()] if not all(are_strings): error_msg = '%s contains non string value' % cstruct raise colander.Invalid(node, error_msg) class BatchRequestSchema(colander.MappingSchema): method = colander.SchemaNode(colander.String(), validator=valid_http_method,
class BatchHTTPMethod(SchemaNode): """An HTTP method in a batch request.""" schema_type = colander.String validator = colander.OneOf(['GET', 'POST', 'PUT', 'OPTIONS']) missing = colander.required
def parse_duration(duration, format=None): start_date = duration.lower end_date = duration.upper if is_infinite(start_date): start_date = None elif format is not None: start_date = start_date.strftime(format) if is_infinite(end_date): end_date = None elif format is not None: end_date = end_date.strftime(format) return start_date, end_date OKStatus = colander.SchemaNode(colander.String(), validator=colander.OneOf(['ok'])) ErrorStatus = colander.SchemaNode(colander.String(), validator=colander.OneOf(['error'])) WEBINDEXTEMPLATES = {} def load_web_index_template(filename='index.html', config=None): """Loads/Caches the index.html file from the dist/web directory, and rewrites the asset paths to the /static dir. Note that this is only updated on server startup. """ html = WEBINDEXTEMPLATES.get(filename) if html is None: dir_name = os.path.join(os.path.dirname(__file__), 'static', 'dist',
class KeywordComparableSchema(SingleLine): """SingleLine of KeywordComparable value.""" validator = colander.OneOf([x for x in KeywordComparator.__members__])
class Invoice(Task, InvoiceCompute): """ Invoice Model """ __tablename__ = 'invoice' __table_args__ = default_table_args __mapper_args__ = { 'polymorphic_identity': 'invoice', } id = Column( ForeignKey('task.id'), primary_key=True, info={ 'colanderalchemy': { 'widget': deform.widget.HiddenWidget(), 'missing': colander.drop, } }, ) paid_status = Column( String(10), default='waiting', info={ 'colanderalchemy': { 'widget': deform.widget.SelectWidget(values=INVOICE_STATES), 'title': u'Statut de la facture', "validator": colander.OneOf(dict(INVOICE_STATES).keys()), } }) # seems it's not used anymore deposit = deferred( Column(Integer, nullable=False, info={'colanderalchemy': { 'exclude': True }}, default=0), group='edit', ) # Common with only estimations course = deferred(Column( Integer, info={'colanderalchemy': { 'title': u"Concerne une formation" }}, nullable=False, default=0), group='edit') # Common with only cancelinvoices financial_year = Column(Integer, info={ 'colanderalchemy': { 'title': u"Année fiscale de référence", 'widget': deform.widget.TextInputWidget(mask='9999'), } }, default=0) exported = deferred(Column( Boolean(), info={'colanderalchemy': { 'title': u"A déjà été exportée ?" }}, default=False), group="edit") estimation_id = Column( ForeignKey('estimation.id'), info={'colanderalchemy': { 'missing': colander.drop }}, ) estimation = relationship( "Estimation", primaryjoin="Invoice.estimation_id==Estimation.id", info={ 'colanderalchemy': forms.EXCLUDED, 'export': { 'exclude': True }, }, ) state_manager = DEFAULT_ACTION_MANAGER['invoice'] paid_states = ('resulted', ) not_paid_states = ( 'valid', 'paid', ) valid_states = paid_states + not_paid_states _number_tmpl = u"{s.company.name} {s.date:%Y-%m} F{s.company_index}" _name_tmpl = u"Facture {0}" _deposit_name_tmpl = u"Facture d'acompte {0}" _sold_name_tmpl = u"Facture de solde {0}" def _get_project_index(self, project): """ Return the index of the current object in the associated project :param obj project: A Project instance in which we will look to get the current doc index :returns: The next number :rtype: int """ return project.get_next_invoice_index() def _get_company_index(self, company): """ Return the index of the current object in the associated company :param obj company: A Company instance in which we will look to get the current doc index :returns: The next number :rtype: int """ return company.get_next_invoice_index() def set_deposit_label(self): self.name = self._deposit_name_tmpl.format(self.project_index) def set_sold_label(self): self.name = self._sold_name_tmpl.format(self.project_index) def set_project(self, project): self.project = project def gen_cancelinvoice(self, user): """ Return a cancel invoice with self's informations """ cancelinvoice = CancelInvoice( company=self.company, project=self.project, customer=self.customer, phase=self.phase, user=user, ) cancelinvoice.address = self.address cancelinvoice.workplace = self.workplace cancelinvoice.description = self.description cancelinvoice.invoice = self cancelinvoice.expenses_ht = -1 * self.expenses_ht cancelinvoice.financial_year = self.financial_year cancelinvoice.prefix = self.prefix cancelinvoice.display_units = self.display_units cancelinvoice.line_groups = [] for group in self.line_groups: cancelinvoice.line_groups.append(group.gen_cancelinvoice_group()) order = self.get_next_row_index() for discount in self.discounts: discount_line = TaskLine( cost=discount.amount, tva=discount.tva, quantity=1, description=discount.description, order=order, unity='', ) discount_line.product_id = Product.first_by_tva_value(discount.tva) order += 1 cancelinvoice.default_line_group.lines.append(discount_line) for index, payment in enumerate(self.payments): paid_line = TaskLine( cost=math_utils.reverse_tva( payment.amount, payment.tva.value, False, ), tva=payment.tva.value, quantity=1, description=u"Paiement {0}".format(index + 1), order=order, unity='NONE', ) paid_line.product_id = Product.first_by_tva_value( payment.tva.value) order += 1 cancelinvoice.default_line_group.lines.append(paid_line) cancelinvoice.mentions = self.mentions cancelinvoice.payment_conditions = u"Réglé" return cancelinvoice def get_next_row_index(self): return len(self.default_line_group.lines) + 1 def record_payment(self, **kw): """ Record a payment for the current invoice """ resulted = kw.pop('resulted', False) if kw['amount'] > 0: payment = Payment() for key, value in kw.iteritems(): setattr(payment, key, value) log.info(u"Amount : {0}".format(payment.amount)) self.payments.append(payment) return self.check_resulted( force_resulted=resulted, user_id=kw['user_id'], ) def check_resulted(self, force_resulted=False, user_id=None): """ Check if the invoice is resulted or not and set the appropriate status """ log.debug(u"-> There still to pay : %s" % self.topay()) if self.topay() <= 0 or force_resulted: self.paid_status = 'resulted' elif len(self.payments) > 0 or self.cancelinvoice_amount() > 0: self.paid_status = 'paid' else: self.paid_status = 'waiting' if user_id is not None: status_record = TaskStatus(status_code=self.paid_status, status_person_id=user_id, status_comment='') self.statuses.append(status_record) return self def duplicate(self, user, project, phase, customer): """ Duplicate the current invoice """ invoice = Invoice( self.company, customer, project, phase, user, ) if customer.id == self.customer_id: invoice.address = self.address else: invoice.address = customer.full_address invoice.workplace = self.workplace invoice.description = self.description invoice.payment_conditions = self.payment_conditions invoice.deposit = self.deposit invoice.course = self.course invoice.display_units = self.display_units invoice.expenses_ht = self.expenses_ht invoice.financial_year = datetime.date.today().year invoice.line_groups = [] for group in self.line_groups: invoice.line_groups.append(group.duplicate()) for line in self.discounts: invoice.discounts.append(line.duplicate()) invoice.mentions = self.mentions return invoice def __repr__(self): return u"<Invoice id:{s.id}>".format(s=self) def __json__(self, request): datas = Task.__json__(self, request) datas.update( dict( deposit=self.deposit, course=self.course, financial_year=self.financial_year, exported=self.exported, estimation_id=self.estimation_id, )) return datas def is_tolate(self): """ Return True if a payment is expected since more than 45 days """ res = False if self.paid_status in ('waiting', 'paid'): today = datetime.date.today() elapsed = today - self.date if elapsed > datetime.timedelta(days=45): res = True else: res = False return res
def deferred_company_datas_validator(node, kw): ids = [entry[0] for entry in CompanyActivity.query('id')] return colander.OneOf(ids)
class DocumentSchema(colander.MappingSchema): """Schema for ``Document``""" # id = colander.SchemaNode( # UUID(), # missing=colander.drop, # ) title = colander.SchemaNode(colander.String(), ) abstract = colander.SchemaNode( colander.String(), missing=colander.drop, ) created = colander.SchemaNode( colander.DateTime(default_tzinfo=TZINFO), missing=deferred_datetime_missing, ) revised = colander.SchemaNode( colander.DateTime(default_tzinfo=TZINFO), missing=deferred_datetime_missing, ) license = LicenseSchema(missing=colander.drop, ) original_license = LicenseSchema(missing=colander.drop, ) language = colander.SchemaNode( colander.String(), default=DEFAULT_LANGUAGE, missing=colander.drop, ) derived_from = colander.SchemaNode( colander.String(), missing=colander.drop, ) derived_from_title = colander.SchemaNode( colander.String(), missing=colander.drop, ) derived_from_uri = colander.SchemaNode( colander.String(), missing=colander.drop, ) content = colander.SchemaNode( colander.String(), missing=colander.drop, ) submitter = UserSchema() authors = RoleSequence(validator=colander.Length(min=1)) # maintainers publishers = RoleSequence(validator=colander.Length(min=1)) # copyright holders licensors = RoleSequence(validator=colander.Length(min=1)) translators = RoleSequence(missing=colander.drop) editors = RoleSequence(missing=colander.drop) illustrators = RoleSequence(missing=colander.drop) media_type = colander.SchemaNode( colander.String(), default=DOCUMENT_MEDIATYPE, missing=colander.drop, validator=colander.OneOf([DOCUMENT_MEDIATYPE, BINDER_MEDIATYPE]), ) subjects = colander.SchemaNode( colander.List(), missing=colander.drop, ) keywords = colander.SchemaNode( colander.List(), missing=colander.drop, ) print_style = colander.SchemaNode( colander.String(), missing=colander.drop, )
class PhraseFinder(Schema): """ Schema for the phrases finder """ widget = PhraseFinderWidget() # overrides the default template description = "Find and process phrases in text." MODES = (('tokenize', 'Tokenize phrases in text'), ('append', 'Append phrases to text'), ('replace', 'Replace all text with found phrases')) SCORING = ( ('default', 'Default'), ('npmi', 'NPMI: Slower, better with common words'), ) LEVELS = ( (2, 'Bigrams'), (3, 'Trigrams'), (4, 'Quadgrams'), ) mode = colander.SchemaNode( colander.String(), validator=colander.OneOf([x[0] for x in MODES]), default=MODES[0][0], missing=MODES[0][0], title="Operating mode", widget=deform.widget.RadioChoiceWidget(values=MODES)) level = colander.SchemaNode( colander.Int(), default=LEVELS[0][0], missing=LEVELS[0][0], title='N-gram level', widget=deform.widget.RadioChoiceWidget(values=LEVELS), description='How many words to include in phrase detection', ) min_count = colander.SchemaNode( colander.Int(), default=5, missing=5, title='Minimum number', description='Ignore all words with total count lower then this', ) threshold = colander.SchemaNode( colander.Float(), default=10.0, missing=10.0, title='Threshold', description='Score threshold for forming phrases. Higher means ' 'fewer phrases.', ) scoring = colander.SchemaNode( colander.String(), validator=colander.OneOf([x[0] for x in SCORING]), default=SCORING[0][0], missing=SCORING[0][0], title="Scoring algorithm", widget=deform.widget.RadioChoiceWidget(values=SCORING))
def response_behavior_validator(): return colander.OneOf(["full", "light", "diff"])
class CustomerTypeSchema(colander.MappingSchema): customer_type = colander.SchemaNode(colander.String(), validator=colander.OneOf(['individual', 'business']), missing=colander.drop)
def op_validator(): op_values = ["test", "add", "remove", "replace", "move", "copy"] return colander.OneOf(op_values)
def deferred_category_validator(node, kw): categories = kw.get('categories', []) return colander.OneOf([x[0] for x in categories])
def deferred_deadline_id_validator(node, kw): return colander.OneOf([c[0] for c in CompetenceDeadline.query('id').all()])