Exemplo n.º 1
0
def userdatas_delete(userdatas, request):
    """
    delete a user account and its userdatas
    """
    if userdatas.user is not None:
        logger.debug(u"Suppression des données  et du compte de : {0}".format(
            format_account(userdatas)))
        # Suppression du compte utilisateur (la cascade va entrainer la
        # suppression des données associées)
        user_delete(userdatas.user, request)
        message = u"Les données de '{0}' ont bien été effacées".format(
            format_account(userdatas))
        request.session.flash(message)
    else:
        try:
            logger.debug(u"Suppression des données de : {0}".format(
                format_account(userdatas)))
            request.dbsession.delete(userdatas)
            request.dbsession.flush()
            message = u"Les données de '{0}' ont bien été effacées".format(
                format_account(userdatas))
            request.session.flash(message)
        except:
            logger.exception(u"Erreur à la suppression des données")
            err_msg = u"Erreur à la suppression des données de '{0}'".format(
                format_account(userdatas))
            request.session.flash(err_msg, 'error')
    return HTTPFound(request.route_path('userdatas'))
Exemplo n.º 2
0
def user_delete(account, request):
    """
        disable a user and its enteprises
    """
    try:
        # First we disable associated companies if we're going to delete the
        # only employee
        for company in account.companies:
            if len(company.employees) == 1:
                company.disable()
                message = u"L'entreprise {0} a été désactivée".format(
                    company.name
                )
                request.dbsession.merge(company)

        logger.debug(u"Deleting account : {0}".format(format_account(account)))
        request.dbsession.delete(account)
        request.dbsession.flush()
        message = u"Le compte '{0}' a bien été supprimé".format(
            format_account(account))
        request.session.flash(message)
    except:
        logger.exception(u"Erreur à la suppression du compte")
        err_msg = u"Erreur à la suppression du compte de '{0}'".format(
            format_account(account)
        )
        request.session.flash(err_msg, 'error')
    return HTTPFound(request.route_path("users"))
Exemplo n.º 3
0
def user_delete(account, request):
    """
        disable a user and its enteprises
    """
    try:
        # First we disable associated companies if we're going to delete the
        # only employee
        for company in account.companies:
            if len(company.employees) == 1:
                company.disable()
                message = u"L'entreprise {0} a été désactivée".format(
                    company.name)
                request.dbsession.merge(company)

        logger.debug(u"Deleting account : {0}".format(format_account(account)))
        request.dbsession.delete(account)
        request.dbsession.flush()
        message = u"Le compte '{0}' a bien été supprimé".format(
            format_account(account))
        request.session.flash(message)
    except:
        logger.exception(u"Erreur à la suppression du compte")
        err_msg = u"Erreur à la suppression du compte de '{0}'".format(
            format_account(account))
        request.session.flash(err_msg, 'error')
    return HTTPFound(request.route_path("users"))
Exemplo n.º 4
0
    def submit_success(self, appstruct):
        """
            Add a user to the database
            Add its companies
            Add a relationship between companies and the new account
        """
        if "companies" in appstruct:
            company_names = set(appstruct.pop('companies'))
        else:
            company_names = None

        groups = set(appstruct.pop('groups', []))
        password = appstruct.pop('pwd', None)

        if self.context.__name__ == 'user':
            user_model = self.schema.objectify(appstruct, self.context)
            logger.info(u"Edit user : {0}".format(format_account(user_model)))
        else:
            user_model = self.schema.objectify(appstruct)
            logger.info(u"Add user : {0}".format(format_account(user_model)))

        if password is not None:
            user_model.set_password(password)

        user_model.groups = groups

        self._handle_companies(company_names, user_model)

        user_model = self.dbsession.merge(user_model)

        # Here we flush to get an id for the redirect
        self.dbsession.flush()

        self.session.flash(self.validate_msg)
        return HTTPFound(self.redirect_url(user_model))
Exemplo n.º 5
0
def userdatas_delete(userdatas, request):
    """
    delete a user account and its userdatas
    """
    if userdatas.user is not None:
        logger.debug(u"Suppression des données  et du compte de : {0}".format(
            format_account(userdatas)
        ))
        # Suppression du compte utilisateur (la cascade va entrainer la
        # suppression des données associées)
        user_delete(userdatas.user, request)
        message = u"Les données de '{0}' ont bien été effacées".format(
            format_account(userdatas)
        )
        request.session.flash(message)
    else:
        try:
            logger.debug(u"Suppression des données de : {0}".format(
                format_account(userdatas)
            ))
            request.dbsession.delete(userdatas)
            request.dbsession.flush()
            message = u"Les données de '{0}' ont bien été effacées".format(
                format_account(userdatas)
            )
            request.session.flash(message)
        except:
            logger.exception(u"Erreur à la suppression des données")
            err_msg = u"Erreur à la suppression des données de '{0}'".format(
                format_account(userdatas)
            )
            request.session.flash(err_msg, 'error')
    return HTTPFound(request.route_path('userdatas'))
