Exemplo n.º 1
0
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    from autonomie.models.config import Config
    session = DBSESSION()
    from alembic.context import get_bind
    conn = get_bind()

    initial_values = [
        ('bookentry_facturation_label_template',
         '{invoice.customer.label} {company.name}'),
        ('bookentry_contribution_label_template',
         "{invoice.customer.label} {company.name}"),
        ('bookentry_rg_interne_label_template',
         "RG COOP {invoice.customer.label} {company.name}"),
        ('bookentry_rg_client_label_template',
         "RG {invoice.customer.label} {company.name}"),
        ('bookentry_expense_label_template',
         "{beneficiaire}/frais {expense_date:%-m %Y}"),
        ('bookentry_payment_label_template',
         "{company.name} / Rgt {invoice.customer.label}"),
        ('bookentry_expense_payment_main_label_template',
         "{beneficiaire_LASTNAME} / REMB FRAIS {expense_date:%B/%Y}"),
        ('bookentry_expense_payment_waiver_label_template',
         "Abandon de créance {beneficiaire_LASTNAME} {expense_date:%B/%Y}"),
    ]

    for key, val in initial_values:
        Config.set(key, val)
Exemplo n.º 2
0
    def submit_success(self, appstruct):
        """
        Handle successfull configuration
        """
        appstruct = flatten_appstruct(appstruct)
        for key in self.keys:

            value = appstruct.pop(key, None)
            if value is None:
                continue

            cfg_obj = Config.get(key) or Config(name=key)
            cfg_obj.value = value

            self.dbsession.add(cfg_obj)

            logger.debug(u" # Setting configuration")
            logger.debug(u"{0} : {1}".format(key, value))

        self.request.session.flash(self.validation_msg)
        back_link = self.back_link
        if back_link is not None:
            result = HTTPFound(self.back_link)
        else:
            logger.error(u"This view %s is not able to provide a back_link "
                         u"after validation" % self)
            result = None
        return result
Exemplo n.º 3
0
def populate_accounting_treasury_measure_types(session):
    """
    Populate the database with treasury measure types
    """
    from autonomie.models.config import Config
    from autonomie.models.accounting.treasury_measures import (
        TreasuryMeasureType,
    )
    if session.query(TreasuryMeasureType.id).count() == 0:
        for internal_id, start, label in (
            (1, '5', u"Trésorerie du jour",),
            (2, "42,-421,-425,43,44", u"Impôts, taxes et cotisations dues",),
            (3, "40", u"Fournisseurs à payer",),
            (5, "421", u"Salaires à payer",),
            (6, "41", u"Clients à encaisser"),
            (7, '425', u"Notes de dépenses à payer"),
            (9, "1,2,3", u"Comptes bilan non pris en compte"),
        ):
            session.add(
                TreasuryMeasureType(
                    internal_id=internal_id, account_prefix=start, label=label
                )
            )
        Config.set("treasury_measure_ui", "1")
        session.flush()
Exemplo n.º 4
0
 def submit_success(self, appstruct):
     """
         Insert config informations into database
     """
     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))
Exemplo n.º 5
0
 def submit_success(self, appstruct):
     """
         Insert config informations into database
     """
     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))
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    session = DBSESSION()
    from alembic.context import get_bind
    conn = get_bind()
    from autonomie.models.config import Config
    Config.set('accounting_label_maxlength', 35)
    session.flush()
Exemplo n.º 7
0
def create_custom_treasury_modules(session, logger):
    logger.warn("Adding custom treasury modules")
    from autonomie.models.config import Config
    from autonomie.models.treasury import CustomInvoiceBookEntryModule

    organic_keys = (
        u"Contribution à l'organic",
        'compte_cg_organic',
        'compte_cg_debiteur_organic',
        'taux_contribution_organic',
        'sage_organic',
        u'Contribution Organic {client.name} {entreprise.name}'
    )

    cgscop_keys = (
        u"Contribution à la CGSCOP",
        'compte_cgscop',
        'compte_cg_debiteur',
        'taux_cgscop',
        'sage_cgscop',
        u'{client.name} {entreprise.name}'
    )

    assurance_keys = (
        u"Assurance",
        'compte_cg_assurance',
        'compte_cg_assurance',
        'taux_assurance',
        'sage_assurance',
        u'{client.name} {entreprise.name}',
    )

    for keys in (organic_keys, cgscop_keys, assurance_keys, ):
        (
            title,
            cg_debit,
            cg_credit,
            percentage_key,
            active_key,
            label_template
        ) = keys

        compte_cg_debit = Config.get(cg_debit)
        compte_cg_credit = Config.get(cg_credit)
        percentage = Config.get(percentage_key)
        enabled = Config.get(active_key, False)
        if compte_cg_debit and compte_cg_debit.value and compte_cg_credit and compte_cg_credit.value and percentage is not None:
            module = CustomInvoiceBookEntryModule(
                title=title,
                compte_cg_debit=compte_cg_debit.value,
                compte_cg_credit=compte_cg_credit.value,
                percentage=percentage.value,
                enabled=enabled.value,
                label_template=label_template,
            )
            session.add(module)
