예제 #1
0
def test_site_config_success(config, get_csrf_request_with_db, dbsession):
    from autonomie.views.admin.main.site import (
        AdminSiteView,
        MAIN_SITE_ROUTE,
    )
    from autonomie.models.config import ConfigFiles
    config.add_route(MAIN_SITE_ROUTE, MAIN_SITE_ROUTE)
    image = file(os.path.join(DATASDIR, 'entete5_1.png'), 'r')
    datas = image.read()
    size = len(datas)
    image.seek(0)
    appstruct = {
        'welcome': 'testvalue',
        'logo': {
            'fp': image,
            'mimetype': 'image/png',
            'uid': '1',
            'name': 'F.png',
            'filename': 'F.png',
            'data': image,
            'size': size
        }
    }
    view = AdminSiteView(get_csrf_request_with_db())
    view.submit_success(appstruct)
    dbsession.flush()
    assert get_config()['welcome'] == u'testvalue'
    assert ConfigFiles.get('logo.png').name == 'F.png'
    assert ConfigFiles.get('logo.png').getvalue() == datas
def upgrade():
    from autonomie.models.company import Company
    from autonomie.models.files import File
    from autonomie.models import DBSESSION
    from alembic.context import get_bind
    from autonomie.models.config import ConfigFiles

    for i in ('header_id', 'logo_id',):
        col = sa.Column(i, sa.Integer, sa.ForeignKey('file.id'))
        op.add_column('company', col)

    query = "select id, header, logo from company;"
    conn = get_bind()
    result = conn.execute(query)

    session = DBSESSION()

    for id_, header, logo in result:
        company = Company.get(id_)
        basepath = u"%scompany/%s" % (BASEFILEPATH, id_,)

        if header:
            header_path = u"%s/header/%s" % (basepath, header)
            try:
                file_datas = load_file_struct(header_path, header)
            except:
                print("Error while loading a header")
                print(id_)
                file_datas = None
            if file_datas:
                company.header = file_datas
                session.add(company.header_file)
                session.flush()

        if logo:
            logo_path = u"%s/logo/%s" % (basepath, logo)
            try:
                file_datas = load_file_struct(logo_path, logo)
            except:
                print("Error while loading a logo")
                print(id_)
                file_datas = None
            if file_datas:
                company.logo = file_datas
                company = session.merge(company)
                session.flush()

    filepath = u"%s/main/logo.png" % BASEFILEPATH
    if os.path.isfile(filepath):
        ConfigFiles.set('logo.png', load_file_struct(filepath, 'logo.png'))

    filepath = u"%s/main/accompagnement_header.png" % BASEFILEPATH
    if os.path.isfile(filepath):
        ConfigFiles.set(
            'accompagnement_header.png',
            load_file_struct(filepath, 'accompagnement_header.png')
        )
def upgrade():
    from autonomie.models.company import Company
    from autonomie.models.files import File
    from autonomie_base.models.base import DBSESSION
    from alembic.context import get_bind
    from autonomie.models.config import ConfigFiles

    for i in ('header_id', 'logo_id',):
        col = sa.Column(i, sa.Integer, sa.ForeignKey('file.id'))
        op.add_column('company', col)

    query = "select id, header, logo from company;"
    conn = get_bind()
    result = conn.execute(query)

    session = DBSESSION()

    for id_, header, logo in result:
        company = Company.get(id_)
        basepath = u"%scompany/%s" % (BASEFILEPATH, id_,)

        if header:
            header_path = u"%s/header/%s" % (basepath, header)
            try:
                file_datas = load_file_struct(header_path, header)
            except:
                print("Error while loading a header")
                print(id_)
                file_datas = None
            if file_datas:
                company.header = file_datas
                session.add(company.header_file)
                session.flush()

        if logo:
            logo_path = u"%s/logo/%s" % (basepath, logo)
            try:
                file_datas = load_file_struct(logo_path, logo)
            except:
                print("Error while loading a logo")
                print(id_)
                file_datas = None
            if file_datas:
                company.logo = file_datas
                company = session.merge(company)
                session.flush()

    filepath = u"%s/main/logo.png" % BASEFILEPATH
    if os.path.isfile(filepath):
        ConfigFiles.set('logo.png', load_file_struct(filepath, 'logo.png'))

    filepath = u"%s/main/accompagnement_header.png" % BASEFILEPATH
    if os.path.isfile(filepath):
        ConfigFiles.set(
            'accompagnement_header.png',
            load_file_struct(filepath, 'accompagnement_header.png')
        )
