Example #1
0
 def tearDown(self):
     # maybe I need to check and remove globals here,
     # so the other tests are not compromised
     #del engine
     from c3smembership.models import DBSession
     DBSession.close()
     DBSession.remove()
 def setUp(self):
     self.config = testing.setUp()
     self.config.include('pyramid_mailer.testing')
     self.config.registry.settings['c3smembership.url'] = 'http://foo.com'
     self.config.registry.settings['c3smembership.mailaddr'] = '*****@*****.**'
     DBSession.remove()
     self.session = _initTestingDB()
Example #3
0
 def tearDown(self):
     """
     clean up after a test case
     """
     DBSession.close()
     DBSession.remove()
     testing.tearDown()
Example #4
0
def verify_mailaddress_conf(request):
    '''
    let member confirm her email address by clicking a link
    '''
    user_email = request.matchdict['email']
    refcode = request.matchdict['refcode']
    token = request.matchdict['token']
    # try to get entry from DB
    afm = C3sMember.get_by_code(refcode)
    if isinstance(afm, NoneType):  # no entry?
        #print "entry not found"
        return {
            'confirmed': False,
            'firstname': 'foo',
            'lastname': 'bar',
            'result_msg': 'bad URL / bad codes. please contact [email protected]!',
        }
    # check token
    if ('_used' in afm.email_confirm_token):  # token was invalidated already
        #print "the token is empty"
        return {
            'confirmed': False,
            'firstname': afm.firstname,
            'lastname': afm.lastname,
            'result_msg': 'your token is invalid. please contact [email protected]!',
        }

    try:
        assert(afm.email_confirm_token in token)
        assert(token in afm.email_confirm_token)
        assert(afm.email in user_email)
        assert(user_email in afm.email)
    except:
        return {
            'confirmed': False,
            'firstname': 'foo',
            'lastname': 'bar',
            'result_msg': 'bad token/email. please contact [email protected]!',
        }

    afm.email_is_confirmed = True
    afm.email_confirm_token += u'_used'
    DBSession.flush()
    # notify staff
    message = Message(
        subject='[C3S Yes!] afm email confirmed',
        sender='*****@*****.**',
        recipients=[request.registry.settings['c3smembership.mailaddr'], ],
        body=u'see {}/detail/{}'.format(
            request.registry.settings['c3smembership.url'],
            afm.id)
    )
    mailer = get_mailer(request)
    mailer.send(message)
    return {
        'confirmed': True,
        'firstname': afm.firstname,
        'lastname': afm.lastname,
        'result_msg': u'',
    }
Example #5
0
 def setUp(self):
     super(C3sMembershipModelTests, self).setUp()
     with transaction.manager:
         member1 = C3sMember(  # german
             firstname=u'SomeFirstnäme',
             lastname=u'SomeLastnäme',
             email=u'*****@*****.**',
             address1=u"addr one",
             address2=u"addr two",
             postcode=u"12345",
             city=u"Footown Mäh",
             country=u"Foocountry",
             locale=u"DE",
             date_of_birth=date.today(),
             email_is_confirmed=False,
             email_confirm_code=u'ABCDEFGFOO',
             password=u'arandompassword',
             date_of_submission=date.today(),
             membership_type=u'normal',
             member_of_colsoc=True,
             name_of_colsoc=u"GEMA",
             num_shares=u'23',
         )
         DBSession.add(member1)
         DBSession.flush()
Example #6
0
 def tearDown(self):
     # maybe I need to check and remove globals here,
     # so the other tests are not compromised
     #del engine
     from c3smembership.models import DBSession
     DBSession.close()
     DBSession.remove()
def init():
    #config_uri = 'development.ini'
    #setup_logging(config_uri)
    #settings = get_appsettings(config_uri)
    #engine = engine_from_config('sqlite://')
    engine = engine_from_config({'sqlalchemy.url': 'sqlite://'})
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
Example #8
0
def init():
    #config_uri = 'development.ini'
    #setup_logging(config_uri)
    #settings = get_appsettings(config_uri)
    #engine = engine_from_config('sqlite://')
    engine = engine_from_config({'sqlalchemy.url': 'sqlite://'})
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
Example #9
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    session_factory = session_factory_from_settings(settings)

    authn_policy = AuthTktAuthenticationPolicy(
        's0secret!!',
        callback=groupfinder,)
    authz_policy = ACLAuthorizationPolicy()

    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    config = Configurator(settings=settings,
                          authentication_policy=authn_policy,
                          authorization_policy=authz_policy,
                          session_factory=session_factory,
                          root_factory=Root)
    # using a custom request with user information
    config.set_request_factory(RequestWithUserAttribute)

    config.include('pyramid_mailer')
    config.add_translation_dirs(
        'colander:locale/',
        'deform:locale/',
        'c3smembership:locale/')
    config.add_static_view('static',
                           'c3smembership:static', cache_max_age=3600)

    config.add_subscriber('c3smembership.subscribers.add_base_template',
                          'pyramid.events.BeforeRender')
    config.add_subscriber('c3smembership.subscribers.add_locale_to_cookie',
                          'pyramid.events.NewRequest')

    # home is /, the membership application form
    config.add_route('join', '/')
    # info pages
    config.add_route('disclaimer', '/disclaimer')
    config.add_route('faq', '/faq')
    config.add_route('statute', '/statute')
    config.add_route('manifesto', '/manifesto')
    # success and further steps
    config.add_route('success', '/success')
    config.add_route('success_check_email', '/check_email')
    config.add_route('verify_email_password', '/verify/{email}/{code}')
    config.add_route('success_pdf', '/C3S_SCE_AFM_{namepart}.pdf')
    # routes & views for staff
    config.add_route('dashboard', '/dashboard/{number}')
    config.add_route('detail', '/detail/{memberid}')
    config.add_route('switch_sig', '/switch_sig/{memberid}')
    config.add_route('switch_pay', '/switch_pay/{memberid}')
    config.add_route('delete_entry', '/delete/{memberid}')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.scan()
    return config.make_wsgi_app()