def create_custom_treasury_modules(session, logger):
    logger.warn("Adding custom treasury modules")
    from autonomie.models.config import Config
    from autonomie.models.treasury import CustomInvoiceBookEntryModule

    organic_keys = (
        u"Contribution à l'organic",
        'compte_cg_organic',
        'compte_cg_debiteur_organic',
        'taux_contribution_organic',
        'sage_organic',
        u'Contribution Organic {client.name} {entreprise.name}'
    )

    cgscop_keys = (
        u"Contribution à la CGSCOP",
        'compte_cgscop',
        'compte_cg_debiteur',
        'taux_cgscop',
        'sage_cgscop',
        u'{client.name} {entreprise.name}'
    )

    assurance_keys = (
        u"Assurance",
        'compte_cg_assurance',
        'compte_cg_assurance',
        'taux_assurance',
        'sage_assurance',
        u'{client.name} {entreprise.name}',
    )

    for keys in (organic_keys, cgscop_keys, assurance_keys, ):
        (
            title,
            cg_debit,
            cg_credit,
            percentage_key,
            active_key,
            label_template
        ) = keys

        compte_cg_debit = Config.get(cg_debit)
        compte_cg_credit = Config.get(cg_credit)
        percentage = Config.get(percentage_key)
        enabled = Config.get(active_key, False)
        if compte_cg_debit and compte_cg_debit.value and compte_cg_credit and compte_cg_credit.value and percentage is not None:
            module = CustomInvoiceBookEntryModule(
                title=title,
                compte_cg_debit=compte_cg_debit.value,
                compte_cg_credit=compte_cg_credit.value,
                percentage=percentage.value,
                enabled=enabled.value,
                label_template=label_template,
            )
            session.add(module)
def test_global_invoice_sequence_initialization(
        invoice,
        set_global_seq_index,
):
    from autonomie.models.config import Config
    Config.set('global_sequence_init_value', 12)

    assert GlobalInvoiceSequence.get_next_index(invoice) == 13

    # ignore initialization if there is an actual SequenceNumber
    set_global_seq_index(index=20)
    assert GlobalInvoiceSequence.get_next_index(invoice) == 21
Exemplo n.º 10
0
def test_global_invoice_sequence_initialization(
    invoice,
    set_global_seq_index,
):
    from autonomie.models.config import Config
    Config.set('global_sequence_init_value', 12)

    assert GlobalInvoiceSequence.get_next_index(invoice) == 13

    # ignore initialization if there is an actual SequenceNumber
    set_global_seq_index(index=20)
    assert GlobalInvoiceSequence.get_next_index(invoice) == 21
Exemplo n.º 11
0
 def _get_initial_value(cls, invoice):
     init_date = Config.get_value(
         'year_sequence_init_date',
         default=None,
         type_=date,
     )
     init_value = Config.get_value(
         'year_sequence_init_value',
         default=None,
         type_=int,
     )
     if init_date and init_value and init_date.year == invoice.date.year:
         return init_value
Exemplo n.º 12
0
def merge_config_datas(dbdatas, appstruct):
    """
        Merge the datas returned by form validation and the original dbdatas
    """
    flat_appstruct = forms.flatten_appstruct(appstruct)
    for name, value in flat_appstruct.items():
        dbdata = get_element_by_name(dbdatas, name)
        if not dbdata:
            # The key 'name' doesn't exist in the database, adding new one
            dbdata = Config(name=name, value=value)
            dbdatas.append(dbdata)
        else:
            dbdata.value = value
    return dbdatas
Exemplo n.º 13
0
def merge_config_datas(dbdatas, appstruct):
    """
        Merge the datas returned by form validation and the original dbdatas
    """
    flat_appstruct = forms.flatten_appstruct(appstruct)
    for name, value in flat_appstruct.items():
        dbdata = get_element_by_name(dbdatas, name)
        if not dbdata:
            # The key 'name' doesn't exist in the database, adding new one
            dbdata = Config(name=name, value=value)
            dbdatas.append(dbdata)
        else:
            dbdata.value = value
    return dbdatas
Exemplo n.º 14
0
    def submit_success(self, appstruct):
        """
        Handle successfull configuration
        """
        appstruct = flatten_appstruct(appstruct)
        for key in self.keys:

            value = appstruct.pop(key, None)
            if value is None:
                continue

            cfg_obj = Config.get(key) or Config(name=key)
            cfg_obj.value = value

            self.dbsession.add(cfg_obj)

            logger.debug(u" # Setting configuration")
            logger.debug(u"{0} : {1}".format(key, value))

        self.request.session.flash(self.validation_msg)
        back_link = self.back_link
        if back_link is not None:
            result = HTTPFound(self.back_link)
        else:
            logger.error(u"This view %s is not able to provide a back_link "
                         u"after validation" % self)
            result = None
        return result
Exemplo n.º 15
0
def test_load_value(dbsession):
    from autonomie.models.config import get_config, Config
    dbsession.add(Config(name="name", value="value"))
    dbsession.flush()
    all_ = get_config()
    assert "name" in all_.keys()
    assert all_["name"] == "value"