Exemplo n.º 6
0
def user_enable(request):
    """
        enable a user and its enterprise (if he has only one)
    """
    account = request.context
    if not account.enabled():
        try:
            account.enable()
            request.dbsession.merge(account)
            logger.info(u"The user {0} has been enabled".format(
                format_account(account)))
            message = u"L'utilisateur {0} a été (ré)activé.".format(
                format_account(account))
            request.session.flash(message)
            if len(account.companies) == 1:
                company = account.companies[0]
                company_enable(request, company=company)
        except:
            logger.exception(u"Erreur à l'activation du compte")
            err_msg = u"Erreur à l'activation du compte de '{0}'".format(
                format_account(account))
            request.session.flash(err_msg, 'error')

    url = request.referer
    if url is None:
        url = request.route_path("users")
    return HTTPFound(url)
Exemplo n.º 7
0
def user_enable(request):
    """
        enable a user and its enterprise (if he has only one)
    """
    account = request.context
    if not account.enabled():
        try:
            account.enable()
            request.dbsession.merge(account)
            logger.info(u"The user {0} has been enabled".format(
                format_account(account))
            )
            message = u"L'utilisateur {0} a été (ré)activé.".format(
                format_account(account)
            )
            request.session.flash(message)
            if len(account.companies) == 1:
                company = account.companies[0]
                company_enable(request, company=company)
        except:
            logger.exception(u"Erreur à l'activation du compte")
            err_msg = u"Erreur à l'activation du compte de '{0}'".format(
                format_account(account)
            )
            request.session.flash(err_msg, 'error')

    url = request.referer
    if url is None:
        url = request.route_path("users")
    return HTTPFound(url)
Exemplo n.º 8
0
    def submit_success(self, appstruct):
        """
            Add a user to the database
            Add its companies
            Add a relationship between companies and the new account
        """
        if "companies" in appstruct:
            company_names = set(appstruct.pop('companies'))
        else:
            company_names = None

        groups = set(appstruct.pop('groups', []))
        password = appstruct.pop('pwd', None)

        if self.context.__name__ == 'user':
            user_model = self.schema.objectify(appstruct, self.context)
            logger.info(u"Edit user : {0}" .format(format_account(user_model)))
        else:
            user_model = self.schema.objectify(appstruct)
            logger.info(u"Add user : {0}" .format(format_account(user_model)))

        if password is not None:
            user_model.set_password(password)

        user_model.groups = groups

        self._handle_companies(company_names, user_model)

        user_model = self.dbsession.merge(user_model)

        # Here we flush to get an id for the redirect
        self.dbsession.flush()

        self.session.flash(self.validate_msg)
        return HTTPFound(self.redirect_url(user_model))
Exemplo n.º 9
0
    def _build_return_value(self, schema, appstruct, query):
        writer = self._init_writer()
        participants, conseillers = self._format_datas_for_export(query)
        for name, activities in participants.items():
            writer.add_row({
                'name': name,
                'date': '',
                'title': '',
                'duration': '',
                'conseillers': ''
            })
            for activity in activities:
                writer.add_row({
                    'name':
                    '',
                    'date':
                    activity.datetime,
                    'title':
                    self._activity_title(activity),
                    'duration':
                    activity.duration,
                    'conseillers':
                    ','.join([
                        render_api.format_account(conseiller)
                        for conseiller in activity.conseillers
                    ])
                })

        sheet_writer = self._init_next_sheet(writer)
        for name, activities in conseillers.items():
            sheet_writer.add_row({
                'name': name,
                'date': '',
                'title': '',
                'duration': '',
                'participants': ''
            })
            for activity in activities:
                sheet_writer.add_row({
                    'name':
                    '',
                    'date':
                    activity.datetime,
                    'title':
                    self._activity_title(activity),
                    'duration':
                    activity.duration,
                    'participants':
                    ','.join([
                        render_api.format_account(user)
                        for user in activity.participants
                    ])
                })

        if hasattr(sheet_writer, '_populate'):
            sheet_writer._populate()

        write_file_to_request(self.request, self.filename, writer.render())
        return self.request.response