Example #10
0
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            #print("removed old DBSession ===================================")
        except:
            #print("no DBSession to remove ==================================")
            pass
        #try:
        #    os.remove('test_webtest_functional.db')
        #    #print "deleted old test database"
        #except:
        #    pass
        #    #print "never mind"

        my_settings = {
            #'sqlalchemy.url': 'sqlite:///test_webtest_functional.db',
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.mailaddr': '*****@*****.**'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        self.session = DBSession  # ()

        Base.metadata.create_all(engine)
        # dummy database entries for testing
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            DBSession.add(member1)
            DBSession.flush()

        from c3smembership import main
        app = main({}, **my_settings)

        from webtest import TestApp
        self.testapp = TestApp(app)
Example #11
0
 def setUp(self):
     """
     set up everything for a test case
     """
     self.config = testing.setUp()
     self.config.include('pyramid_mailer.testing')
     try:
         DBSession.remove()
     except:
         pass
     self.session = _initTestingDB()
Example #12
0
 def setUp(self):
     """
     set up everything for a test case
     """
     self.config = testing.setUp()
     self.config.include('pyramid_mailer.testing')
     try:
         DBSession.remove()
     except:
         pass
     self.session = _initTestingDB()
Example #13
0
def _initTestingDB():
    from sqlalchemy import create_engine
    from c3smembership.models import DBSession
    from c3smembership.models import Base
    from c3smembership.models import initialize_sql
    engine = create_engine('sqlite:///:memory:')
    #session = initialize_sql(create_engine('sqlite:///:memory:'))
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    return DBSession
Example #14
0
 def setUp(self):
     self.config = testing.setUp()
     self.config.include('pyramid_mailer.testing')
     try:
         DBSession.remove()
         #print("removing old DBSession ===================================")
     except:
         #print("no DBSession to remove ===================================")
         pass
     engine = create_engine('sqlite:///test_models.db')
     self.session = DBSession
     DBSession.configure(bind=engine)  # XXX does influence self.session!?!
     Base.metadata.create_all(engine)
Example #15
0
    def setUp(self):
        """
        set up everything for a test case
        """
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            #print("removing old DBSession ===================================")
        except:
            #print("no DBSession to remove ===================================")
            pass
        from sqlalchemy import create_engine
        #engine = create_engine('sqlite:///test_utils.db')
        engine = create_engine('sqlite:///:memory:')
        DBSession.configure(bind=engine)
        self.session = DBSession  # ()

        Base.metadata.create_all(engine)
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGBAR',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            DBSession.add(member1)
            DBSession.flush()
def _initTestingDB():
    #from sqlalchemy import create_engine
    #from c3smembership.models import initialize_sql
    #session = initialize_sql(create_engine('sqlite:///memory'))
    #session = DBSession
    my_settings = {
        'sqlalchemy.url': 'sqlite:///:memory:', }
    engine = engine_from_config(my_settings)
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        member1 = C3sMember(  # german
            firstname=u'SomeFirstnäme',
            lastname=u'SomeLastnäme',
            email=u'*****@*****.**',
            address1=u"addr one",
            address2=u"addr two",
            postcode=u"12345",
            city=u"Footown Mäh",
            country=u"Foocountry",
            locale=u"DE",
            date_of_birth=date.today(),
            email_is_confirmed=False,
            email_confirm_code=u'ABCDEFGFOO',
            password=u'arandompassword',
            date_of_submission=date.today(),
            membership_type=u'normal',
            member_of_colsoc=True,
            name_of_colsoc=u"GEMA",
            num_shares=u'23',
        )
        member2 = C3sMember(  # german
            firstname=u'AAASomeFirstnäme',
            lastname=u'XXXSomeLastnäme',
            email=u'*****@*****.**',
            address1=u"addr one",
            address2=u"addr two",
            postcode=u"12345",
            city=u"Footown Mäh",
            country=u"Foocountry",
            locale=u"DE",
            date_of_birth=date.today(),
            email_is_confirmed=False,
            email_confirm_code=u'ABCDEFGBAR',
            password=u'arandompassword',
            date_of_submission=date.today(),
            membership_type=u'normal',
            member_of_colsoc=True,
            name_of_colsoc=u"GEMA",
            num_shares=u'23',
        )
        DBSession.add(member1)
        DBSession.add(member2)

    return DBSession
Example #17
0
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.remove()
        except:
            pass
        #engine = create_engine('sqlite:///test_model_staff.db')
        engine = create_engine('sqlite://')
        self.session = DBSession
        self.session.configure(bind=engine)
        Base.metadata.create_all(engine)

        with transaction.manager:
            group1 = Group(name=u'staff')
            group2 = Group(name=u'staff2')
            DBSession.add(group1, group2)
            DBSession.flush()
Example #18
0
 def tearDown(self):
     DBSession.remove()
     testing.tearDown()
Example #19
0
def join_c3s(request):
    """
    This is the main form view: Join C3S as member
    """
    import datetime
    from colander import Range

    #LOGGING = True

    #if LOGGING:  # pragma: no cover
        #import logging
        #log = logging.getLogger(__name__)
        #log.info("join...")

    # if another language was chosen by clicking on a flag
    # the add_locale_to_cookie subscriber has planted an attr on the request
    if hasattr(request, '_REDIRECT_'):
        #print("request._REDIRECT_: " + str(request._REDIRECT_))

        _query = request._REDIRECT_
        #print("_query: " + _query)
        # set language cookie
        request.response.set_cookie('_LOCALE_', _query)
        request._LOCALE_ = _query
        locale_name = _query
        #print("locale_name (from query_string): " + locale_name)
        #from pyramid.httpexceptions import HTTPFound
        #print("XXXXXXXXXXXXXXX ==> REDIRECTING ")
        return HTTPFound(location=request.route_url('join'),
                         headers=request.response.headers)
    # # if another language was chosen, pick it
    # if request._REDIRECT_ is not '':
    #     print("request.query_string: " + str(request.query_string))
    #     _query = request.query_string
    #     print("_query: " + _query)
    #     # set language cookie
    #     request.response.set_cookie('_LOCALE_', _query)
    #     request._LOCALE_ = _query
    #     locale_name = _query
    #     print("locale_name (from query_string): " + locale_name)
    #     from pyramid.httpexceptions import HTTPFound
    #     print("XXXXXXXXXXXXXXX ==> REDIRECTING ")
    #     return HTTPFound(location=request.route_url('intent'),
    #                      headers=request.response.headers)
    else:
        #locale_name = request._LOCALE_
        locale_name = get_locale_name(request)
        #print("locale_name (from request): " + locale_name)

    # check if user clicked on language symbol to have page translated
    # #print("request.query_string: " + str(request.query_string))
    # if 'l' in request.query_string:
    #     print("request.query_string: " + str(request.query_string))
    #     print("request.query_string[0]: " + str(request.query_string[0]))

    # from pyramid.httpexceptions import HTTPFound
    # if (request.query_string == '_LOCALE_=%s' % (locale_name)) or (
    #     request.query_string == 'l=%s' % (locale_name)):
    #     # set language cookie
    #     request.response.set_cookie('_LOCALE_', locale_name)
    #     return HTTPFound(location=request.route_url('intent'),
    #                      headers=request.response.headers)

    if DEBUG:  # pragma: no cover
        print "-- locale_name: " + str(locale_name)

    country_codes = [
        ('AT', _(u'Austria')),
        ('BE', _(u'Belgium')),
        ('BG', _(u'Bulgaria')),
        ('CH', _(u'Switzerland')),
        ('CZ', _(u'Czech Republic')),
        ('DE', _(u'Germany')),
        ('DK', _(u'Denmark')),
        ('ES', _(u'Spain')),
        ('EE', _(u'Estonia')),
        ('FI', _(u'Finland')),
        ('FR', _(u'France')),
        ('GB', _(u'United Kingdom')),
        ('GR', _(u'Greece')),
        ('HU', _(u'Hungary')),
        ('HR', _(u'Croatia')),
        ('IL', _(u'Israel')),
        ('IE', _(u'Ireland')),
        ('IT', _(u'Italy')),
        ('LT', _(u'Lithuania')),
        ('LV', _(u'Latvia')),
        ('LU', _(u'Luxembourg')),
        ('MT', _(u'Malta')),
        ('NL', _(u'Netherlands')),
        ('PL', _(u'Poland')),
        ('PT', _(u'Portugal')),
        ('SK', _(u'Slovakia')),
        ('SI', _(u'Slovenia')),
        ('SE', _(u'Sweden')),
        ('XX', _(u'other'))
        ]

   # set default of Country select widget according to locale
    LOCALE_COUNTRY_MAPPING = {
        'de': 'DE',
        #'da': 'DK',
        'en': 'GB',
        #'es': 'ES',
        #'fr': 'FR',
    }
    country_default = LOCALE_COUNTRY_MAPPING.get(locale_name)
    if DEBUG:  # pragma: no cover
        print("== locale is :" + str(locale_name))
        print("== choosing :" + str(country_default))

    class MembershipForm(colander.MappingSchema):
        """
        colander schema for membership application form
        """
        firstname = colander.SchemaNode(
            colander.String(),
            title=_(u"(Real) First Name"),
            oid="firstname",
        )
        lastname = colander.SchemaNode(
            colander.String(),
            title=_(u"(Real) Last Name"),
            oid="lastname",
        )
        email = colander.SchemaNode(
            colander.String(),
            title=_(u'Email'),
            validator=colander.Email(),
            oid="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'),
            oid="postcode"
        )
        city = colander.SchemaNode(
            colander.String(),
            title=_(u'City'),
            oid="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),
            oid="country",
        )

        # 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(''),
        #     oid="activity",)

        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

        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),
            oid="other_colsoc",
            #validator=colsoc_validator
        )
        name_of_colsoc = colander.SchemaNode(
            colander.String(),
            title=_(u'If so, which one?'),
            missing=unicode(''),
            oid="colsoc_name",
            validator=colander.All(
                colsoc_validator,
            )
        )
        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),
            oid="investing_member",
        )
        num_shares = colander.SchemaNode(
            colander.Integer(),
            title=_(u"Number of Shares (50€ each"),
            default=1,
            validator=colander.Range(
                min=1,
                max=60,
                min_err=_(u"You need at least one share of 50 Euro."),
                max_err=_(u"You may choose 60 shares at most. (3000 Euro)"),
            ),
            oid="num_shares")
       # 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}')
            ),
            oid="date_of_birth",
        )

        # opt_band = colander.SchemaNode(
        #     colander.String(),
        #     title=_(u'optional: Band/Artist name'),
        #     missing=u'',
        #     oid="bandname",
        #     )

        # opt_URL = colander.SchemaNode(
        #     colander.String(),
        #     title=_(u'optional: Homepage'),
        #     missing=u'',
        #     oid="bandurl",
        #     )

        #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_no),