Exemplo n.º 16
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é
        dbdatas = Config.query().all()

        log.debug(u"Cae configuration submission")
        log.debug(appstruct)

        new_dbdatas = merge_config_datas(dbdatas, appstruct)
        for dbdata in new_dbdatas:
            log.debug(dbdata.name)
            if dbdata in dbdatas:
                self.dbsession.merge(dbdata)
            else:
                self.dbsession.add(dbdata)
            # If we set the contribution_cae value, we want it to be the default
            # for every company that has no contribution value set
            if dbdata.name == 'contribution_cae':
                for comp in Company.query():
                    if comp.contribution is None:
                        comp.contribution = dbdata.value
                        self.dbsession.merge(comp)
        self.dbsession.flush()
        self.request.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path("admin_cae"))
 def highlight_key(self):
     config_key = Config.get("treasury_measure_ui")
     if config_key is None:
         key = 1
     else:
         key = int(config_key.value)
     return key
Exemplo n.º 18
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', ''))
Exemplo n.º 19
0
 def _get_initial_value(cls, invoice):
     init_date = Config.get_value(
         'month_sequence_init_date',
         None,
         type_=date,
     )
     init_value = Config.get_value(
         'month_sequence_init_value',
         default=None,
         type_=int,
     )
     if (init_date and init_value and init_date.year == invoice.date.year
             and init_date.month == invoice.date.month):
         return init_value
     else:
         return None
Exemplo n.º 20
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.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))
Exemplo n.º 21
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é
        dbdatas = Config.query().all()

        log.debug(u"Cae configuration submission")
        log.debug(appstruct)

        new_dbdatas = merge_config_datas(dbdatas, appstruct)
        for dbdata in new_dbdatas:
            log.debug(dbdata.name)
            if dbdata in dbdatas:
                self.dbsession.merge(dbdata)
            else:
                self.dbsession.add(dbdata)
            # If we set the contribution_cae value, we want it to be the default
            # for every company that has no contribution value set
            if dbdata.name == 'contribution_cae':
                for comp in Company.query():
                    if comp.contribution is None:
                        comp.contribution = dbdata.value
                        self.dbsession.merge(comp)
        self.dbsession.flush()
        self.request.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path("admin_cae"))
def migrate_datas():
    logger = logging.getLogger("alembic.autonomie")
    from autonomie_base.models.base import DBSESSION
    session = DBSESSION()
    from autonomie.models.config import Config
    import json

    from autonomie.models.files import (
        File,
        FileType,
    )
    json_str = Config.get_value("attached_filetypes", "[]")
    try:
        configured_filetypes = json.loads(json_str)
    except:
        logger.exception(u"Error in json str : %s" % json_str)
        configured_filetypes = []
    if configured_filetypes:
        result = []
        for filetype_label in configured_filetypes:
            if filetype_label:
                filetype = FileType(label=filetype_label)
                session.add(filetype)
                session.flush()
                result.append(filetype)

        for typ_ in result:
            query = File.query().filter_by(label=typ_.label)
            for file_ in query:
                file_.file_type_id = typ_.id
                session.merge(file_)
        session.flush()
Exemplo n.º 23
0
 def highlight_key(self):
     config_key = Config.get("treasury_measure_ui")
     if config_key is None:
         key = 1
     else:
         key = int(config_key.value)
     return key
def migrate_datas():
    logger = logging.getLogger("alembic.autonomie")
    from autonomie_base.models.base import DBSESSION
    session = DBSESSION()
    from autonomie.models.config import Config
    import json

    from autonomie.models.files import (
        File,
        FileType,
    )
    json_str = Config.get_value("attached_filetypes", "[]")
    try:
        configured_filetypes = json.loads(json_str)
    except:
        logger.exception(u"Error in json str : %s" % json_str)
        configured_filetypes = []
    if configured_filetypes:
        result = []
        for filetype_label in configured_filetypes:
            if filetype_label:
                filetype = FileType(label=filetype_label)
                session.add(filetype)
                session.flush()
                result.append(filetype)

        for typ_ in result:
            query = File.query().filter_by(label=typ_.label)
            for file_ in query:
                file_.file_type_id = typ_.id
                session.merge(file_)
        session.flush()
Exemplo n.º 25
0
def content(connection, settings):
    """
    sets up some default content
    """
    from transaction import commit
    from autonomie_base.models.base import (
        DBBASE, )
    metadata = DBBASE.metadata

    metadata.drop_all(connection.engine)
    from autonomie.models import adjust_for_engine
    adjust_for_engine(connection.engine)
    metadata.create_all(connection.engine)

    from autonomie.models.config import Config
    Config.set('invoice_number_template', '{SEQYEAR}')
    commit()
Exemplo n.º 26
0
def config(dbsession):
    from autonomie.models.config import Config
    c = Config(
        name='csv_import',
        value='{"test en action": {"PR\\u00e9nom": "coordonnees_firstname"}}')
    dbsession.add(c)
    dbsession.flush()
    return c