예제 #4
0
    def _an_config(self):
        from autonomie.models.config import Config, ConfigFiles

        Config.set('cae_admin_mail', self.faker.ascii_safe_email())
        Config.set('welcome', self.faker.sentence(nb_words=15))
        ConfigFiles.set(
            'logo.png', {
                'data':
                pkg_resources.resource_stream('autonomie',
                                              'static/img/autonomie.jpg'),
                'filename':
                'logo.jpg',
            })
        Config.set('coop_cgv', self.faker.paragraph(nb_sentences=40))
        Config.set(
            'coop_pdffootertitle', u"""Une activité de ma CAE SARL SCOP à \
capital variable""")
        Config.set(
            'coop_pdffootercourse',
            u"""Organisme de formation N° de déclaration \
d'activité au titre de la FPC : xx xx xxxxx. MA CAE est exonérée de TVA pour \
les activités s'inscrivant dans le cadre de la formation professionnelle \
conformément à l'art. L920-4 du Code du travail et de l'art. 202 C de \
l'annexe II du code général des impôts""")
        footer = u"""RCS XXXX 000 000 000 00000 - SIRET 000 \
000 000 000 00 - Code naf 0000Z TVA INTRACOM : FR0000000. Siège social : 10 \
rue vieille 23200 Aubusson"""
        Config.set('coop_pdffootercontent', footer)
        Config.set('coop_pdffootertext', footer)
        Config.set(
            'coop_invoicepayment', u"""Par chèque libellé à l'ordre de : \
MA CAE/ %ENTREPRENEUR%
à envoyer à l'adresse suivante :
MA CAE/ %ENTREPRENEUR%
10 rue Vieille
23200 Aubusson

Ou par virement sur le compte de MA CAE/ %ENTREPRENEUR%
MA BANQUE
RIB : xxxxx xxxx xxxxxxxxxxxxx
IBAN : xxxx xxxx xxxx xxxx xxxx xxxx xxx
BIC : MABAFRMACAXX
Merci d'indiquer le numéro de facture sur le libellé de votre virement ou \
dos de votre chèque.
""")
        Config.set(
            "coop_invoicelate",
            u"""Tout retard de paiement entraînera à titre de \
clause pénale, conformément à la loi 92.1442 du 31 décembre 1992, une \
pénalité égale à un taux d'intérêt équivalent à une fois et demi le taux \
d'intérêt légal en vigueur à cette échéance.
Une indemnité de 40 euros forfaitaire sera demandée en sus pour chaque \
facture payée après l’échéance fixée. Celle-ci n’est pas soumise à TVA.""")

        Config.set("activity_footer", footer)

        Config.set('workshop_footer', footer)
예제 #5
0
    def _an_config(self):
        from autonomie.models.config import Config, ConfigFiles

        Config.set('cae_admin_mail', self.faker.ascii_safe_email())
        Config.set('welcome', self.faker.sentence(nb_words=15))
        ConfigFiles.set(
            'logo.png',
            {
                'data': pkg_resources.resource_stream(
                    'autonomie',
                    'static/img/autonomie.jpg'
                ),
                'filename': 'logo.jpg',
            }
        )
        Config.set('coop_cgv', self.faker.paragraph(nb_sentences=40))
        Config.set('coop_pdffootertitle', u"""Une activité de ma CAE SARL SCOP à \
capital variable""")
        Config.set('coop_pdffootercourse', u"""Organisme de formation N° de déclaration \
d'activité au titre de la FPC : xx xx xxxxx. MA CAE est exonérée de TVA pour \
les activités s'inscrivant dans le cadre de la formation professionnelle \
conformément à l'art. L920-4 du Code du travail et de l'art. 202 C de \
l'annexe II du code général des impôts""")
        footer = u"""RCS XXXX 000 000 000 00000 - SIRET 000 \
000 000 000 00 - Code naf 0000Z TVA INTRACOM : FR0000000. Siège social : 10 \
rue vieille 23200 Aubusson"""
        Config.set('coop_pdffootercontent', footer)
        Config.set('coop_pdffootertext', footer)
        Config.set('coop_invoicepayment', u"""Par chèque libellé à l'ordre de : \
MA CAE/ %ENTREPRENEUR%
à envoyer à l'adresse suivante :
MA CAE/ %ENTREPRENEUR%
10 rue Vieille
23200 Aubusson

Ou par virement sur le compte de MA CAE/ %ENTREPRENEUR%
MA BANQUE
RIB : xxxxx xxxx xxxxxxxxxxxxx
IBAN : xxxx xxxx xxxx xxxx xxxx xxxx xxx
BIC : MABAFRMACAXX
Merci d'indiquer le numéro de facture sur le libellé de votre virement ou \
dos de votre chèque.
""")
        Config.set("coop_invoicelate", u"""Tout retard de paiement entraînera à titre de \
clause pénale, conformément à la loi 92.1442 du 31 décembre 1992, une \
pénalité égale à un taux d'intérêt équivalent à une fois et demi le taux \
d'intérêt légal en vigueur à cette échéance.
Une indemnité de 40 euros forfaitaire sera demandée en sus pour chaque \
facture payée après l’échéance fixée. Celle-ci n’est pas soumise à TVA.""")

        Config.set("activity_footer", footer)

        Config.set('workshop_footer', footer)