#                 #    (u'yes', _(u'Yes')),
#                 #    )
#                 ),
#        )
        _LOCALE_ = colander.SchemaNode(colander.String(),
                                       widget=deform.widget.HiddenWidget(),
                                       default=locale_name)

    schema = MembershipForm()

    form = deform.Form(
        schema,
        buttons=[
            deform.Button('submit', _(u'Submit')),
            deform.Button('reset', _(u'Reset'))
        ],
        use_ajax=True,
        renderer=zpt_renderer
    )

    # if the form has been used and SUBMITTED, check contents
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
            if DEBUG:  # pragma: no cover
                print("the appstruct from the form: %s \n") % appstruct
                for thing in appstruct:
                    print("the thing: %s") % thing
                    print("type: %s") % type(thing)
        except ValidationFailure, e:
            #print("the appstruct from the form: %s \n") % appstruct
            #for thing in appstruct:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)
            print(e)
            #message.append(
            request.session.flash(
                _(u"Please note: There were errors, "
                  "please check the form below."),
                'message_above_form',
                allow_duplicate=False)
            return{'form': e.render()}

        def make_random_string():
            """
            used as email confirmation code
            """
            import random
            import string
            return ''.join(
                random.choice(
                    string.ascii_uppercase + string.digits
                ) for x in range(10))

        # make confirmation code and
        randomstring = make_random_string()
        # check if confirmation code is already used
        while (C3sMember.check_for_existing_confirm_code(randomstring)):
            # create a new one, if the new one already exists in the database
            randomstring = make_random_string()  # pragma: no cover

        from datetime import datetime
        from sqlalchemy.exc import (
            InvalidRequestError,
            IntegrityError
        )
        # to store the data in the DB, an objet is created
        member = C3sMember(
            firstname=appstruct['firstname'],
            lastname=appstruct['lastname'],
            email=appstruct['email'],
            address1=appstruct['address1'],
            address2=appstruct['address2'],
            postcode=appstruct['postcode'],
            city=appstruct['city'],
            country=appstruct['country'],
            locale=appstruct['_LOCALE_'],
            date_of_birth=appstruct['date_of_birth'],
            email_is_confirmed=False,
            email_confirm_code=randomstring,
            #is_composer=('composer' in appstruct['activity']),
            #is_lyricist=('lyricist' in appstruct['activity']),
            #is_producer=('music producer' in appstruct['activity']),
            #is_remixer=('remixer' in appstruct['activity']),
            #is_dj=('dj' in appstruct['activity']),
            date_of_submission=datetime.now(),
            invest_member=(appstruct['invest_member'] == u'yes'),
            member_of_colsoc=(appstruct['member_of_colsoc'] == u'yes'),
            name_of_colsoc=appstruct['name_of_colsoc'],
            #opt_band=appstruct['opt_band'],
            #opt_URL=appstruct['opt_URL'],
            num_shares=appstruct['num_shares'],
        )
        dbsession = DBSession()
        try:
            dbsession.add(member)
            appstruct['email_confirm_code'] = randomstring
        except InvalidRequestError, e:  # pragma: no cover
            print("InvalidRequestError! %s") % e
Example #20
0
 def setUp(self):
     self.config = testing.setUp()
     # import pdb; pdb.set_trace()
     # shutil.move('c3sMembership.db', 'c3sMembership.db.old')
     DBSession.remove()
     self.session = _initTestingDB()
Example #21
0
 def setUp(self):
     self.config = testing.setUp()
     self.config.include('pyramid_mailer.testing')
     DBSession.remove()
     self.session = _initTestingDB()
Example #22
0
def new_member(request):
    '''
    let staff create a new member entry, when receiving input via dead wood
    '''

    # XXX check if submitted, etc...

    class PersonalData(colander.MappingSchema):
        """
        colander schema for membership application form
        """
        #id = colander.SchemaNode(
        #    colander.Integer(),
        #    title='Database ID (optional, used to re-add deleted member',
        #)
        firstname = colander.SchemaNode(
            colander.String(),
            title='Vorname',
            oid="firstname",
        )
        lastname = colander.SchemaNode(
            colander.String(),
            title='Nachnahme',
            oid="lastname",
        )
        email = colander.SchemaNode(
            colander.String(),
            title=_(u'Email'),
            validator=colander.Email(),
            oid="email",
        )
        passwort = colander.SchemaNode(
            colander.String(),
            widget=deform.widget.HiddenWidget(),
            default='NoneSet',
            missing='NoneSetPurposefully'
        )
        address1 = colander.SchemaNode(
            colander.String(),
            title='Addresse Zeile 1'
        )
        address2 = colander.SchemaNode(
            colander.String(),
            missing=unicode(''),
            title='Addresse Zeile 2'
        )
        postcode = colander.SchemaNode(
            colander.String(),
            title='Postleitzahl',
            oid="postcode"
        )
        city = colander.SchemaNode(
            colander.String(),
            title='Ort',
            oid="city",
        )
        country = colander.SchemaNode(
            colander.String(),
            title='Land',
            default=country_default,
            widget=deform.widget.SelectWidget(
                values=country_codes),
            oid="country",
        )
        date_of_birth = colander.SchemaNode(
            colander.Date(),
            title='Geburtsdatum',
            #widget=deform.widget.DatePartsWidget(
            #    inline=True),
            default=date(2013, 1, 1),
            validator=Range(
                min=date(1913, 1, 1),
                max=date(2000, 1, 1),
                min_err=_(u'${val} is earlier than earliest date ${min}'),
                max_err=_(u'${val} is later than latest date ${max}')
            ),
            oid="date_of_birth",
        )
        _LOCALE_ = colander.SchemaNode(
            colander.String(),
            widget=deform.widget.HiddenWidget(),
            default='de',
            missing='de',
        )

    class MembershipInfo(colander.Schema):

        yes_no = ((u'yes', _(u'Yes')),
                  (u'no', _(u'No')))

        membership_type = colander.SchemaNode(
            colander.String(),
            title=(u'Art der Mitgliedschaft (lt. Satzung, §4)'),
            description=u'Bitte die Art der Mitgliedschaft auswählen.',
            widget=deform.widget.RadioChoiceWidget(
                values=(
                    (u'normal',
                     (u'Normales Mitglied')),
                    (u'investing',
                     u'Investierendes Mitglied'),
                ),
            )
        )
        member_of_colsoc = colander.SchemaNode(
            colander.String(),
            title='Mitglied einer Verwertungsgesellschaft?',
            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'Falls ja, welche? (Kommasepariert)'),
            missing=unicode(''),
            oid="colsoc_name",
            #validator=colander.All(
            #    colsoc_validator,
            #)
        )

    class Shares(colander.Schema):
        """
        the number of shares a member wants to hold

        this involves a slider widget: added to deforms widgets.
        see README.Slider.rst
        """
        num_shares = colander.SchemaNode(
            colander.Integer(),
            title='Anzahl Anteile (1-60)',
            default="1",
            #widget=deform.widget.TextInputSliderWidget(
            #    size=3, css_class='num_shares_input'),
            validator=colander.Range(
                min=1,
                max=60,
                min_err=u'mindestens 1',
                max_err=u'höchstens 60',
            ),
            oid="num_shares")

    class MembershipForm(colander.Schema):
        """
        The Form consists of
        - Personal Data
        - Membership Information
        - Shares
        """
        person = PersonalData(
            title=_(u"Personal Data"),
            #description=_(u"this is a test"),
            #css_class="thisisjustatest"
        )
        membership_info = MembershipInfo(
            title=_(u"Membership Requirements")
        )
        shares = Shares(
            title=_(u"Shares")
        )

    schema = MembershipForm()

    form = deform.Form(
        schema,
        buttons=[
            deform.Button('submit', _(u'Submit')),
            deform.Button('reset', _(u'Reset'))
        ],
        use_ajax=True,
        #renderer=zpt_renderer
    )

    # if the form has NOT been used and submitted, remove error messages if any
    if not 'submit' in request.POST:
        request.session.pop_flash()
        #print('ping!')

    # if the form has been used and SUBMITTED, check contents
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
            #print("the appstruct from the form: %s \n") % appstruct
            #for thing in appstruct:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)

            # data sanity: if not in collecting society, don't save
            #  collsoc name even if it was supplied through form
            #if 'no' in appstruct['membership_info']['member_of_colsoc']:
            #    appstruct['membership_info']['name_of_colsoc'] = ''
            #    print appstruct['membership_info']['name_of_colsoc']
            #print '-'*80

        except ValidationFailure as e:
            #print("Validation Failure!")
            #print("the request.POST: %s \n" % request.POST)
            #for thing in request.POST:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)
            #print(e.args)
            #print(e.error)
            #print(e.message)
            request.session.flash(
                _(u"Please note: There were errors, "
                  "please check the form below."),
                'message_above_form',
                allow_duplicate=False)
            return{'form': e.render()}

        def make_random_string():
            """
            used as email confirmation code
            """
            import random
            import string
            return u''.join(
                random.choice(
                    string.ascii_uppercase + string.digits
                ) for x in range(10))

        # make confirmation code and
        randomstring = make_random_string()
        # check if confirmation code is already used
        while (C3sMember.check_for_existing_confirm_code(randomstring)):
            # create a new one, if the new one already exists in the database
            randomstring = make_random_string()  # pragma: no cover

        # to store the data in the DB, an objet is created
        member = C3sMember(
            firstname=appstruct['person']['firstname'],
            lastname=appstruct['person']['lastname'],
            email=appstruct['person']['email'],
            password='******',
            address1=appstruct['person']['address1'],
            address2=appstruct['person']['address2'],
            postcode=appstruct['person']['postcode'],
            city=appstruct['person']['city'],
            country=appstruct['person']['country'],
            locale=appstruct['person']['_LOCALE_'],
            date_of_birth=appstruct['person']['date_of_birth'],
            email_is_confirmed=False,
            email_confirm_code=randomstring,
            #is_composer=('composer' in appstruct['activity']),
            #is_lyricist=('lyricist' in appstruct['activity']),
            #is_producer=('music producer' in appstruct['activity']),
            #is_remixer=('remixer' in appstruct['activity']),
            #is_dj=('dj' in appstruct['activity']),
            date_of_submission=datetime.now(),
            #invest_member=(
            #    appstruct['membership_info']['invest_member'] == u'yes'),
            membership_type=appstruct['membership_info']['membership_type'],
            member_of_colsoc=(
                appstruct['membership_info']['member_of_colsoc'] == u'yes'),
            name_of_colsoc=appstruct['membership_info']['name_of_colsoc'],
            #opt_band=appstruct['opt_band'],
            #opt_URL=appstruct['opt_URL'],
            num_shares=appstruct['shares']['num_shares'],
        )
        dbsession = DBSession()

        try:
            _temp = request.url.split('?')[1].split('=')
            if 'id' in _temp[0]:
                _id = _temp[1]
                #print("the id we want to recreate: %s" % _id)

            # add a member with a DB id that had seen its entry deleted before
                _mem = C3sMember.get_by_id(_id)  # load from id
                if isinstance(_mem, NoneType):  # check deletion status
                    member.id = _id  # set id as specified
        except:
            #print "no splitable url params found, creating new entry"
            pass

        # add member at next free DB id (default if member.id not set)
        try:
            dbsession.add(member)
            dbsession.flush()
            #print(member.id)
            the_new_id = member.id
            #appstruct['email_confirm_code'] = randomstring  # ???
        except InvalidRequestError, e:  # pragma: no cover
            print("InvalidRequestError! %s") % e
        except IntegrityError, ie:  # pragma: no cover
            print("IntegrityError! %s") % ie