Exemplo n.º 10
0
 def _disable_user(self, user):
     """
         disable the current user
     """
     if user.enabled():
         user.disable()
         self.dbsession.merge(user)
         log.info(u"The user {0} has been disabled".format(
                                                     format_account(user)))
         message = u"L'utilisateur {0} a été désactivé.".format(
                                                     format_account(user))
         self.session.flash(message)
Exemplo n.º 11
0
 def _disable_user(self, user):
     """
         disable the current user
     """
     if user.enabled():
         user.disable()
         self.dbsession.merge(user)
         logger.info(u"The user {0} has been disabled".format(
             format_account(user)))
         message = u"L'utilisateur {0} a été désactivé.".format(
             format_account(user))
         self.session.flash(message)
Exemplo n.º 12
0
 def _format_datas_for_export(self, query):
     """
     Returns datas in order to be able to easily use them in a for loop
     """
     participants = {}
     conseillers = {}
     for activity in query:
         for participant in activity.participants:
             participants.setdefault(render_api.format_account(participant),
                                     []).append(activity)
         for conseiller in activity.conseillers:
             conseillers.setdefault(render_api.format_account(conseiller),
                                    []).append(activity)
     return participants, conseillers
Exemplo n.º 13
0
    def _build_return_value(self, schema, appstruct, query):
        writer = self._init_writer()
        participants, conseillers = self._format_datas_for_export(query)
        for name, activities in participants.items():
            writer.add_row({
                'name': name,
                'date': '',
                'title': '',
                'duration': '',
                'conseillers': ''
            })
            for activity in activities:
                writer.add_row({
                    'name': '',
                    'date': activity.datetime,
                    'title': self._activity_title(activity),
                    'duration': activity.duration,
                    'conseillers': ','.join([
                        render_api.format_account(conseiller)
                        for conseiller in activity.conseillers])
                })

        sheet_writer = self._init_next_sheet(writer)
        for name, activities in conseillers.items():
            print("Adding a row")
            sheet_writer.add_row({
                'name': name,
                'date': '',
                'title': '',
                'duration': '',
                'participants': ''
            })
            for activity in activities:
                print(u"Adding a row")
                sheet_writer.add_row({
                    'name': '',
                    'date': activity.datetime,
                    'title': self._activity_title(activity),
                    'duration': activity.duration,
                    'participants': ','.join([
                        render_api.format_account(user)
                        for user in activity.participants])
                })

        if hasattr(sheet_writer, '_populate'):
            sheet_writer._populate()

        write_file_to_request(self.request, self.filename, writer.render())
        return self.request.response
Exemplo n.º 14
0
def user_view(request):
    """
        Return user view only datas
    """
    title = u"{0}".format(format_account(request.context))
    populate_actionmenu(request, request.context)
    return dict(title=title, user=request.context)
Exemplo n.º 15
0
 def _format_datas_for_export(self, query):
     """
     Returns datas in order to be able to easily use them in a for loop
     """
     participants = {}
     conseillers = {}
     for activity in query:
         for participant in activity.participants:
             participants.setdefault(
                 render_api.format_account(participant), []
             ).append(activity)
         for conseiller in activity.conseillers:
             conseillers.setdefault(
                 render_api.format_account(conseiller), []
             ).append(activity)
     return participants, conseillers
Exemplo n.º 16
0
def stream_workshop_entries_for_export(query):
    """
    Stream workshop datas for csv export
    """
    for workshop in query.all():

        hours = sum(t.duration[0] for t in workshop.timeslots)
        minutes = sum(t.duration[1] for t in workshop.timeslots)

        duration = hours * 60 + minutes

        for participant in workshop.participants:

            attended = False
            for timeslot in workshop.timeslots:
                # On exporte une ligne que si le user était là au moins une
                # fois
                if timeslot.user_status(participant.id) == u'Présent':
                    attended = True
                    break

            if attended:
                yield {
                    "date": workshop.timeslots[0].start_time.date(),
                    "label": workshop.name,
                    "participant": format_account(participant),
                    "leaders": '\n'.join(workshop.leaders),
                    "duration": duration,
                }
Exemplo n.º 17
0
def stream_workshop_entries_for_export(query):
    for workshop in query.all():

        hours = sum(t.duration[0] for t in workshop.timeslots)
        minutes = sum(t.duration[1] for t in workshop.timeslots)

        duration = hours * 60 + minutes

        for participant in workshop.participants:

            attended = False
            for timeslot in workshop.timeslots:
                # On exporte une ligne que si le user était là au moins une
                # fois
                if timeslot.user_status(participant.id) == u'Présent':
                    attended = True
                    break

            if attended:
                yield {
                    "label": workshop.name,
                    "participant": format_account(participant),
                    "leaders": '\n'.join(workshop.leaders),
                    "duration": duration,
                }