Exemplo n.º 27
0
def content(connection, settings):
    """
    sets up some default content
    """
    from transaction import commit
    from autonomie_base.models.base import (
        DBBASE,
    )
    metadata = DBBASE.metadata

    metadata.drop_all(connection.engine)
    from autonomie.models import adjust_for_engine
    adjust_for_engine(connection.engine)
    metadata.create_all(connection.engine)

    from autonomie.models.config import Config
    Config.set('invoice_number_template', '{SEQYEAR}')
    commit()
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    from autonomie.models.config import Config
    session = DBSESSION()
    from alembic.context import get_bind
    conn = get_bind()

    initial_values = [
        (
            'bookentry_facturation_label_template',
            '{invoice.customer.label} {company.name}'
        ),
        (
            'bookentry_contribution_label_template',
            "{invoice.customer.label} {company.name}"
        ),
        (
            'bookentry_rg_interne_label_template',
            "RG COOP {invoice.customer.label} {company.name}"
        ),
        (
            'bookentry_rg_client_label_template',
            "RG {invoice.customer.label} {company.name}"
        ),
        (
            'bookentry_expense_label_template',
            "{beneficiaire}/frais {expense_date:%-m %Y}"
        ),
        (
            'bookentry_payment_label_template',
            "{company.name} / Rgt {invoice.customer.label}"
        ),
        (
            'bookentry_expense_payment_main_label_template',
            "{beneficiaire_LASTNAME} / REMB FRAIS {expense_date:%B/%Y}"
        ),
        (
            'bookentry_expense_payment_waiver_label_template',
            "Abandon de créance {beneficiaire_LASTNAME} {expense_date:%B/%Y}"
        ),
    ]

    for key, val in initial_values:
        Config.set(key, val)
Exemplo n.º 29
0
def test_year_invoice_sequence_initialization(
    mk_invoice,
    set_year_seq_index,
):
    YIS = YearInvoiceSequence

    from autonomie.models.config import Config
    Config.set('year_sequence_init_value', 12)
    Config.set('year_sequence_init_date', date(2017, 2, 1))

    # year with initialization
    assert YIS.get_next_index(mk_invoice(date=date(2017, 6, 1))) == 13

    # year without initialization
    assert YIS.get_next_index(mk_invoice(date=date(2018, 3, 1))) == 1

    # ignore initialization if there is an actual SequenceNumber
    set_year_seq_index(index=20, year=2017)
    assert YIS.get_next_index(mk_invoice(date=date(2017, 2, 1))) == 21
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    from autonomie.models.config import Config

    session = DBSESSION()

    Config.query().filter_by(app='autonomie',
                             name='invoice_number_template').delete()

    prefix = session.query(Config.value).filter_by(
        app='autonomie',
        name='invoiceprefix',
    ).scalar() or ''

    default_format = Config(app='autonomie',
                            name='invoice_number_template',
                            value=prefix + '{SEQYEAR}')
    session.add(default_format)
    session.flush()
def test_month_invoice_sequence_initialization(
        mk_invoice,
        set_month_seq_index,
):
    MIS = MonthInvoiceSequence

    from autonomie.models.config import Config
    Config.set('month_sequence_init_value', 12)
    Config.set('month_sequence_init_date', date(2017, 2, 1))

    # month with initialization
    assert MIS.get_next_index(mk_invoice(date=date(2017, 2, 1))) == 13

    # month without initialization
    assert MIS.get_next_index(mk_invoice(date=date(2017, 3, 1))) == 1

    # ignore initialization if there is an actual SequenceNumber
    set_month_seq_index(index=20, year=2017, month=2)
    assert MIS.get_next_index(mk_invoice(date=date(2017, 2, 1))) == 21
def test_year_invoice_sequence_initialization(
        mk_invoice,
        set_year_seq_index,
):
    YIS = YearInvoiceSequence

    from autonomie.models.config import Config
    Config.set('year_sequence_init_value', 12)
    Config.set('year_sequence_init_date', date(2017, 2, 1))

    # year with initialization
    assert YIS.get_next_index(mk_invoice(date=date(2017, 6, 1))) == 13

    # year without initialization
    assert YIS.get_next_index(mk_invoice(date=date(2018, 3, 1))) == 1

    # ignore initialization if there is an actual SequenceNumber
    set_year_seq_index(index=20, year=2017)
    assert YIS.get_next_index(mk_invoice(date=date(2017, 2, 1))) == 21
Exemplo n.º 33
0
def test_month_invoice_sequence_initialization(
    mk_invoice,
    set_month_seq_index,
):
    MIS = MonthInvoiceSequence

    from autonomie.models.config import Config
    Config.set('month_sequence_init_value', 12)
    Config.set('month_sequence_init_date', date(2017, 2, 1))

    # month with initialization
    assert MIS.get_next_index(mk_invoice(date=date(2017, 2, 1))) == 13

    # month without initialization
    assert MIS.get_next_index(mk_invoice(date=date(2017, 3, 1))) == 1

    # ignore initialization if there is an actual SequenceNumber
    set_month_seq_index(index=20, year=2017, month=2)
    assert MIS.get_next_index(mk_invoice(date=date(2017, 2, 1))) == 21
Exemplo n.º 34
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', '')
        )