예제 #6
0
    def store_pdf_conf(self, appstruct, data_type):
        """
        Store the pdf configuration for the given type

        :param dict appstruct: The datas in which we will find the pdf
        configuration
        :param str data_type: activity/workshop
        """
        pdf_appstruct = appstruct
        for file_type in ("header_img", "footer_img"):
            file_datas = pdf_appstruct.get(file_type)
            if file_datas:
                file_name = "%s_%s.png" % (data_type, file_type)
                ConfigFiles.set(file_name, file_datas)

        Config.set("%s_footer" % data_type, pdf_appstruct.get('footer', ''))
예제 #7
0
파일: site.py 프로젝트: tonthon/autonomie
    def submit_success(self, appstruct):
        """
            Insert config informations into database
        """
        # la table config étant un stockage clé valeur
        # le merge_session_with_post ne peut être utilisé
        logo = appstruct.pop('logo', None)
        if logo:
            ConfigFiles.set('logo.png', logo)
            self.request.session.pop('substanced.tempstore')
            self.request.session.changed()

        for key, value in appstruct.items():
            Config.set(key, value)
        self.request.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path(self.route_name))
예제 #8
0
 def before(self, form):
     """
         Add the appstruct to the form
     """
     config_dict = self.request.config
     logo = ConfigFiles.get('logo.png')
     appstruct = get_config_appstruct(self.request, config_dict, logo)
     form.set_appstruct(appstruct)
     tinymce.need()
예제 #9
0
 def before(self, form):
     """
         Add the appstruct to the form
     """
     config_dict = self.request.config
     logo = ConfigFiles.get('logo.png')
     appstruct = get_config_appstruct(self.request, config_dict, logo)
     form.set_appstruct(appstruct)
     tinymce.need()
예제 #10
0
    def store_pdf_conf(self, appstruct, data_type):
        """
        Store the pdf configuration for the given type

        :param dict appstruct: The datas in which we will find the pdf
        configuration
        :param str data_type: activity/workshop
        """
        pdf_appstruct = appstruct
        for file_type in ("header_img", "footer_img"):
            file_datas = pdf_appstruct.get(file_type)
            if file_datas:
                file_name = "%s_%s.png" % (data_type, file_type)
                ConfigFiles.set(file_name, file_datas)

        Config.set(
            "%s_footer" % data_type,
            pdf_appstruct.get('footer', '')
        )
예제 #11
0
파일: admin.py 프로젝트: yledoare/autonomie
    def submit_success(self, appstruct):
        """
            Handle successfull expense configuration
        """
        header = appstruct['main'].pop('header', None)
        if header is not None:
            ConfigFiles.set('accompagnement_header.png', header)
        # We delete the elements that are no longer in the appstruct
        self.disable_types(appstruct)
        self.disable_actions(appstruct)
        new_modes = self.delete_modes(appstruct)
        self.dbsession.flush()

        self.add_types(appstruct)
        self.add_actions(appstruct)
        self.add_modes(new_modes)

        self.request.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path("admin_activity"))
예제 #12
0
    def submit_success(self, appstruct):
        """
            Insert config informations into database
        """
        # la table config étant un stockage clé valeur
        # le merge_session_with_post ne peut être utilisé
        logo = appstruct['site'].pop('logo', None)
        if logo:
            ConfigFiles.set('logo.png', logo)
            self.request.session.pop('substanced.tempstore')
            self.request.session.changed()

        dbdatas = self.dbsession.query(Config).all()
        appstruct = get_config_dbdatas(appstruct)
        dbdatas = merge_config_datas(dbdatas, appstruct)
        for dbdata in dbdatas:
            self.dbsession.merge(dbdata)
        self.dbsession.flush()
        self.request.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path("admin_main"))