Exemplo n.º 18
0
 def title(self):
     """
         form title
     """
     return u"Modification de {0}".format(
         format_account(self.context)
     )
Exemplo n.º 19
0
    def check(self, expenses):
        """
        Check if we can export the expenses

        :param expenses: the expenses to export
        """
        count = expenses.count()
        if count == 0:
            title = u"Il n'y a aucune note de frais à exporter"
            res = {'title': title, 'errors': [""]}
            return res

        title = u"Vous vous apprêtez à exporter {0} notes de frais".format(
            count)

        errors = []

        if not self.check_config(self.request.config):
            url1 = self.request.route_path('admin_expense')
            url2 = self.request.route_path('admin_cae')
            errors.append(EXPENSE_CONFIG_ERROR_MSG.format(url1, url2))

        for expense in expenses:
            company = expense.company
            error = self.check_company(company)
            if error is not None:
                errors.append(u"La note de frais de {0} n'est pas exportable\
<br />{1}".format(format_account(expense.user), error))

        res = {'title': title, 'errors': errors}
        return res
Exemplo n.º 20
0
 def title(self):
     return u"Notes de dépense de {0} pour la période de {1} {2}"\
         .format(
             format_account(self.request.context.user),
             month_name(self.context.month),
             self.context.year,
         )
Exemplo n.º 21
0
    def check(self, expenses) :
        """
        Check if we can export the expenses

        :param expenses: the expenses to export
        """
        count = expenses.count()
        if count == 0:
            title = u"Il n'y a aucune note de frais à exporter"
            res = {'title': title,
                    'errors': [""]}
            return res

        title = u"Vous vous apprêtez à exporter {0} notes de frais".format(
                count)

        errors = []

        if not self.check_config(self.request.config):
            url1 = self.request.route_path('admin_expense')
            url2 = self.request.route_path('admin_cae')
            errors.append(EXPENSE_CONFIG_ERROR_MSG.format(url1, url2))

        for expense in expenses:
            company = expense.company
            error = self.check_company(company)
            if error is not None:
                errors.append(u"La note de frais de {0} n'est pas exportable\
<br />{1}".format(format_account(expense.user), error))

        res = {'title': title, 'errors':errors}
        return res
Exemplo n.º 22
0
 def title(self):
     """
         Return the title of the page
     """
     return u"Notes de dépense de {0} pour la période de {1} {2}".format(
         format_account(self.request.context.user), month_name(self.month), self.year
     )
Exemplo n.º 23
0
 def title(self):
     """
         title of the form
     """
     return u"Désactivation du compte {0}".format(
         format_account(self.context)
     )
Exemplo n.º 24
0
 def title(self):
     """
     Dynamic page title
     """
     participants = self.request.context.participants
     participants_list = [render_api.format_account(account)
         for account in participants]
     return u"Accompagnement de {0}".format(", ".join(participants_list))
Exemplo n.º 25
0
 def title(self):
     """
     Dynamic page title
     """
     participants = self.request.context.participants
     participants_list = [render_api.format_account(account)
         for account in participants]
     return u"Accompagnement de {0}".format(", ".join(participants_list))
Exemplo n.º 26
0
def user_view(request):
    """
        Return user view only datas
    """
    title = u"{0}".format(format_account(request.context))
    populate_actionmenu(request, request.context)
    return dict(title=title,
                user=request.context)
Exemplo n.º 27
0
def user_delete(request):
    """
        disable a user and its enteprises
    """
    account = request.context
    try:
        log.debug(u"Deleting account : {0}".format(format_account(account)))
        request.dbsession.delete(account)
        request.dbsession.flush()
        message = u"Le compte '{0}' a bien été supprimé".format(
                                        format_account(account))
        request.session.flash(message)
    except:
        log.exception(u"Erreur à la suppression du compte")
        err_msg = u"Erreur à la suppression du compte de '{0}'".format(
                                            format_account(account))
        request.session.flash(err_msg, 'error')
    return HTTPFound(request.route_path("users"))
Exemplo n.º 28
0
 def subject(self):
     """
         return the subject of the email
     """
     subject = u"Notes de frais de {0} : {1}".format(
         format_account(self.expense.user),
         format_expense_status(self.expense),
     )
     return subject
Exemplo n.º 29
0
 def subject(self):
     """
         return the subject of the email
     """
     subject = u"Notes de dépense de {0} : {1}".format(
         format_account(self.expense.user),
         format_expense_status(self.expense),
     )
     return subject