def migrate_datas():
    from autonomie.models.project.types import BusinessType
    from autonomie.models.config import Config
    from autonomie.models.task.mentions import TaskMention
    from autonomie.models.project.mentions import BusinessTypeTaskMention
    from autonomie_base.models.base import DBSESSION
    from alembic.context import get_bind
    session = DBSESSION()
    conn = get_bind()

    # Collect business type ids
    business_type_ids = [b[0] for b in session.query(BusinessType.id)]

    # for each fixed config key we now use mentions
    for index, (doctype, key, label, title) in enumerate(((
            'estimation',
            'coop_estimationfooter',
            u"Informations sur l'acceptation des devis",
            u"Acceptation du devis",
    ), (
            "invoice",
            "coop_invoicepayment",
            u"Informations de paiement pour les factures",
            u"Mode de paiement",
    ), (
            "invoice",
            "coop_invoicelate",
            u"Informations sur les retards de paiement",
            u"Retard de paiement",
    ))):
        # We retrieve the configurated value
        value = Config.get_value(key, "")
        mention = TaskMention(
            order=index,
            label=label,
            title=title,
            full_text=value.replace('%IBAN%', "{IBAN}").replace(
                '%RIB%', "{RIB}").replace('%ENTREPRENEUR%', '{name}'))
        session.add(mention)
        session.flush()

        for btype_id in business_type_ids:
            rel = BusinessTypeTaskMention(
                task_mention_id=mention.id,
                business_type_id=btype_id,
                doctype=doctype,
                mandatory=True,
            )
            session.add(rel)
            session.flush()

        op.execute(
            u"INSERT INTO mandatory_task_mention_rel (task_id, mention_id) \
    SELECT task.id, {mention_id} from task join node on task.id=node.id where \
    node.type_='{type_}'".format(mention_id=mention.id, type_=doctype))
Exemplo n.º 36
0
def test_base_config_view(config, dbsession, get_csrf_request_with_db):
    from autonomie.views.admin.tools import BaseConfigView
    from autonomie.forms.admin import get_config_schema

    class TestView(BaseConfigView):
        title = u"Test",
        keys = ('test_key1', 'test_key2')
        schema = get_config_schema(keys)
        validation_msg = u"Ok"
        redirect_path = "test"

    config.add_route(TestView.redirect_path, '/')

    appstruct = {'test_key1': 'test1', 'test_wrong_key': 'test error'}

    view = TestView(get_csrf_request_with_db())
    view.submit_success(appstruct)

    assert Config.get('test_key1').value == 'test1'
    assert Config.get('test_wrong_key') == None
Exemplo n.º 37
0
    def _set_config_value(self, appstruct, config_key, appstruct_key):
        """
        Set a config value
        :param appstruct: the form submitted values
        :param config_key: The name of the configuration key
        :param appstruct_key: The name of the key in the appstruct
        """
        cfg_obj = self._get_actual_config_obj(config_key)
        value = appstruct.pop(appstruct_key, None)

        if value:
            if cfg_obj is None:
                cfg_obj = Config(name=config_key, value=value)
                self.dbsession.add(cfg_obj)

            else:
                cfg_obj.value = value
                self.dbsession.merge(cfg_obj)

        log.debug(u"Setting the new {0} : {1}".format(config_key, value))
Exemplo n.º 38
0
    def _set_config_value(self, appstruct, config_key, appstruct_key):
        """
        Set a config value
        :param appstruct: the form submitted values
        :param config_key: The name of the configuration key
        :param appstruct_key: The name of the key in the appstruct
        """
        cfg_obj = self._get_actual_config_obj(config_key)
        value = appstruct.pop(appstruct_key, None)

        if value:
            if cfg_obj is None:
                cfg_obj = Config(name=config_key, value=value)
                self.dbsession.add(cfg_obj)

            else:
                cfg_obj.value = value
                self.dbsession.merge(cfg_obj)

        log.debug(u"Setting the new {0} : {1}".format(config_key, value))
Exemplo n.º 39
0
def test_base_config_view(config, dbsession, get_csrf_request_with_db):
    from autonomie.views.admin.tools import BaseConfigView
    from autonomie.forms.admin import get_config_schema

    class TestView(BaseConfigView):
        title = u"Test",
        keys = ('test_key1', 'test_key2')
        schema = get_config_schema(keys)
        validation_msg = u"Ok"
        redirect_path = "test"

    config.add_route(TestView.redirect_path, '/')

    appstruct = {'test_key1': 'test1', 'test_wrong_key': 'test error'}

    view = TestView(get_csrf_request_with_db())
    view.submit_success(appstruct)

    assert Config.get('test_key1').value == 'test1'
    assert Config.get('test_wrong_key') == None
Exemplo n.º 40
0
def populate_bookentry_config(session):
    from autonomie.models.config import Config
    initial_values = [
        (
            'bookentry_facturation_label_template',
            '{invoice.customer.label} {company.name}'
        ),
        (
            'bookentry_contribution_label_template',
            "{invoice.customer.label} {company.name}"
        ),
        (
            'bookentry_rg_interne_label_template',
            "RG COOP {invoice.customer.label} {company.name}"
        ),
        (
            'bookentry_rg_client_label_template',
            "RG {invoice.customer.label} {company.name}"
        ),
        (
            'bookentry_expense_label_template',
            "{beneficiaire}/frais {expense_date:%-m %Y}"
        ),
        (
            'bookentry_payment_label_template',
            "{company.name} / Rgt {invoice.customer.label}"
        ),
        (
            'bookentry_expense_payment_main_label_template',
            "{beneficiaire_LASTNAME} / REMB FRAIS {expense_date:%B/%Y}"
        ),
        (
            'bookentry_expense_payment_waiver_label_template',
            "Abandon de créance {beneficiaire_LASTNAME} {expense_date:%B/%Y}"
        ),

    ]

    for key, val in initial_values:
        Config.set(key, val)