Example #23
0
 def tearDown(self):
     DBSession.close()
     DBSession.remove()
     #os.remove('test_import.db')
     testing.tearDown()
Example #24
0
 def setUp(self):
     self.config = testing.setUp()
     #import pdb; pdb.set_trace()
     #shutil.move('c3sMembership.db', 'c3sMembership.db.old')
     DBSession.remove()
     self.session = _initTestingDB()
Example #25
0
def join_c3s(request):
    """
    This is the main form view: Join C3S as member
    """
    import datetime
    from colander import Range

    #LOGGING = True

    #if LOGGING:  # pragma: no cover
    #import logging
    #log = logging.getLogger(__name__)
    #log.info("join...")

    # if another language was chosen by clicking on a flag
    # the add_locale_to_cookie subscriber has planted an attr on the request
    if hasattr(request, '_REDIRECT_'):
        #print("request._REDIRECT_: " + str(request._REDIRECT_))

        _query = request._REDIRECT_
        #print("_query: " + _query)
        # set language cookie
        request.response.set_cookie('_LOCALE_', _query)
        request._LOCALE_ = _query
        locale_name = _query
        #print("locale_name (from query_string): " + locale_name)
        #from pyramid.httpexceptions import HTTPFound
        #print("XXXXXXXXXXXXXXX ==> REDIRECTING ")
        return HTTPFound(location=request.route_url('join'),
                         headers=request.response.headers)
    # # if another language was chosen, pick it
    # if request._REDIRECT_ is not '':
    #     print("request.query_string: " + str(request.query_string))
    #     _query = request.query_string
    #     print("_query: " + _query)
    #     # set language cookie
    #     request.response.set_cookie('_LOCALE_', _query)
    #     request._LOCALE_ = _query
    #     locale_name = _query
    #     print("locale_name (from query_string): " + locale_name)
    #     from pyramid.httpexceptions import HTTPFound
    #     print("XXXXXXXXXXXXXXX ==> REDIRECTING ")
    #     return HTTPFound(location=request.route_url('intent'),
    #                      headers=request.response.headers)
    else:
        #locale_name = request._LOCALE_
        locale_name = get_locale_name(request)
        #print("locale_name (from request): " + locale_name)

    # check if user clicked on language symbol to have page translated
    # #print("request.query_string: " + str(request.query_string))
    # if 'l' in request.query_string:
    #     print("request.query_string: " + str(request.query_string))
    #     print("request.query_string[0]: " + str(request.query_string[0]))

    # from pyramid.httpexceptions import HTTPFound
    # if (request.query_string == '_LOCALE_=%s' % (locale_name)) or (
    #     request.query_string == 'l=%s' % (locale_name)):
    #     # set language cookie
    #     request.response.set_cookie('_LOCALE_', locale_name)
    #     return HTTPFound(location=request.route_url('intent'),
    #                      headers=request.response.headers)

    if DEBUG:  # pragma: no cover
        print "-- locale_name: " + str(locale_name)

    country_codes = [('AT', _(u'Austria')), ('BE', _(u'Belgium')),
                     ('BG', _(u'Bulgaria')), ('CH', _(u'Switzerland')),
                     ('CZ', _(u'Czech Republic')), ('DE', _(u'Germany')),
                     ('DK', _(u'Denmark')), ('ES', _(u'Spain')),
                     ('EE', _(u'Estonia')), ('FI', _(u'Finland')),
                     ('FR', _(u'France')), ('GB', _(u'United Kingdom')),
                     ('GR', _(u'Greece')), ('HU', _(u'Hungary')),
                     ('HR', _(u'Croatia')), ('IL', _(u'Israel')),
                     ('IE', _(u'Ireland')), ('IT', _(u'Italy')),
                     ('LT', _(u'Lithuania')), ('LV', _(u'Latvia')),
                     ('LU', _(u'Luxembourg')), ('MT', _(u'Malta')),
                     ('NL', _(u'Netherlands')), ('PL', _(u'Poland')),
                     ('PT', _(u'Portugal')), ('SK', _(u'Slovakia')),
                     ('SI', _(u'Slovenia')), ('SE', _(u'Sweden')),
                     ('XX', _(u'other'))]

    # set default of Country select widget according to locale
    LOCALE_COUNTRY_MAPPING = {
        'de': 'DE',
        #'da': 'DK',
        'en': 'GB',
        #'es': 'ES',
        #'fr': 'FR',
    }
    country_default = LOCALE_COUNTRY_MAPPING.get(locale_name)
    if DEBUG:  # pragma: no cover
        print("== locale is :" + str(locale_name))
        print("== choosing :" + str(country_default))

    class PersonalData(colander.MappingSchema):
        """
        colander schema for membership application form
        """
        firstname = colander.SchemaNode(
            colander.String(),
            title=_(u"(Real) First Name"),
            oid="firstname",
        )
        lastname = colander.SchemaNode(
            colander.String(),
            title=_(u"(Real) Last Name"),
            oid="lastname",
        )
        email = colander.SchemaNode(
            colander.String(),
            title=_(u'Email'),
            validator=colander.Email(),
            oid="email",
        )
        password = colander.SchemaNode(
            colander.String(),
            validator=colander.Length(min=5, max=100),
            widget=deform.widget.PasswordWidget(size=20),
            title=_(u"Password"),
            description=_("We need a password to protect your data. After "
                          "verifying your email you will have to enter it."),
            oid="password",
        )

        address1 = colander.SchemaNode(colander.String(),
                                       title=_(u'Address Line 1'))
        address2 = colander.SchemaNode(colander.String(),
                                       missing=unicode(''),
                                       title=_(u"Address Line 2"))
        postcode = colander.SchemaNode(colander.String(),
                                       title=_(u'Post Code'),
                                       oid="postcode")
        city = colander.SchemaNode(
            colander.String(),
            title=_(u'City'),
            oid="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),
            oid="country",
        )

        # 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.DatePartsWidget(),
            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}')),
            oid="date_of_birth",
        )

        # 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(''),
        #     oid="activity",)
        _LOCALE_ = colander.SchemaNode(colander.String(),
                                       widget=deform.widget.HiddenWidget(),
                                       default=locale_name)

    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 Shares(colander.Schema):
        """
        the number of shares a member wants to hold

        this involves a slider widget: added to deforms widgets.
        see README.slider.rst
        """
        num_shares = colander.SchemaNode(
            colander.Integer(),
            title=_(u"I want to buy the following number "
                    u"of Shares (50€ each, up to 3000€)"),
            description=_(
                u'You can choose any amount of shares between 1 and 60.'),
            default="1",
            widget=deform.widget.TextInputSliderWidget(
                size=3, css_class='num_shares_input'),
            validator=colander.Range(
                min=1,
                max=60,
                min_err=_(u"You need at least one share of 50 Euro."),
                max_err=_(u"You may choose 60 shares at most. (3000 Euro)"),
            ),
            oid="num_shares")

    class MembershipForm(colander.Schema):
        """
        The Form consists of
        - Personal Data
        - Membership Information
        - Shares
        """
        person = PersonalData(
            title=_(u"Personal Data"),
            #description=_(u"this is a test"),
            #css_class="thisisjustatest"
        )
        membership_info = MembershipInfo(title=_(u"Membership Requirements"))
        shares = Shares(title=_(u"Shares"))

    schema = MembershipForm()

    form = deform.Form(schema,
                       buttons=[
                           deform.Button('submit', _(u'Submit')),
                           deform.Button('reset', _(u'Reset'))
                       ],
                       use_ajax=True,
                       renderer=zpt_renderer)

    # if the form has NOT been used and submitted, remove error messages if any
    if not 'submit' in request.POST:
        request.session.pop_flash()

    # if the form has been used and SUBMITTED, check contents
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
            #print("the appstruct from the form: %s \n") % appstruct
            #for thing in appstruct:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)

            # data sanity: if not in collecting society, don't save
            #  collsoc name even if it was supplied through form
            if 'no' in appstruct['membership_info']['member_of_colsoc']:
                appstruct['membership_info']['name_of_colsoc'] = ''
                print appstruct['membership_info']['name_of_colsoc']
                #print '-'*80

        except ValidationFailure, e:
            #print("the appstruct from the form: %s \n") % appstruct
            #for thing in appstruct:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)
            print(e)
            #message.append(
            request.session.flash(_(u"Please note: There were errors, "
                                    "please check the form below."),
                                  'message_above_form',
                                  allow_duplicate=False)
            return {'form': e.render()}

        def make_random_string():
            """
            used as email confirmation code
            """
            import random
            import string
            return ''.join(
                random.choice(string.ascii_uppercase + string.digits)
                for x in range(10))

        # make confirmation code and
        randomstring = make_random_string()
        # check if confirmation code is already used
        while (C3sMember.check_for_existing_confirm_code(randomstring)):
            # create a new one, if the new one already exists in the database
            randomstring = make_random_string()  # pragma: no cover

        from datetime import datetime
        from sqlalchemy.exc import (InvalidRequestError, IntegrityError)
        # to store the data in the DB, an objet is created
        member = C3sMember(
            firstname=appstruct['person']['firstname'],
            lastname=appstruct['person']['lastname'],
            email=appstruct['person']['email'],
            password=appstruct['person']['password'],
            address1=appstruct['person']['address1'],
            address2=appstruct['person']['address2'],
            postcode=appstruct['person']['postcode'],
            city=appstruct['person']['city'],
            country=appstruct['person']['country'],
            locale=appstruct['person']['_LOCALE_'],
            date_of_birth=appstruct['person']['date_of_birth'],
            email_is_confirmed=False,
            email_confirm_code=randomstring,
            #is_composer=('composer' in appstruct['activity']),
            #is_lyricist=('lyricist' in appstruct['activity']),
            #is_producer=('music producer' in appstruct['activity']),
            #is_remixer=('remixer' in appstruct['activity']),
            #is_dj=('dj' in appstruct['activity']),
            date_of_submission=datetime.now(),
            #invest_member=(
            #    appstruct['membership_info']['invest_member'] == u'yes'),
            membership_type=appstruct['membership_info']['membership_type'],
            member_of_colsoc=(
                appstruct['membership_info']['member_of_colsoc'] == u'yes'),
            name_of_colsoc=appstruct['membership_info']['name_of_colsoc'],
            #opt_band=appstruct['opt_band'],
            #opt_URL=appstruct['opt_URL'],
            num_shares=appstruct['shares']['num_shares'],
        )
        dbsession = DBSession()
        try:
            dbsession.add(member)
            appstruct['email_confirm_code'] = randomstring
        except InvalidRequestError, e:  # pragma: no cover
            print("InvalidRequestError! %s") % e