Exemplo n.º 30
0
    def submit_success(self, appstruct):
        if self.context.__name__ == 'userdatas':
            model = self.schema.objectify(appstruct, self.context)
        else:
            from autonomie.views import render_api
            confirmation = self.request.GET.get('confirmation', '0')
            lastname = appstruct['coordonnees_lastname']
            email = appstruct['coordonnees_email1']
            if lastname and confirmation == '0':
                query = UserDatas.query().filter(
                    or_(
                        UserDatas.coordonnees_lastname == lastname,
                        UserDatas.coordonnees_email1 == email,
                    ))
                query_count = query.count()
                if query_count > 0:
                    if query_count == 1:
                        msg = u"Une entrée de gestion sociale similaire \
a déjà été créée: <ul>"

                    else:
                        msg = u"{0} entrées de gestion sociale similaires ont \
déjà été créées : <ul>".format(query_count)

                    for entry in query:
                        msg += u"<li><a href='%s'>%s (%s)</a></li>" % (
                            self.request.route_path('userdata', id=entry.id),
                            render_api.format_account(entry),
                            entry.coordonnees_email1,
                        )
                    msg += u"</ul>"
                    form = self._get_form()
                    form.action = self.request.current_route_path(
                        _query={
                            'action': 'new',
                            'confirmation': '1'
                        })
                    form.set_appstruct(appstruct)
                    datas = dict(
                        form=form.render(),
                        confirmation_message=msg,
                        confirm_form_id=form.formid,
                    )
                    datas.update(self._more_template_vars())
                    return datas

            model = self.schema.objectify(appstruct)

        model = self.dbsession.merge(model)
        self.dbsession.flush()

        self.post_integration(model)

        self.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path('userdata', id=model.id))
Exemplo n.º 31
0
    def submit_success(self, appstruct):
        if self.context.__name__ == 'userdatas':
            model = self.schema.objectify(appstruct, self.context)
        else:
            from autonomie.views import render_api
            confirmation = self.request.GET.get('confirmation', '0')
            lastname = appstruct['coordonnees_lastname']
            email = appstruct['coordonnees_email1']
            if lastname and confirmation == '0':
                query = UserDatas.query().filter(
                    or_(
                        UserDatas.coordonnees_lastname == lastname,
                        UserDatas.coordonnees_email1 == email,
                    )
                )
                query_count = query.count()
                if query_count > 0:
                    if query_count == 1:
                        msg = u"Une entrée de gestion sociale similaire \
a déjà été créée: <ul>"
                    else:
                        msg = u"{0} entrées de gestion sociale similaires ont \
déjà été créées : <ul>".format(query_count)

                    for entry in query:
                        msg += u"<li><a href='%s'>%s (%s)</a></li>" % (
                            self.request.route_path('userdata', id=entry.id),
                            render_api.format_account(entry),
                            entry.coordonnees_email1,
                        )
                    msg += u"</ul>"
                    form = self._get_form()
                    form.action = self.request.current_route_path(
                        _query={'action': 'new', 'confirmation': '1'}
                    )
                    form.set_appstruct(appstruct)
                    datas = dict(
                        form=form.render(),
                        confirmation_message=msg,
                        confirm_form_id=form.formid,
                    )
                    datas.update(self._more_template_vars())
                    return datas

            model = self.schema.objectify(appstruct)

        model = self.dbsession.merge(model)
        self.dbsession.flush()

        self.post_integration(model)

        self.session.flash(self.validation_msg)
        return HTTPFound(self.request.route_path('userdata', id=model.id))
Exemplo n.º 32
0
    def body(self):
        """
            return the body of the email
        """
        status_verb = get_status_verb(self.new_status)

        # If the document is validated, we directly send the link to the pdf
        # file
        if self.new_status == 'valid':
            query_args = dict(view="pdf")
        else:
            query_args = {}

        addr = self.request.route_url(
            self.document.type_,
            id=self.document.id,
            _query=query_args,
        )
        addr = format_link(self.settings, addr)

        docnumber = self.document.internal_number.lower()
        customer = self.document.customer.name.capitalize()
        project = self.document.project.name.capitalize()
        if self.document.is_invoice():
            docname = u"La facture"
            gender = u"e"
            determinant = u"la"
        elif self.document.is_cancelinvoice():
            docname = u"L'avoir"
            gender = u""
            determinant = u"le"
        else:
            docname = u"Le devis"
            gender = u""
            determinant = u"le"
        if self.document.statusComment:
            comment = self.document.statusComment
        else:
            comment = u"Aucun"

        username = render_api.format_account(self.document.owner,
                                             reverse=False)
        return MAIL_TMPL.format(determinant=determinant,
                                username=username,
                                docname=docname,
                                docnumber=docnumber,
                                customer=customer,
                                project=project,
                                status_verb=status_verb,
                                gender=gender,
                                addr=addr,
                                comment=comment)