예제 #13
0
    def submit_success(self, appstruct):
        """
            Insert config informations into database
        """
        # la table config étant un stockage clé valeur
        # le merge_session_with_post ne peut être utilisé
        logo = appstruct['site'].pop('logo', None)
        if logo:
            ConfigFiles.set('logo.png', logo)
            self.request.session.pop('substanced.tempstore')
            self.request.session.changed()

        dbdatas = self.dbsession.query(Config).all()
        appstruct = get_config_dbdatas(appstruct)
        dbdatas = merge_config_datas(dbdatas, appstruct)
        for dbdata in dbdatas:
            self.dbsession.merge(dbdata)
        self.dbsession.flush()
        self.request.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path("admin_main"))
예제 #14
0
파일: site.py 프로젝트: tonthon/autonomie
 def before(self, form):
     """
         Add the appstruct to the form
     """
     config_dict = self.request.config
     logo = ConfigFiles.get('logo.png')
     appstruct = {}
     if logo is not None:
         appstruct["logo"] = public_file_appstruct(self.request, 'logo.png',
                                                   logo)
     appstruct['welcome'] = config_dict.get('welcome', '')
     form.set_appstruct(appstruct)
예제 #15
0
 def _add_pdf_img_to_appstruct(self, data_type, appstruct):
     for file_type in ("header_img", "footer_img"):
         file_name = "%s_%s.png" % (data_type, file_type)
         file_model = ConfigFiles.get(file_name)
         if file_model is not None:
             appstruct[file_type] = {
                 'uid': file_model.id,
                 'filename': file_model.name,
                 'preview_url': self.request.route_url(
                     'public',
                     name=file_name,
                 )
             }
예제 #16
0
def test_site_config_success(config, get_csrf_request_with_db, dbsession):
    from autonomie.views.admin.main.site import (
        AdminSiteView,
        MAIN_SITE_ROUTE,
    )
    from autonomie.models.config import ConfigFiles
    config.add_route(MAIN_SITE_ROUTE, MAIN_SITE_ROUTE)
    image = file(os.path.join(DATASDIR, 'entete5_1.png'), 'r')
    datas = image.read()
    size = len(datas)
    image.seek(0)
    appstruct = {
        'welcome': 'testvalue',
        'logo': {'fp': image, 'mimetype': 'image/png', 'uid': '1',
                 'name': 'F.png', 'filename': 'F.png', 'data': image,
                 'size': size}
    }
    view = AdminSiteView(get_csrf_request_with_db())
    view.submit_success(appstruct)
    dbsession.flush()
    assert get_config()['welcome'] == u'testvalue'
    assert ConfigFiles.get('logo.png').name == 'F.png'
    assert ConfigFiles.get('logo.png').getvalue() == datas
예제 #17
0
    def before(self, form):
        appstruct = {}

        file_name = u"competence_header.png"
        file_model = ConfigFiles.get(file_name)
        if file_model is not None:
            appstruct['header_img'] = {
                'uid': file_model.id,
                'filename': file_model.name,
                'preview_url': self.request.route_url(
                    'public',
                    name=file_name,
                )
            }
        form.set_appstruct(appstruct)
예제 #18
0
    def before(self, form):
        appstruct = {}

        file_name = u"competence_header.png"
        file_model = ConfigFiles.get(file_name)
        if file_model is not None:
            appstruct['header_img'] = {
                'uid': file_model.id,
                'filename': file_model.name,
                'preview_url': self.request.route_url(
                    'public',
                    name=file_name,
                )
            }
        form.set_appstruct(appstruct)
예제 #19
0
 def _add_pdf_img_to_appstruct(self, data_type, appstruct):
     for file_type in ("header_img", "footer_img"):
         file_name = "%s_%s.png" % (data_type, file_type)
         file_model = ConfigFiles.get(file_name)
         if file_model is not None:
             appstruct[file_type] = {
                 'uid':
                 file_model.id,
                 'filename':
                 file_model.name,
                 'preview_url':
                 self.request.route_url(
                     'public',
                     name=file_name,
                 )
             }