Example #26
0
def staff_view(request):
    """
    This view lets admins edit staff/cashier personnel:
    who may act as cashier etc.?
    """
    _staffers = C3sStaff.get_all()

    class Staffer(colander.MappingSchema):
        login = colander.SchemaNode(
            colander.String(),
            title='login',
        )
        password = colander.SchemaNode(
            colander.String(),
            title='passwort',
        )

    schema = Staffer()

    stafferform = deform.Form(
        schema,
        buttons=[
            deform.Button('new_staffer', 'save')
        ]
    )

    if 'action' in request.POST:
        #print(request.POST['id'])
        try:
            _staffer = C3sStaff.get_by_id(int(request.POST['id']))
        except:
        #    print("exception!")
            return HTTPFound(location=request.route_url('staff'))
        #print(request.POST['action'])
        if request.POST['action'] == u'delete':
            #print("will delete staff id %s" % _staffer.id)
            C3sStaff.delete_by_id(_staffer.id)
            #print("deleted staff id %s" % _staffer.id)
            # send mail
            encrypted = encrypt_with_gnupg('''hi,
%s was deleted from the backend by %s.

best,
your membership tool''' % (_staffer.login,
                           request.authenticated_userid))
            message = Message(
                subject='[C3S Yes] staff was deleted.',
                sender='*****@*****.**',
                recipients=[
                    request.registry.settings['c3smembership.mailaddr']],
                body=encrypted
            )
            mailer = get_mailer(request)
            mailer.send(message)
            return HTTPFound(location=request.route_url('staff'))
        elif request.POST['action'] == 'edit':
            appstruct = {
                'login': _staffer.login,
                'password': '******',
            }
            stafferform.set_appstruct(appstruct)

    if 'new_staffer' in request.POST:
        #print "new staffer!"
        controls = request.POST.items()
        try:
            appstruct = stafferform.validate(controls)
            #print('validated!')
        except ValidationFailure, e:
            return {
                'stafferform': e.render()
            }
        # XXX login must be unique!
        existing = C3sStaff.get_by_login(appstruct['login'])
        if existing is not None:
            #print "that staffer exists!"
            if u'_UNCHANGED_' in appstruct['password']:
                pass
            else:
                existing.password = appstruct['password']
                existing.last_password_change = datetime.now()
            encrypted = encrypt_with_gnupg('''hi,
the password of %s was changed by %s.

best,
your membership tool''' % (existing.login,
                           request.authenticated_userid))
            message = Message(
                subject='[C3S Yes] staff password changed.',
                sender='*****@*****.**',
                recipients=[
                    request.registry.settings['c3smembership.mailaddr']],
                body=encrypted
            )

        else:  # create new entry
            staffer = C3sStaff(
                login=appstruct['login'],
                password=appstruct['password'],
                email=u'',
            )
            staffer.groups = [Group.get_staffers_group()]
            #print "about to add user"
            DBSession.add(staffer)
            DBSession.flush()
            print "added staffer"
            # send mail
            encrypted = encrypt_with_gnupg('''hi,
%s was added to the backend by %s.

best,
your membership tool''' % (staffer.login,
                           request.authenticated_userid))
            message = Message(
                subject='[C3S Yes] staff was added.',
                sender='*****@*****.**',
                recipients=[
                    request.registry.settings['c3smembership.mailaddr']],
                body=encrypted
            )
            mailer = get_mailer(request)
            mailer.send(message)

        return HTTPFound(
            request.route_url('staff')
        )