Exemplo n.º 41
0
def populate_accounting_treasury_measure_types(session):
    """
    Populate the database with treasury measure types
    """
    from autonomie.models.config import Config
    from autonomie.models.accounting.treasury_measures import (
        TreasuryMeasureType, )
    if session.query(TreasuryMeasureType.id).count() == 0:
        for internal_id, start, label in (
            (
                1,
                '5',
                u"Trésorerie du jour",
            ),
            (
                2,
                "42,-421,-425,43,44",
                u"Impôts, taxes et cotisations dues",
            ),
            (
                3,
                "40",
                u"Fournisseurs à payer",
            ),
            (
                5,
                "421",
                u"Salaires à payer",
            ),
            (6, "41", u"Clients à encaisser"),
            (7, '425', u"Notes de dépenses à payer"),
            (9, "1,2,3", u"Comptes bilan non pris en compte"),
        ):
            session.add(
                TreasuryMeasureType(internal_id=internal_id,
                                    account_prefix=start,
                                    label=label))
        Config.set("treasury_measure_ui", "1")
        session.flush()
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    from autonomie.models.config import Config

    session = DBSESSION()

    Config.query().filter_by(
        app='autonomie',
        name='invoice_number_template'
    ).delete()

    prefix = session.query(Config.value).filter_by(
        app='autonomie',
        name='invoiceprefix',
    ).scalar() or ''

    default_format = Config(
        app='autonomie',
        name='invoice_number_template',
        value=prefix + '{SEQYEAR}'
    )
    session.add(default_format)
    session.flush()
Exemplo n.º 43
0
def help_text_libelle_comptable():
    """
    Hack to allow dynamic content in a description field description.
    """
    base = u"Les variables disponibles \
pour la génération des écritures sont décrites en haut de page."
    maxlength = Config.get_value('accounting_label_maxlength', None)
    if maxlength:
        return u"{} NB : les libellés sont tronqués à ".format(base) + \
            u"{} caractères au moment de l'export.".format(maxlength) + \
            u"Il est possible de changer cette taille dans  " +\
            u"Configuration → Logiciel de comptabilité."
    else:
        return base
Exemplo n.º 44
0
def populate_bookentry_config(session):
    from autonomie.models.config import Config
    initial_values = [
        ('bookentry_facturation_label_template',
         '{invoice.customer.label} {company.name}'),
        ('bookentry_contribution_label_template',
         "{invoice.customer.label} {company.name}"),
        ('bookentry_rg_interne_label_template',
         "RG COOP {invoice.customer.label} {company.name}"),
        ('bookentry_rg_client_label_template',
         "RG {invoice.customer.label} {company.name}"),
        ('bookentry_expense_label_template',
         "{beneficiaire}/frais {expense_date:%-m %Y}"),
        ('bookentry_payment_label_template',
         "{company.name} / Rgt {invoice.customer.label}"),
        ('bookentry_expense_payment_main_label_template',
         "{beneficiaire_LASTNAME} / REMB FRAIS {expense_date:%B/%Y}"),
        ('bookentry_expense_payment_waiver_label_template',
         "Abandon de créance {beneficiaire_LASTNAME} {expense_date:%B/%Y}"),
    ]

    for key, val in initial_values:
        Config.set(key, val)
Exemplo n.º 45
0
def help_text_libelle_comptable(*args):
    """
    Hack to allow dynamic content in a description field description.
    """
    base = u"Les variables disponibles \
pour la génération des écritures sont décrites en haut de page."
    maxlength = Config.get_value('accounting_label_maxlength', None)
    if maxlength:
        return u"{} NB : les libellés sont tronqués à ".format(base) + \
            u"{} caractères au moment de l'export.".format(maxlength) + \
            u"Il est possible de changer cette taille dans  " +\
            u"Configuration → Logiciel de comptabilité."
    else:
        return base
Exemplo n.º 46
0
def test_expense_config_success(config, dbsession, get_csrf_request_with_db):
    from autonomie.views.admin import AdminExpense
    config.add_route('admin_expense', '/')
    appstruct = {
            "code_journal": "JOURNAL01",
            'compte_cg': "DOE548",
            'expenses':[
{'label':u"Restauration", "code":u"0001", "id":None, 'compte_tva':"CTVA" },

{'label':u"Déplacement", "code":u"0002", "id":None, 'code_tva':"TVA"}
        ],
                'expenseskm':[
{'label':u"Scooter", "code":u"0003", "amount":"0.852", "id":None,
    'code_tva':"TVA1"}],
                'expensestel':[
{'label':u"Adsl-Téléphone", "code":u"0004", "percentage":"80",
    "id":None, "code_tva": "TVA2", 'contribution': True}]}
    view = AdminExpense(get_csrf_request_with_db())
    view.submit_success(appstruct)

    assert "DOE548" == Config.get('compte_cg_ndf').value
    assert "JOURNAL01" == Config.get('code_journal_ndf').value

    form = DummyForm()
    view.before(form)
    assert len(form.appstruct['expenses']) == 2
    assert form.appstruct['expenses'][0]['label'] == u"Restauration"
    assert form.appstruct['expenses'][0]['code'] == u"0001"
    assert form.appstruct['expenses'][0]['compte_tva'] == "CTVA"
    assert form.appstruct['expenses'][1]['code_tva'] == "TVA"

    assert form.appstruct['expenseskm'][0]['label'] == u"Scooter"
    assert form.appstruct['expenseskm'][0]['amount'] == 0.852
    assert form.appstruct['expenseskm'][0]['code_tva'] == 'TVA1'
    assert form.appstruct['expensestel'][0]['percentage'] == 80
    assert form.appstruct['expensestel'][0]['code_tva'] == 'TVA2'
    assert form.appstruct['expensestel'][0]['contribution'] == True