Exemplo n.º 33
0
    def body(self):
        """
            return the body of the email
        """
        status_verb = get_status_verb(self.new_status)

        # If the document is validated, we directly send the link to the pdf
        # file
        if self.new_status == 'valid':
            query_args = dict(view="pdf")
        else:
            query_args = {}

        addr = self.request.route_url(
                    self.document.type_,
                    id=self.document.id,
                    _query=query_args,
                    )
        addr = format_link(self.settings, addr)

        docnumber = self.document.number.lower()
        customer = self.document.customer.name.capitalize()
        project = self.document.project.name.capitalize()
        if self.document.is_invoice():
            docname = u"La facture"
            gender = u"e"
            determinant = u"la"
        elif self.document.is_cancelinvoice():
            docname = u"L'avoir"
            gender = u""
            determinant = u"le"
        else:
            docname = u"Le devis"
            gender = u""
            determinant = u"le"
        if self.document.statusComment:
            comment = self.document.statusComment
        else:
            comment = u"Aucun"

        username = render_api.format_account(self.document.owner, reverse=False)
        return MAIL_TMPL.format(
                determinant=determinant,
                username=username,
                docname=docname,
                docnumber=docnumber,
                customer=customer,
                project=project,
                status_verb=status_verb,
                gender=gender,
                addr=addr,
                comment=comment)
Exemplo n.º 34
0
 def add_company(self, name, user):
     """
         Add a company 'name' in the database
         ( set its goal by default )
     """
     log.info(u"Adding company : %s" % name)
     company = Company()
     company.name = name
     company.goal = u"Entreprise de {0}".format(format_account(user))
     company.contribution = self.request.config.get('contribution_cae')
     company = self.dbsession.merge(company)
     self.dbsession.flush()
     return company
Exemplo n.º 35
0
 def _add_company(self, name, user):
     """
         Add a company 'name' in the database
         ( set its goal by default )
     """
     logger.info(u"Adding company : %s" % name)
     company = Company()
     company.name = name
     company.goal = u"Entreprise de {0}".format(
         format_account(user, reverse=False))
     company.contribution = self.request.config.get('contribution_cae')
     company = self.dbsession.merge(company)
     self.dbsession.flush()
     return company
Exemplo n.º 36
0
def get_users_options(roles=None):
    """
    Return the list of active users from the database formatted as choices:
        [(user_id, user_label)...]

    :param role: roles of the users we want
        default:  all
        values : ('contractor', 'manager', 'admin'))
    """
    if roles and not hasattr(roles, "__iter__"):
        roles = [roles]
    if roles:
        query = get_user_by_roles(roles)
    else:
        query = User.query()
    return [(unicode(u.id), render_api.format_account(u)) for u in query]
Exemplo n.º 37
0
 def submit_success(self, appstruct):
     """
         Edit the database entry for the current user
     """
     user = self.get_user(self.request.context, appstruct)
     if 'companies' in appstruct:
         companies = set(appstruct.get('companies'))
         user.companies = []
         for company_name in companies:
             company = self.get_company(company_name, user)
             user.companies.append(company)
     log.info(u"Edit user : {0}" .format(format_account(user)))
     user = self.dbsession.merge(user)
     self.dbsession.flush()
     self.session.flash(self.validate_msg)
     return HTTPFound(self.request.route_path("user", id=user.id))
Exemplo n.º 38
0
    def body(self):
        """
            return the body of the email
        """
        owner = format_account(self.expense.user)
        date = u"{0}/{1}".format(self.expense.month, self.expense.year)
        status_verb = get_status_verb(self.new_status)
        addr = self.request.route_url("expensesheet", id=self.expense.id)
        addr = format_link(self.settings, addr)

        return MAIL_TMPL.format(
            owner=owner,
            addr=addr,
            date=date,
            status_verb=status_verb,
            comment=self.comment,
        )
Exemplo n.º 39
0
    def body(self):
        """
            return the body of the email
        """
        owner = format_account(self.expense.user)
        date = u"{0}/{1}".format(self.expense.month, self.expense.year)
        status_verb = get_status_verb(self.new_status)
        addr = self.request.route_url("expensesheet", id=self.expense.id)
        addr = format_link(self.settings, addr)

        return MAIL_TMPL.format(
            owner=owner,
            addr=addr,
            date=date,
            status_verb=status_verb,
            comment=self.comment,
        )