Example #27
0
 def tearDown(self):
     DBSession.remove()
     # shutil.rm('c3sMembership.db')
     testing.tearDown()
Example #28
0
 def tearDown(self):
     """
     clean up after a test case
     """
     DBSession.remove()
     testing.tearDown()
Example #29
0
def main(argv=sys.argv):
    """
    initialize the database
    """
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    # add some content
    with transaction.manager:
        # a group for accountants/staff
        accountants_group = Group(name=u"staff")
        try:
            DBSession.add(accountants_group)
            DBSession.flush()
            print("adding group staff")
        except:
            print("could not add group staff.")
            # pass
    with transaction.manager:
        # staff personnel
        staffer1 = C3sStaff(
            login=u"rut",
            password=u"berries",
            email=u"*****@*****.**",
        )
        staffer1.groups = [accountants_group]
        try:
            DBSession.add(staffer1)
            print("adding staff rut")
            DBSession.flush()
        except:
            print("it borked! (rut)")
            # pass
    # one more staffer
    with transaction.manager:
        staffer2 = C3sStaff(
            login=u"reel",
            password=u"boo",
            email=u"*****@*****.**",
        )
        staffer2.groups = [accountants_group]
        try:
            DBSession.add(staffer2)
            print("adding staff reel")
            DBSession.flush()
        except:
            print("it borked! (reel)")
            # pass
    # a member, actually a membership form submission
    with transaction.manager:
        member1 = C3sMember(
            firstname=u"Firstnäme",  # includes umlaut
            lastname=u"Lastname",
            email=u"*****@*****.**",
            password=u"berries",
            address1=u"address one",
            address2=u"address two",
            postcode=u"12345 foo",
            city=u"Footown Mäh",
            country=u"Foocountry",
            locale=u"DE",
            date_of_birth=date.today(),
            email_is_confirmed=False,
            email_confirm_code=u"ABCDEFGHIJ",
            num_shares=u'10',
            date_of_submission=datetime.now(),
            membership_type=u'normal',
            member_of_colsoc=True,
            name_of_colsoc=u"GEMA",
        )
        try:
            DBSession.add(member1)
            print("adding Firstnäme")
        except:
            pass
    # even more members
    import random
    import string
    print("about to add %s members..." % how_many)

    with transaction.manager:
        for i in range(how_many):  # create 50 members with semi-random dates
            #print i
            member = C3sMember(
                firstname=u"Firstnäme%s" % i,  # includes umlaut
                lastname=u"Lastname",
                email=u"*****@*****.**",
                password=u"berries",
                address1=u"address one",
                address2=u"address two",
                postcode=u"12345 foo",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u''.join(
                    random.choice(string.ascii_uppercase + string.digits)
                    for x in range(8)),
                num_shares=random.randint(1, 60),
                date_of_submission=datetime.now(),
                membership_type=random.choice((u'normal', u'investing')),
                member_of_colsoc=random.choice((True, False)),
                name_of_colsoc=u"GEMA",
            )
            try:
                DBSession.add(member)
            except IntegrityError:
                print("exception!!!!!!!!!!!!!!!!!!!!1")
    def test_edit_members(self):
        '''
        tests for the edit_member view
        '''
        # unauthorized access must be prevented
        res = self.testapp.reset()  # delete cookie
        res = self.testapp.get('/edit/1', status=403)
        assert('Access was denied to this resource' in res.body)
        res = self.testapp.get('/login', status=200)
        self.failUnless('login' in res.body)
        # try valid user
        form = res.form
        form['login'] = '******'
        form['password'] = '******'
        res2 = form.submit('submit', status=302)
        # # being logged in ...
        res3 = res2.follow()  # being redirected to dashboard_only
        #print('>'*20)
        #print(res3.body)
        #print('<'*20)
        res4 = res3.follow()  # being redirected to dashboard with parameters
        self.failUnless(
            'Dashboard' in res4.body)
        # # now that we are logged in,
        # # the login view should redirect us to the dashboard
        # res5 = self.testapp.get('/login', status=302)
        # # so yes: that was a redirect
        # res6 = res5.follow()
        # res6 = res6.follow()
        # #print(res4.body)
        # self.failUnless(
        #     'Dashboard' in res6.body)
        # # choose number of applications shown
        # res6a = self.testapp.get(
        #     '/dashboard',
        #     status=302,
        #     extra_environ={
        #         'num_display': '30',
        #     }
        # )
        # res6a = res6a.follow()

        # no member in DB, so redirecting to dashboard
        res = self.testapp.get('/edit/1', status=302)
        res2 = res.follow()

        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
        DBSession.add(member1)

        # now there is a member in the DB
        #
        # letzt try invalid input
        res = self.testapp.get('/edit/foo', status=302)
        res2 = res.follow()
        res3 = res2.follow()
        self.failUnless('Dashboard' in res4.body)

        #print '+' * 20
        #print res2.body
        #print '+' * 20
        # now try valid id
        res = self.testapp.get('/edit/1', status=200)
        #print(res.body)
        self.failUnless('Mitglied bearbeiten' in res.body)

        # now we change details, really editing that member
        form = res.form
        #import pdb
        #pdb.set_trace()
        self.assertTrue(u'SomeFirstn\xe4me' in form['firstname'].value)

        form['firstname'] = 'EinVorname'
        form['lastname'] = 'EinNachname'
        form['email'] = '*****@*****.**'
        form['address1'] = 'adressteil 1'
        form['address2'] = 'adressteil 2'
        form['postcode'] = '12346'
        form['city'] = 'die city'
        form['country'] = 'FI'
        #print("der wert von 'deformField14': %s" % form['deformField14'].value)
        form['deformField14'] = 'investing'
        #print("der wert von 'deformField14': %s" % form['deformField14'].value)
        #print("der wert von 'other_colsoc': %s" % form['other_colsoc'].value)
        #print("der wert von 'name_of_colsoc': %s" % form['name_of_colsoc'].value)
        form['other_colsoc'] = 'no'
        form['name_of_colsoc'] = ''
        form['num_shares'] = 42

        # try to submit now. this must fail, because the date of birth is wrong
        res2 = form.submit('submit', status=200)
        #print res2.body
        self.assertTrue('is later than latest date 2000-01-01' in res2.body)
        # set the date correctly
        form2 = res2.form
        form2['date_of_birth'] = '1999-09-19'

        # submit again
        res2 = form2.submit('submit', status=302)
        res3 = res2.follow()
        self.assertTrue('EinVorname' in res3.body)

        #print("der wert von 'deformField14': %s" % form['deformField14'].value)
        #print("der wert von 'date_of_birth': %s" % form['date_of_birth'].value)

        # more asserts
        self.assertTrue('EinNachname' in res3.body)
        self.assertTrue('*****@*****.**' in res3.body)
        self.assertTrue('adressteil 1' in res3.body)
        self.assertTrue('adressteil 2' in res3.body)
        self.assertTrue('12346' in res3.body)
        self.assertTrue('die city' in res3.body)
        self.assertTrue('FI' in res3.body)
        self.assertTrue('investing' in res3.body)
        self.assertTrue('42' in res3.body)
Example #31
0
 def setUp(self):
     self.config = testing.setUp()
     self.config.include('pyramid_mailer.testing')
     DBSession.remove()
     self.session = _initTestingDB()
Example #32
0
 def tearDown(self):
     DBSession.remove()
     #shutil.rm('c3sMembership.db')
     testing.tearDown()
Example #33
0
 def tearDown(self):
     DBSession.remove()
     testing.tearDown()