Exemplo n.º 47
0
def test_expense_config_success(config, dbsession, get_csrf_request_with_db):
    from autonomie.views.admin.main import AdminExpense
    config.add_route('admin_expense', '/')
    appstruct = {
            "code_journal": "JOURNAL01",
            'compte_cg': "DOE548",
            'expenses':[
{'label':u"Restauration", "code":u"0001", "id":None, 'compte_tva':"CTVA" },

{'label':u"Déplacement", "code":u"0002", "id":None, 'code_tva':"TVA"}
        ],
                'expenseskm':[
{'label':u"Scooter", "code":u"0003", "amount":"0.852", "id":None,
    'code_tva':"TVA1"}],
                'expensestel':[
{'label':u"Adsl-Téléphone", "code":u"0004", "percentage":"80",
    "id":None, "code_tva": "TVA2", 'contribution': True}]}
    view = AdminExpense(get_csrf_request_with_db())
    view.submit_success(appstruct)

    assert "DOE548" == Config.get('compte_cg_ndf').value
    assert "JOURNAL01" == Config.get('code_journal_ndf').value

    form = DummyForm()
    view.before(form)
    assert len(form.appstruct['expenses']) == 2
    assert form.appstruct['expenses'][0]['label'] == u"Restauration"
    assert form.appstruct['expenses'][0]['code'] == u"0001"
    assert form.appstruct['expenses'][0]['compte_tva'] == "CTVA"
    assert form.appstruct['expenses'][1]['code_tva'] == "TVA"

    assert form.appstruct['expenseskm'][0]['label'] == u"Scooter"
    assert form.appstruct['expenseskm'][0]['amount'] == 0.852
    assert form.appstruct['expenseskm'][0]['code_tva'] == 'TVA1'
    assert form.appstruct['expensestel'][0]['percentage'] == 80
    assert form.appstruct['expensestel'][0]['code_tva'] == 'TVA2'
    assert form.appstruct['expensestel'][0]['contribution'] == True
Exemplo n.º 48
0
    def submit_success(self, appstruct):
        """
        Handle successfull configuration
        """
        appstruct = flatten_appstruct(appstruct)
        for key in self.keys:

            value = appstruct.pop(key, None)
            if value is None:
                continue

            cfg_obj = Config.get(key) or Config(name=key)
            cfg_obj.value = value

            self.dbsession.add(cfg_obj)

            logger.debug(u" # Setting configuration")
            logger.debug(u"{0} : {1}".format(key, value))

        self.request.session.flash(self.validation_msg)
        if self.redirect_path is not None:
            return HTTPFound(self.request.route_path(self.redirect_path))
        else:
            return HTTPFound(self.request.current_route_path())
Exemplo n.º 49
0
def _set_invoice_number(request, task, **kw):
    """
    Set a official number on invoices (or cancelinvoices)

    :param obj request: The current pyramid request
    :param obj task: The current context
    """
    template = Config.get_value('invoice_number_template', None)
    assert template is not None, \
        'invoice_number_template setting should be set'

    if task.official_number is None:
        InvoiceNumberService.assign_number(
            task,
            template,
        )
    return task
Exemplo n.º 50
0
def _set_invoice_number(request, task, **kw):
    """
    Set a official number on invoices (or cancelinvoices)

    :param obj request: The current pyramid request
    :param obj task: The current context
    """
    template = Config.get_value('invoice_number_template', None)
    assert template is not None, \
        'invoice_number_template setting should be set'

    if task.official_number is None:
        InvoiceNumberService.assign_number(
            task,
            template,
        )
    return task
Exemplo n.º 51
0
    def _get_common_invoice(self, user):
        """
            Return an invoice object with common args for
            all the generated invoices
        """
        inv = Invoice(self.company, self.customer, self.project, self.phase,
                      user)
        inv.estimation = self

        # Common args
        inv.payment_conditions = self.payment_conditions
        inv.description = self.description
        inv.course = self.course
        inv.address = self.address
        inv.workplace = self.workplace
        inv.mentions = self.mentions
        inv.prefix = Config.get_value('invoice_prefix', '')
        return inv
def migrate_datas():
    from autonomie_base.models.base import DBSESSION
    from autonomie.models.config import Config
    session = DBSESSION()
    from alembic.context import get_bind
    conn = get_bind()

    deprecated_conf_keys = [
        'compte_cgscop',
        'compte_cg_debiteur',
        'compte_cg_organic',
        'compte_cg_debiteur_organic',
        'compte_cg_assurance',
        'taux_assurance',
        'taux_cgscop',
        'taux_contribution_organic',
        'sage_assurance',
        'sage_cgscop',
        'sage_organic',
    ]
    q = Config.query().filter(Config.name.in_(deprecated_conf_keys))
    q.delete(synchronize_session=False)
    session.flush()