Exemplo n.º 40
0
def _get_appstruct_from_activity(activity):
    """
    Return an activity as a form appstruct
    """
    appstruct = activity.appstruct()
    participants = activity.participants
    conseillers = activity.conseillers

    appstruct['participants'] = [p.id for p in participants]
    appstruct['conseillers'] = [c.id for c in conseillers]
    appstruct['attendances'] = [
        {
        'event_id': att.event_id,
        'account_id': att.account_id,
        'username': render_api.format_account(att.user),
        'status': att.status,
        } for att in activity.attendances]
    return appstruct
Exemplo n.º 41
0
 def submit_success(self, appstruct):
     """
         Add a user to the database
         Add its companies
         Add a relationship between companies and the new account
     """
     user = self.get_user(User(), appstruct)
     if 'companies' in appstruct:
         companies = set(appstruct.get('companies'))
         user.companies = []
         for company_name in companies:
             company = self.get_company(company_name, user)
             user.companies.append(company)
     log.info(u"Add user : {0}" .format(format_account(user)))
     user = self.dbsession.merge(user)
     self.dbsession.flush()
     self.session.flash(self.validate_msg)
     return HTTPFound(self.request.route_path("user", id=user.id))
Exemplo n.º 42
0
def _get_appstruct_from_activity(activity):
    """
    Return an activity as a form appstruct
    """
    appstruct = activity.appstruct()
    participants = activity.participants
    conseillers = activity.conseillers
    companies = activity.companies

    appstruct['participants'] = [p.id for p in participants]
    appstruct['conseillers'] = [c.id for c in conseillers]
    appstruct['companies'] = [c.id for c in companies]
    appstruct['attendances'] = [{
        'event_id': att.event_id,
        'account_id': att.account_id,
        'username': render_api.format_account(att.user),
        'status': att.status,
    } for att in activity.attendances]
    return appstruct
Exemplo n.º 43
0
def company_remove_employee_view(context, request):
    """
    Enlève un employé de l'entreprise courante
    """
    uid = request.params.get("uid")
    if not uid:
        request.session.flash("Missing uid parameter", "error")
    user = User.get(uid)
    if not user:
        request.session.flash("User not found", "error")

    if user in context.employees:
        context.employees = [employee for employee in context.employees if employee != user]
        request.session.flash(
            u"L'utilisateur {0} ne fait plus partie de l'entreprise {1}".format(format_account(user), context.name)
        )
    url = request.referer
    if url is None:
        url = request.route_path("company", id=context.id)
    return HTTPFound(url)
Exemplo n.º 44
0
def company_remove_employee_view(context, request):
    """
    Enlève un employé de l'entreprise courante
    """
    uid = request.params.get('uid')
    if not uid:
        request.session.flash('Missing uid parameter', 'error')
    user = User.get(uid)
    if not user:
        request.session.flash('User not found', 'error')

    if user in context.employees:
        context.employees = [
            employee for employee in context.employees if employee != user
        ]
        request.session.flash(
            u"L'utilisateur {0} ne fait plus partie de l'entreprise {1}".
            format(format_account(user), context.name))
    url = request.referer
    if url is None:
        url = request.route_path('company', id=context.id)
    return HTTPFound(url)
Exemplo n.º 45
0
    def _confirmation_form(self, query, appstruct, query_count):
        """
        Return datas used to display a confirmation form

        :param obj query: homonym SQLAlchemy query object
        :param dict appstruct: Preserved form datas
        :param int query_count: The number of homonyms
        :returns: template vars
        :rtype: dict
        """
        if query_count == 1:
            msg = u"Une entrée de gestion sociale similaire \
a déjà été créée: <ul>"

        else:
            msg = u"{0} entrées de gestion sociale similaires ont \
déjà été créées : <ul>".format(query_count)

        for entry in query:
            msg += u"<li><a href='%s'>%s (%s)</a></li>" % (
                self.request.route_path('userdata', id=entry.id),
                format_account(entry),
                entry.coordonnees_email1,
            )
        msg += u"</ul>"
        form = self._get_form()
        form.action = self.request.current_route_path(_query={
            'action': 'new',
            'confirmation': '1'
        })
        form.set_appstruct(appstruct)
        datas = dict(
            form=form.render(),
            confirmation_message=msg,
            confirm_form_id=form.formid,
        )
        datas.update(self._more_template_vars())
        return datas