Example #34
0
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            #print "closed and removed DBSession"
        except:
            pass
            #print "no session to close"
        try:
            os.remove('test_webtest_accountants.db')
            #print "deleted old test database"
        except:
            pass
            #print "never mind"
       # self.session = DBSession()
        my_settings = {
            'sqlalchemy.url': 'sqlite:///test_webtest_accountants.db',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)

        self._insert_members()

        with transaction.manager:
                # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            try:
                DBSession.add(accountants_group)
                DBSession.flush()
                print("adding group staff")
            except:
                print("could not add group staff.")
                # pass
            # staff personnel
            staffer1 = C3sStaff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            try:
                DBSession.add(accountants_group)
                DBSession.add(staffer1)
                DBSession.flush()
            except:
                print("it borked! (rut)")
                # pass

        from c3smembership import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)
Example #35
0
def main(argv=sys.argv):
    """
    initialize the database
    """
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    # add some content
    with transaction.manager:
        # a group for accountants/staff
        accountants_group = Group(name=u"staff")
        try:
            DBSession.add(accountants_group)
            DBSession.flush()
            #print("adding group staff")
        except:
            print("could not add group staff.")
            # pass
    with transaction.manager:
        # staff personnel
        staffer1 = C3sStaff(
            login=u"rut",
            password=u"berries",
            email=u"*****@*****.**",
        )
        staffer1.groups = [accountants_group]
        try:
            DBSession.add(staffer1)
            #print("adding staff rut")
            DBSession.flush()
        except:
            print("it borked! (rut)")
            # pass
    # one more staffer
    with transaction.manager:
        staffer2 = C3sStaff(
            login=u"reel",
            password=u"boo",
            email=u"*****@*****.**",
        )
        staffer2.groups = [accountants_group]
        try:
            DBSession.add(staffer2)
            #print("adding staff reel")
            DBSession.flush()
        except:
            print("it borked! (reel)")
            # pass
    # a member, actually a membership form submission
    with transaction.manager:
        member1 = C3sMember(
            firstname=u"Firstnäme",  # includes umlaut
            lastname=u"Lastname",
            email=u"*****@*****.**",
            password=u"berries",
            address1=u"address one",
            address2=u"address two",
            postcode=u"12345 foo",
            city=u"Footown Mäh",
            country=u"Foocountry",
            locale=u"en",
            date_of_birth=date.today(),
            email_is_confirmed=False,
            email_confirm_code=u"ABCDEFGHIJ",
            num_shares=u'10',
            date_of_submission=datetime.now(),
            membership_type=u'normal',
            member_of_colsoc=True,
            name_of_colsoc=u"GEMA",
        )
        try:
            DBSession.add(member1)
            #print("adding Firstnäme")
        except:
            pass
    # even more members
    import random
    import string
    print("about to add %s members..." % how_many)

    with transaction.manager:
        for i in range(how_many):  # create 50 members with semi-random dates
            #print i
            member = C3sMember(
                firstname=u"Firstnäme%s" % i,  # includes umlaut
                lastname=u"Lastname",
                email=u"*****@*****.**",
                password=u"berries",
                address1=u"address one",
                address2=u"address two",
                postcode=u"12345 foo",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"de",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u''.join(
                    random.choice(
                        string.ascii_uppercase + string.digits
                    ) for x in range(8)),
                num_shares=random.randint(1, 60),
                date_of_submission=datetime.now(),
                membership_type=random.choice((u'normal', u'investing')),
                member_of_colsoc=random.choice((True, False)),
                name_of_colsoc=u"GEMA",
            )
            try:
                DBSession.add(member)
            except IntegrityError:
                print("exception!!!!!!!!!!!!!!!!!!!!1")
Example #36
0
 def tearDown(self):
     DBSession.close()
     DBSession.remove()
     os.remove('test_webtest_accountants.db')
     testing.tearDown()
Example #37
0
    def setUp(self):
        self.config = testing.setUp()
        self.config.include('pyramid_mailer.testing')
        try:
            DBSession.close()
            DBSession.remove()
            #print "closed and removed DBSession"
        except:
            pass
            #print "no session to close"
        #try:
        #    os.remove('test_import.db')
        #    #print "deleted old test database"
        #except:
        #    pass
        #    #print "never mind"
       # self.session = DBSession()
        my_settings = {
            #'sqlalchemy.url': 'sqlite:///test_import.db',
            'sqlalchemy.url': 'sqlite:///:memory:',
            'available_languages': 'da de en es fr',
            'c3smembership.dashboard_number': '30'}
        engine = engine_from_config(my_settings)
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            member1 = C3sMember(  # german
                firstname=u'SomeFirstnäme',
                lastname=u'SomeLastnäme',
                email=u'*****@*****.**',
                address1=u"addr one",
                address2=u"addr two",
                postcode=u"12345",
                city=u"Footown Mäh",
                country=u"Foocountry",
                locale=u"DE",
                date_of_birth=date.today(),
                email_is_confirmed=False,
                email_confirm_code=u'ABCDEFGFOO',
                password=u'arandompassword',
                date_of_submission=date.today(),
                membership_type=u'normal',
                member_of_colsoc=True,
                name_of_colsoc=u"GEMA",
                num_shares=u'23',
            )
            DBSession.add(member1)
            DBSession.flush()
            self.m1_last_pw_change = member1.last_password_change
        with transaction.manager:
                # a group for accountants/staff
            accountants_group = Group(name=u"staff")
            try:
                DBSession.add(accountants_group)
                DBSession.flush()
                #print("adding group staff")
            except:
                #print("could not add group staff.")
                pass
            # staff personnel
            staffer1 = C3sStaff(
                login=u"rut",
                password=u"berries",
                email=u"*****@*****.**",
            )
            staffer1.groups = [accountants_group]
            try:
                DBSession.add(accountants_group)
                DBSession.add(staffer1)
                DBSession.flush()
            except:
                #print("it borked! (rut)")
                pass

        from c3smembership import main
        app = main({}, **my_settings)
        from webtest import TestApp
        self.testapp = TestApp(app)