Exemplo n.º 53
0
    def submit_success(self, appstruct):
        """
        Handle successfull configuration
        """
        appstruct = flatten_appstruct(appstruct)
        for key in self.keys:

            value = appstruct.pop(key, None)
            if value is None:
                continue

            cfg_obj = Config.get(key) or Config(name=key)
            cfg_obj.value = value

            self.dbsession.add(cfg_obj)

            logger.debug(u" # Setting configuration")
            logger.debug(u"{0} : {1}".format(key, value))

        self.request.session.flash(self.validation_msg)
        if self.redirect_path is not None:
            return HTTPFound(self.request.route_path(self.redirect_path))
        else:
            return HTTPFound(self.request.current_route_path())
Exemplo n.º 54
0
def test_sage_csv_writer(dbsession):
    class TestCSVWriter(SageCsvWriter):
        headers = (
            {'name': 'libelle', 'label': 'test libelle'},
        )

    def mk_test_csv_writer():
        request = Mock()
        request.config = Config
        w = TestCSVWriter(request=request, context=None)
        w.set_datas([
            {'libelle': '123456789'},
        ])
        return w

    # default (no conf)
    buf = mk_test_csv_writer().render(StringIO.StringIO())
    buf.readline()  # header
    assert buf.readline().strip() == '"123456789"'

    # zero
    Config.set('accounting_label_maxlength', '0')
    buf = mk_test_csv_writer().render(StringIO.StringIO())
    buf.readline()  # header
    assert buf.readline().strip() == '"123456789"'

    # lower than size
    Config.set('accounting_label_maxlength', '1')
    buf = mk_test_csv_writer().render(StringIO.StringIO())
    buf.readline()  # header
    assert buf.readline().strip() == '"1"'

    # bigger than size
    Config.set('accounting_label_maxlength', '11')
    buf = mk_test_csv_writer().render(StringIO.StringIO())
    buf.readline()  # header
    assert buf.readline().strip() == '"123456789"'
Exemplo n.º 55
0
def populate_invoice_number_template(session):
    from autonomie.models.config import Config
    if not Config.get_value("invoice_number_template"):
        Config.set("invoice_number_template", "{SEQGLOBAL}")
    session.flush()
def upgrade():
    from autonomie.models import DBSESSION
    from autonomie.models.workshop import WorkshopAction
    from alembic.context import get_bind

    session = DBSESSION()
    conn = get_bind()

    col = sa.Column("activity_id", sa.Integer(), sa.ForeignKey("company_activity.id"))
    op.add_column("company_datas", col)
    col = sa.Column("archived", sa.Boolean(), default=False, server_default="0")
    op.add_column("customer", col)

    # Migration de accompagnement_header.png en activity_header.png
    op.execute(
        'update config_files set config_files.key="activity_header_img.png" where \
config_files.key="accompagnement_header.png";'
    )

    # Le bas de page des pdfs est celui par defaut pour les ateliers et rdv
    from autonomie.models.config import Config

    val = Config.get("coop_pdffootertext").value
    if val:
        for key in ("activity", "workshop"):
            config_key = "%s_footer" % key
            config = Config.set(config_key, val)

    # Migration de la taille des libelles pour les actions des rendez-vous
    op.execute("alter table activity_action modify label VARCHAR(255)")
    # Migration des intitules des ateliers
    # 1- Ajout des nouvelles foreignkey
    for name in "info1_id", "info2_id", "info3_id":
        col = sa.Column(name, sa.Integer, sa.ForeignKey("workshop_action.id"))
        op.add_column("workshop", col)

    # 2- création des options en fonction des valeurs en durs
    request = "select id, info1, info2, info3 from workshop"
    result = conn.execute(request)

    already_added = {}

    for id, info1, info2, info3 in result:
        info1 = info1.lower()
        info2 = info2.lower()
        info3 = info3.lower()
        info1_id = info2_id = info3_id = None
        if (info1, info2, info3) not in already_added.keys():

            for key, value in already_added.items():
                if key[0] == info1 and info1:
                    info1_id = value[0]
                    if key[1] == info2 and info2:
                        info2_id = value[1]

            if info1_id is None and info1:
                w = WorkshopAction(label=info1)
                session.add(w)
                session.flush()
                info1_id = w.id

            if info2_id is None and info2:
                w = WorkshopAction(label=info2, parent_id=info1_id)
                session.add(w)
                session.flush()
                info2_id = w.id

            if info3:
                w = WorkshopAction(label=info3, parent_id=info2_id)
                session.add(w)
                session.flush()
                info3_id = w.id
            already_added[(info1, info2, info3)] = (info1_id, info2_id, info3_id)
        else:
            info1_id, info2_id, info3_id = already_added[(info1, info2, info3)]

        request = "update workshop "
        if info1_id:
            request += "set info1_id={0}".format(info1_id)
            if info2_id:
                request += ", info2_id={0}".format(info2_id)
                if info3_id:
                    request += ", info3_id={0}".format(info3_id)
            request += " where id={0}".format(id)
            op.execute(request)
Exemplo n.º 57
0
def invoice_base_config(dbsession):
    from autonomie.models.config import Config
    Config.set('invoice_number_template', '{SEQYEAR}')
Exemplo n.º 58
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)
Exemplo n.º 59
0
 def _get_actual_config_obj(self, config_key):
     """
     Return the actual configured compte_cg object
     """
     return Config.get(config_key)