Exemplo n.º 46
0
    def check(self, payments):
        """
        Check that the given expense_payments can be exported

        :param obj payments: A SQLA query of ExpensePayment objects
        """
        count = payments.count()
        if count == 0:
            title = u"Il n'y a aucun paiement à exporter"
            res = {
                'title': title,
                'errors': [''],
            }
            return res

        title = u"Vous vous apprêtez à exporter {0} paiements".format(count)
        res = {'title': title, 'errors': []}

        for payment in payments:
            expense = payment.expense
            company = expense.company
            if not self.check_company(company):
                company_url = self.request.route_path(
                    "company",
                    id=company.id,
                    _query={'action': 'edit'},
                )
                message = ERR_COMPANY_CONFIG.format(
                    expense.id,
                    company.name,
                    company_url,
                )
                res['errors'].append(message)
                continue

            user = expense.user
            if not self.check_user(user):
                user_url = self.request.route_path(
                    "user",
                    id=user.id,
                    _query={'action': 'edit'},
                )
                message = ERR_USER_CONFIG.format(
                    expense.id,
                    format_account(user),
                    user_url,
                )
                res['errors'].append(message)
                continue

            if not self.check_bank(payment):
                payment_url = self.request.route_path(
                    'expensepayment', id=payment.id, _query={'action': 'edit'})
                message = ERR_BANK_CONFIG.format(expense.id, payment_url)
                res['errors'].append(message)
                continue

            if payment.waiver and not self.check_waiver(payment):
                admin_url = self.request.route_path('admin_expense_treasury')
                message = ERR_WAIVER_CONFIG.format(admin_url)
                res['errors'].append(message)
                continue

        return res
Exemplo n.º 47
0
 def libelle(self):
     return u"{0}/frais {1} {2}".format(
         render_api.format_account(self.expense.user, reverse=False),
         self.expense.month,
         self.expense.year
     )
Exemplo n.º 48
0
 def title(self):
     """
         title of the form
     """
     return u"Désactivation du compte {0}".format(
         format_account(self.context))
Exemplo n.º 49
0
 def libelle(self):
     return u"{0}/frais {1} {2}".format(
         render_api.format_account(self.expense.user, reverse=False),
         self.expense.month, self.expense.year)
Exemplo n.º 50
0
 def title(self):
     """
         form title
     """
     return u"Modification de {0}".format(format_account(self.context))
Exemplo n.º 51
0
 def title(self):
     return u"Gestion sociale : {0}".format(
         format_account(self.request.context))
Exemplo n.º 52
0
 def title(self):
     return u"Gestion sociale : {0}".format(
         format_account(self.request.context)
     )
Exemplo n.º 53
0
    def check(self, payments):
        """
        Check that the given expense_payments can be exported

        :param obj payments: A SQLA query of ExpensePayment objects
        """
        count = payments.count()
        if count == 0:
            title = u"Il n'y a aucun paiement à exporter"
            res = {
                'title': title,
                'errors': [''],
            }
            return res

        title = u"Vous vous apprêtez à exporter {0} paiements".format(
                count)
        res = {'title': title, 'errors': []}

        for payment in payments:
            expense = payment.expense
            company = expense.company
            if not self.check_company(company):
                company_url = self.request.route_path(
                    "company",
                    id=company.id,
                    _query={'action': 'edit'},
                )
                message = ERR_COMPANY_CONFIG.format(
                    expense.id,
                    company.name,
                    company_url,
                )
                res['errors'].append(message)
                continue

            user = expense.user
            if not self.check_user(user):
                user_url = self.request.route_path(
                    "user",
                    id=user.id,
                    _query={'action': 'edit'},
                )
                message = ERR_USER_CONFIG.format(
                    expense.id,
                    format_account(user),
                    user_url,
                )
                res['errors'].append(message)
                continue

            if not self.check_bank(payment):
                payment_url = self.request.route_path(
                    'expensepayment',
                    id=payment.id,
                    _query={'action': 'edit'}
                )
                message = ERR_BANK_CONFIG.format(
                    expense.id,
                    payment_url)
                res['errors'].append(message)
                continue

            if payment.waiver and not self.check_waiver(payment):
                admin_url = self.request.route_path(
                    'admin_expense_treasury'
                )
                message = ERR_WAIVER_CONFIG.format(admin_url)
                res['errors'].append(message)
                continue

        return res
Exemplo n.º 54
0
 def title(self):
     """
         form title
     """
     return u"Édition de {0}".format(
                                     format_account(self.request.context))