Example #38
0
def join_c3s(request):
    """
    This is the main form view: Join C3S as member
    """
    import datetime
    from colander import Range

    #LOGGING = True

    #if LOGGING:  # pragma: no cover
        #import logging
        #log = logging.getLogger(__name__)
        #log.info("join...")

    # if another language was chosen by clicking on a flag
    # the add_locale_to_cookie subscriber has planted an attr on the request
    if hasattr(request, '_REDIRECT_'):
        #print("request._REDIRECT_: " + str(request._REDIRECT_))

        _query = request._REDIRECT_
        #print("_query: " + _query)
        # set language cookie
        request.response.set_cookie('_LOCALE_', _query)
        request._LOCALE_ = _query
        locale_name = _query
        #print("locale_name (from query_string): " + locale_name)
        #from pyramid.httpexceptions import HTTPFound
        #print("XXXXXXXXXXXXXXX ==> REDIRECTING ")
        return HTTPFound(location=request.route_url('join'),
                         headers=request.response.headers)
    # # if another language was chosen, pick it
    # if request._REDIRECT_ is not '':
    #     print("request.query_string: " + str(request.query_string))
    #     _query = request.query_string
    #     print("_query: " + _query)
    #     # set language cookie
    #     request.response.set_cookie('_LOCALE_', _query)
    #     request._LOCALE_ = _query
    #     locale_name = _query
    #     print("locale_name (from query_string): " + locale_name)
    #     from pyramid.httpexceptions import HTTPFound
    #     print("XXXXXXXXXXXXXXX ==> REDIRECTING ")
    #     return HTTPFound(location=request.route_url('intent'),
    #                      headers=request.response.headers)
    else:
        #locale_name = request._LOCALE_
        locale_name = get_locale_name(request)
        #print("locale_name (from request): " + locale_name)

    # check if user clicked on language symbol to have page translated
    # #print("request.query_string: " + str(request.query_string))
    # if 'l' in request.query_string:
    #     print("request.query_string: " + str(request.query_string))
    #     print("request.query_string[0]: " + str(request.query_string[0]))

    # from pyramid.httpexceptions import HTTPFound
    # if (request.query_string == '_LOCALE_=%s' % (locale_name)) or (
    #     request.query_string == 'l=%s' % (locale_name)):
    #     # set language cookie
    #     request.response.set_cookie('_LOCALE_', locale_name)
    #     return HTTPFound(location=request.route_url('intent'),
    #                      headers=request.response.headers)

    if DEBUG:  # pragma: no cover
        print "-- locale_name: " + str(locale_name)

    country_codes = [
        ('AT', _(u'Austria')),
        ('BE', _(u'Belgium')),
        ('BG', _(u'Bulgaria')),
        ('CH', _(u'Switzerland')),
        ('CZ', _(u'Czech Republic')),
        ('DE', _(u'Germany')),
        ('DK', _(u'Denmark')),
        ('ES', _(u'Spain')),
        ('EE', _(u'Estonia')),
        ('FI', _(u'Finland')),
        ('FR', _(u'France')),
        ('GB', _(u'United Kingdom')),
        ('GR', _(u'Greece')),
        ('HU', _(u'Hungary')),
        ('HR', _(u'Croatia')),
        ('IE', _(u'Ireland')),
        ('IS', _(u'Iceland')),
        ('IT', _(u'Italy')),
        ('LT', _(u'Lithuania')),
        ('LI', _(u'Liechtenstein')),
        ('LV', _(u'Latvia')),
        ('LU', _(u'Luxembourg')),
        ('MT', _(u'Malta')),
        ('NL', _(u'Netherlands')),
        ('NO', _(u'Norway')),
        ('PL', _(u'Poland')),
        ('PT', _(u'Portugal')),
        ('SK', _(u'Slovakia')),
        ('SI', _(u'Slovenia')),
        ('SE', _(u'Sweden')),
        ('XX', _(u'other'))
    ]
    # set default of Country select widget according to locale
    LOCALE_COUNTRY_MAPPING = {
        'de': 'DE',
        #'da': 'DK',
        'en': 'GB',
        #'es': 'ES',
        #'fr': 'FR',
    }
    country_default = LOCALE_COUNTRY_MAPPING.get(locale_name)
    if DEBUG:  # pragma: no cover
        print("== locale is :" + str(locale_name))
        print("== choosing :" + str(country_default))

    class PersonalData(colander.MappingSchema):
        """
        colander schema for membership application form
        """
        firstname = colander.SchemaNode(
            colander.String(),
            title=_(u"(Real) First Name"),
            oid="firstname",
        )
        lastname = colander.SchemaNode(
            colander.String(),
            title=_(u"(Real) Last Name"),
            oid="lastname",
        )
        email = colander.SchemaNode(
            colander.String(),
            title=_(u'Email'),
            validator=colander.Email(),
            oid="email",
        )
        password = colander.SchemaNode(
            colander.String(),
            validator=colander.Length(min=5, max=100),
            widget=deform.widget.PasswordWidget(size=20),
            title=_(u"Password (to protect access to your data)"),
            description=_("We need a password to protect your data. After "
                          "verifying your email you will have to enter it."),
            oid="password",
        )

        address1 = colander.SchemaNode(
            colander.String(),
            title=_(u'Address Line 1')
        )
        address2 = colander.SchemaNode(
            colander.String(),
            missing=unicode(''),
            title=_(u"Address Line 2")
        )
        postcode = colander.SchemaNode(
            colander.String(),
            title=_(u'Post Code'),
            oid="postcode"
        )
        city = colander.SchemaNode(
            colander.String(),
            title=_(u'City'),
            oid="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),
            oid="country",
        )

       # 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.DatePartsWidget(),
            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}')
            ),
            oid="date_of_birth",
        )

        # 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(''),
        #     oid="activity",)
        _LOCALE_ = colander.SchemaNode(colander.String(),
                                       widget=deform.widget.HiddenWidget(),
                                       default=locale_name)

    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, see C3S SCE statute sec. 4)'),
            description=_(u'choose the type of membership.'),
            widget=deform.widget.RadioChoiceWidget(
                values=(
                    (u'normal',
                     _(u'FULL member. Full 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 or legal entities or private companies 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'An electronic copy of the statute of the '
                u'C3S SCE has been made available to me. (see link below)'),
            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 Shares(colander.Schema):
        """
        the number of shares a member wants to hold

        this involves a slider widget: added to deforms widgets.
        see README.Slider.rst
        """
        num_shares = colander.SchemaNode(
            colander.Integer(),
            title=_(u"I want to buy the following number "
                    u"of Shares (50€ each, up to 3000€, see C3S statute sec. 5)"),
            description=_(
                u'You can choose any amount of shares between 1 and 60.'),
            default="1",
            widget=deform.widget.TextInputSliderWidget(
                size=3, css_class='num_shares_input'),
            validator=colander.Range(
                min=1,
                max=60,
                min_err=_(u"You need at least one share of 50 Euro."),
                max_err=_(u"You may choose 60 shares at most. (3000 Euro)"),
            ),
            oid="num_shares")

    class MembershipForm(colander.Schema):
        """
        The Form consists of
        - Personal Data
        - Membership Information
        - Shares
        """
        person = PersonalData(
            title=_(u"Personal Data"),
            #description=_(u"this is a test"),
            #css_class="thisisjustatest"
        )
        membership_info = MembershipInfo(
            title=_(u"Membership Requirements")
        )
        shares = Shares(
            title=_(u"Shares")
        )

    schema = MembershipForm()

    form = deform.Form(
        schema,
        buttons=[
            deform.Button('submit', _(u'Submit')),
            deform.Button('reset', _(u'Reset'))
        ],
        use_ajax=True,
        renderer=zpt_renderer
    )

    # if the form has NOT been used and submitted, remove error messages if any
    if not 'submit' in request.POST:
        request.session.pop_flash()

    # if the form has been used and SUBMITTED, check contents
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
            #print("the appstruct from the form: %s \n") % appstruct
            #for thing in appstruct:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)

            # data sanity: if not in collecting society, don't save
            #  collsoc name even if it was supplied through form
            if 'no' in appstruct['membership_info']['member_of_colsoc']:
                appstruct['membership_info']['name_of_colsoc'] = ''
                print appstruct['membership_info']['name_of_colsoc']
                #print '-'*80

        except ValidationFailure, e:
            #print("the appstruct from the form: %s \n") % appstruct
            #for thing in appstruct:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)
            print(e)
            #message.append(
            request.session.flash(
                _(u"Please note: There were errors, "
                  "please check the form below."),
                'message_above_form',
                allow_duplicate=False)
            return{'form': e.render()}

        def make_random_string():
            """
            used as email confirmation code
            """
            import random
            import string
            return ''.join(
                random.choice(
                    string.ascii_uppercase + string.digits
                ) for x in range(10))

        # make confirmation code and
        randomstring = make_random_string()
        # check if confirmation code is already used
        while (C3sMember.check_for_existing_confirm_code(randomstring)):
            # create a new one, if the new one already exists in the database
            randomstring = make_random_string()  # pragma: no cover

        from datetime import datetime
        from sqlalchemy.exc import (
            InvalidRequestError,
            IntegrityError
        )
        # to store the data in the DB, an objet is created
        member = C3sMember(
            firstname=appstruct['person']['firstname'],
            lastname=appstruct['person']['lastname'],
            email=appstruct['person']['email'],
            password=appstruct['person']['password'],
            address1=appstruct['person']['address1'],
            address2=appstruct['person']['address2'],
            postcode=appstruct['person']['postcode'],
            city=appstruct['person']['city'],
            country=appstruct['person']['country'],
            locale=appstruct['person']['_LOCALE_'],
            date_of_birth=appstruct['person']['date_of_birth'],
            email_is_confirmed=False,
            email_confirm_code=randomstring,
            #is_composer=('composer' in appstruct['activity']),
            #is_lyricist=('lyricist' in appstruct['activity']),
            #is_producer=('music producer' in appstruct['activity']),
            #is_remixer=('remixer' in appstruct['activity']),
            #is_dj=('dj' in appstruct['activity']),
            date_of_submission=datetime.now(),
            #invest_member=(
            #    appstruct['membership_info']['invest_member'] == u'yes'),
            membership_type=appstruct['membership_info']['membership_type'],
            member_of_colsoc=(
                appstruct['membership_info']['member_of_colsoc'] == u'yes'),
            name_of_colsoc=appstruct['membership_info']['name_of_colsoc'],
            #opt_band=appstruct['opt_band'],
            #opt_URL=appstruct['opt_URL'],
            num_shares=appstruct['shares']['num_shares'],
        )
        dbsession = DBSession()
        try:
            dbsession.add(member)
            appstruct['email_confirm_code'] = randomstring
        except InvalidRequestError, e:  # pragma: no cover
            print("InvalidRequestError! %s") % e