예제 #20
0
파일: pdf.py 프로젝트: tonthon/autonomie
def fetch_resource(uri, rel):
    """
        Callback used by pisa to locally retrieve ressources
        giving the uri
        if the uri starts with /files : we're looking for a db file
        else we're looking for a static resource
    """
    f_regex_group = FILEPATH_REGX.match(uri)
    pf_regex_group = PUBLIC_FILES_REGX.match(uri)

    if f_regex_group is not None:
        # C'est un modèle File que l'on doit renvoyer
        filename = f_regex_group.group('fileid')
        # On récupère l'objet fichier
        from autonomie.models.files import File
        fileobj = File.get(filename)
        resource = get_db_file_resource(fileobj)

    elif pf_regex_group is not None:
        key = pf_regex_group.group('filekey')
        from autonomie.models.config import ConfigFiles
        fileobj = ConfigFiles.get(key)
        resource = get_db_file_resource(fileobj)

    else:
        # C'est un fichier statique
        request = get_current_request()
        introspector = request.registry.introspector
        if uri.startswith('/'):
            uri = uri[1:]
        mainuri, sep, relative_filepath = uri.partition('/')
        mainuri = mainuri + '/'
        resource = ''
        for staticpath in introspector.get_category('static views'):
            if mainuri == staticpath['introspectable']['name']:
                basepath = staticpath['introspectable']['spec']
                resource = join(basepath, relative_filepath).encode('utf-8')
                if ':' in resource:
                    package, filename = resource.split(':')
                    resource = pkg_resources.resource_filename(
                        package,
                        filename,
                    )
                break
    return resource
예제 #21
0
def fetch_resource(uri, rel):
    """
        Callback used by pisa to locally retrieve ressources
        giving the uri
        if the uri starts with /files : we're looking for a db file
        else we're looking for a static resource
    """
    f_regex_group = FILEPATH_REGX.match(uri)
    pf_regex_group = PUBLIC_FILES_REGX.match(uri)

    if f_regex_group is not None:
        # C'est un modèle File que l'on doit renvoyer
        filename = f_regex_group.group('fileid')
        # On récupère l'objet fichier
        from autonomie.models.files import File
        fileobj = File.get(filename)
        resource = get_db_file_resource(fileobj)

    elif pf_regex_group is not None:
        key = pf_regex_group.group('filekey')
        from autonomie.models.config import ConfigFiles
        fileobj = ConfigFiles.get(key)
        resource = get_db_file_resource(fileobj)

    else:
        # C'est un fichier statique
        request = get_current_request()
        introspector = request.registry.introspector
        if uri.startswith('/'):
            uri = uri[1:]
        mainuri, sep, relative_filepath = uri.partition('/')
        mainuri = mainuri + '/'
        resource = ''
        for staticpath in introspector.get_category('static views'):
            if mainuri == staticpath['introspectable']['name']:
                basepath = staticpath['introspectable']['spec']
                resource = join(basepath, relative_filepath).encode('utf-8')
                if ':' in resource:
                    package, filename = resource.split(':')
                    resource = pkg_resources.resource_filename(
                        package,
                        filename,
                    )
                break
    return resource
예제 #22
0
파일: admin.py 프로젝트: yledoare/autonomie
    def before(self, form):
        """
            Add appstruct to the current form object
        """
        query = ActivityType.query()
        types = query.filter(ActivityType.active==True)

        modes = ActivityMode.query()

        query = ActivityAction.query()
        query = query.filter(ActivityAction.parent_id==None)
        actions = query.filter(ActivityAction.active==True)


        appstruct = {
            'main': {},
            'types': [type_.appstruct() for type_ in types],
            'modes': [mode.appstruct() for mode in modes],
            'actions': [
                {
                'id': act.id,
                'label': act.label,
                'children': [child.appstruct() for child in act.children],
                }
                for act in actions]
        }

        accompagnement_file = ConfigFiles.get('accompagnement_header.png')
        if accompagnement_file is not None:
            appstruct['main']['header'] = {
                'uid': accompagnement_file.id,
                'filename': accompagnement_file.name,
                'preview_url': self.request.route_url(
                    'public',
                    name='accompagnement_header.png',
                )
            }

        form.set_appstruct(appstruct)
        populate_actionmenu(self.request)
예제 #23
0
    def submit_success(self, appstruct):
        file_datas = appstruct.get('header_img')

        if file_datas:
            file_name = "competence_header.png"
            ConfigFiles.set(file_name, file_datas)
예제 #24
0
    def submit_success(self, appstruct):
        file_datas = appstruct.get('header_img')

        if file_datas:
            file_name = "competence_header.png"
            ConfigFiles.set(file_name, file_datas)