Пример #1
0
def populate(engine):

    session = DBSession()

    cp = VacationType.by_id(session, 1)
    rtt = VacationType.by_id(session, 2)
    parent = VacationType.by_id(session, 3)

    fr_country = Countries.by_name(session, u'fr')
    session.add(fr_country)
    lu_country = Countries.by_name(session, u'lu')
    session.add(lu_country)
    us_country = Countries.by_name(session, u'us')
    session.add(us_country)
    zh_country = Countries.by_name(session, u'zh')
    session.add(zh_country)

    # CP is available for everyone
    cp.countries.append(fr_country)
    cp.countries.append(lu_country)
    cp.countries.append(us_country)
    cp.countries.append(zh_country)

    # RTT only available for france
    rtt.countries.append(fr_country)

    # parent is available for everyone
    parent.countries.append(fr_country)
    parent.countries.append(lu_country)
    parent.countries.append(us_country)
    parent.countries.append(zh_country)

    session.commit()
Пример #2
0
    def test_by_name_country_rtt_ok(self):
        from pyvac.models import User, VacationType

        jdoe = User.by_login(self.session, u"jdoe")
        with freeze_time("2014-12-25", ignore=["celery", "psycopg2", "sqlalchemy", "icalendar"]):
            vac = VacationType.by_name_country(self.session, u"RTT", jdoe.country)
            self.assertEqual(vac, 10)
Пример #3
0
 def test_by_country_ok(self):
     from pyvac.models import User, VacationType
     manager3 = User.by_login(self.session, u'manager3')
     vac_types = VacationType.by_country(self.session, manager3.country)
     self.assertEqual(len(vac_types), 5)
     # take the first
     vac_type = vac_types.pop()
     self.assertIsInstance(vac_type, VacationType)
Пример #4
0
 def test_by_country_ok(self):
     from pyvac.models import User, VacationType
     manager3 = User.by_login(self.session, u'manager3')
     vac_types = VacationType.by_country(self.session, manager3.country)
     self.assertEqual(len(vac_types), 5)
     # take the first
     vac_type = vac_types.pop()
     self.assertIsInstance(vac_type, VacationType)
Пример #5
0
    def update_view(self, model, view):
        view['countries'] = Countries.all(self.session,
                                          order_by=Countries.name)
        view['vacation_types'] = VacationType.all(self.session,
                                                  order_by=VacationType.id)

        if view['errors']:
            self.request.session.flash('error;%s' % ','.join(view['errors']))
Пример #6
0
 def test_by_name_country_rtt_ok(self):
     from pyvac.models import User, VacationType
     jdoe = User.by_login(self.session, u'jdoe')
     with freeze_time('2014-12-25',
                      ignore=['celery', 'psycopg2', 'sqlalchemy',
                              'icalendar']):
         vac = VacationType.by_name_country(self.session, u'RTT',
                                            jdoe.country)
         self.assertEqual(vac, 10)
Пример #7
0
 def test_by_name_country_rtt_ok(self):
     from pyvac.models import User, VacationType
     jdoe = User.by_login(self.session, u'jdoe')
     with freeze_time('2014-12-25',
                      ignore=['celery', 'psycopg2', 'sqlalchemy',
                              'icalendar']):
         kwargs = {'session': self.session,
                   'name': u'RTT', 'country': jdoe.country}
         vac = VacationType.by_name_country(**kwargs)
         self.assertEqual(vac.acquired(**kwargs), 10)
Пример #8
0
    def render(self):
        if not self.user:
            return self.redirect()

        _ = self.request.translate

        self.user.rtt = self.user.get_rtt_usage(self.session)

        holidays = get_holiday(self.user)

        ret_dict = {'types': [], 'holidays': holidays, 'sudo_users': [],
                    'futures_pending': [], 'futures_approved': []}

        vacation_types = VacationType.by_country(self.session,
                                                 self.user.country)
        for vac in vacation_types:
            if vac.visibility and self.user.role not in vac.visibility:
                continue
            ret_dict['types'].append({'name': _(vac.name), 'id': vac.id})

        if self.user.is_admin:
            ret_dict['sudo_users'] = User.for_admin(self.session, self.user)

        futures_pending = [timestamp
                           for req in
                           Request.by_user_future_pending(self.session,
                                                          self.user)
                           for timestamp in req.timestamps]
        ret_dict['futures_pending'] = futures_pending
        futures_approved = [timestamp
                            for req in
                            Request.by_user_future_approved(self.session,
                                                            self.user)
                            for timestamp in req.timestamps]
        ret_dict['futures_approved'] = futures_approved

        exception_info_tooltip = """\
This type is for events which are not covered by other types: \
wedding, funeral, etc.

Providing a reason for this request is mandatory.
"""
        ret_dict['exception_info_tooltip'] = _(exception_info_tooltip)

        if self.request.matched_route:
            matched_route = self.request.matched_route.name
            ret_dict.update({
                'matched_route': matched_route,
                'csrf_token': self.request.session.get_csrf_token()})
            return ret_dict

        ret_dict.update({'csrf_token': self.request.session.get_csrf_token()})
        return ret_dict
Пример #9
0
def populate(engine):

    session = DBSession()

    cp = VacationType.by_id(session, 1)
    rtt = VacationType.by_id(session, 2)
    parent = VacationType.by_id(session, 3)
    recovery = VacationType.by_id(session, 4)

    fr_country = Countries.by_name(session, 'fr')
    session.add(fr_country)
    lu_country = Countries.by_name(session, 'lu')
    session.add(lu_country)
    us_country = Countries.by_name(session, 'us')
    session.add(us_country)
    zh_country = Countries.by_name(session, 'zh')
    session.add(zh_country)

    # CP is available for everyone
    cp.countries.append(fr_country)
    cp.countries.append(lu_country)
    cp.countries.append(us_country)
    cp.countries.append(zh_country)

    # RTT only available for france
    rtt.countries.append(fr_country)

    # parent is available for everyone
    parent.countries.append(fr_country)
    parent.countries.append(lu_country)
    parent.countries.append(us_country)
    parent.countries.append(zh_country)

    # recovery is available for everyone
    recovery.countries.append(fr_country)
    recovery.countries.append(lu_country)
    recovery.countries.append(us_country)
    recovery.countries.append(zh_country)

    session.commit()
Пример #10
0
    def render(self):
        try:
            form_date_from = self.request.params.get('date_from')
            if ' - ' not in form_date_from:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            dates = self.request.params.get('date_from').split(' - ')
            date_from = datetime.strptime(dates[0], '%d/%m/%Y')
            date_to = datetime.strptime(dates[1], '%d/%m/%Y')
            days = int(self.request.params.get('days'))

            vac_type = VacationType.by_name(self.session,
                                            self.request.params.get('type'))

            if days <= 0:
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            request = Request(date_from=date_from,
                              date_to=date_to,
                              days=days,
                              vacation_type=vac_type,
                              status=u'PENDING',
                              user=self.user,
                              notified=False,
                              )
            self.session.add(request)
            self.session.flush()

            if request:
                msg = 'Request sent to your manager.'
                self.request.session.flash('info;%s' % msg)
                # call celery task directly, do not wait for polling
                from celery.registry import tasks
                from celery.task import subtask
                req_task = tasks['worker_pending']
                data = {'req_id': request.id}
                subtask(req_task).delay(data=data)

        except Exception as exc:
            log.error(exc)
            msg = ('An error has occured while processing this request: %r'
                   % exc)
            self.request.session.flash('error;%s' % msg)

        return HTTPFound(location=route_url('home', self.request))
Пример #11
0
    def render(self):
        if not self.user:
            return self.redirect()

        ret_dict = {'types': [vac.name for vac in
                              VacationType.find(self.session,
                                                order_by=[VacationType.name])]}
        if self.request.matched_route:
            matched_route = self.request.matched_route.name
            ret_dict.update({'matched_route': matched_route,
                             'csrf_token': self.request.session.get_csrf_token()})
            return ret_dict

        ret_dict.update({'csrf_token': self.request.session.get_csrf_token()})
        return ret_dict
Пример #12
0
def populate(engine):
    Base.metadata.create_all(engine)
    session = DBSession()

    vactype = VacationType(name='Télétravail')
    session.add(vactype)

    fr_country = Countries.by_name(session, name='fr')
    lu_country = Countries.by_name(session, name='lu')
    us_country = Countries.by_name(session, name='us')
    zh_country = Countries.by_name(session, name='zh')

    # Remote is available for everyone
    vactype.countries.append(fr_country)
    vactype.countries.append(lu_country)
    vactype.countries.append(us_country)
    vactype.countries.append(zh_country)

    session.commit()
Пример #13
0
    def render(self):
        if not self.user:
            return self.redirect()

        _ = self.request.translate

        self.user.rtt = self.user.get_rtt_usage(self.session)

        ret_dict = {"types": [], "holidays": [], "sudo_users": []}

        vacation_types = VacationType.by_country(self.session, self.user.country)
        for vac in vacation_types:
            ret_dict["types"].append({"name": _(vac.name), "id": vac.id})

        if self.user.is_admin:
            ret_dict["sudo_users"] = User.for_admin(self.session, self.user)

        if self.request.matched_route:
            matched_route = self.request.matched_route.name
            ret_dict.update({"matched_route": matched_route, "csrf_token": self.request.session.get_csrf_token()})
            return ret_dict

        ret_dict.update({"csrf_token": self.request.session.get_csrf_token()})
        return ret_dict
Пример #14
0
def populate(engine):

    Base.metadata.create_all(engine)
    session = DBSession()

    user_perm = Permission(name=u'user_view')
    admin_perm = Permission(name=u'admin_view')
    manager_perm = Permission(name=u'manager_view')
    sudo_perm = Permission(name=u'sudo_view')
    session.add(user_perm)
    session.add(admin_perm)
    session.add(manager_perm)
    session.add(sudo_perm)

    admin_group = Group(name=u'admin')
    admin_group.permissions.append(user_perm)
    admin_group.permissions.append(admin_perm)
    admin_group.permissions.append(manager_perm)
    admin_group.permissions.append(sudo_perm)
    session.add(admin_group)

    manager_group = Group(name=u'manager')
    manager_group.permissions.append(user_perm)
    manager_group.permissions.append(manager_perm)
    manager_group.permissions.append(sudo_perm)
    session.add(manager_group)

    user_group = Group(name=u'user')
    user_group.permissions.append(user_perm)
    session.add(user_group)

    sudoer_group = Group(name=u'sudoer')
    sudoer_group.permissions.append(sudo_perm)
    session.add(sudoer_group)

    vactype1 = VacationType(name=u'CP')
    session.add(vactype1)
    vactype2 = VacationType(name=u'RTT')
    session.add(vactype2)
    vactype3 = VacationType(name=u'Congé Parental')
    session.add(vactype3)
    vactype4 = VacationType(name=u'Récupération')
    session.add(vactype4)
    vactype5 = VacationType(name=u'Maladie', visibility=u'admin')
    session.add(vactype5)
    vactype6 = VacationType(name=u'Exceptionnel')
    session.add(vactype6)
    vactype7 = VacationType(name=u'Compensatoire')
    session.add(vactype7)

    fr_country = Countries(name=u'fr')
    session.add(fr_country)
    lu_country = Countries(name=u'lu')
    session.add(lu_country)
    us_country = Countries(name=u'us')
    session.add(us_country)
    zh_country = Countries(name=u'zh')
    session.add(zh_country)

    # CP is available for everyone
    vactype1.countries.append(fr_country)
    vactype1.countries.append(lu_country)
    vactype1.countries.append(us_country)
    vactype1.countries.append(zh_country)

    # RTT only available for france
    vactype2.countries.append(fr_country)

    # Parental vacation is available for everyone
    vactype3.countries.append(fr_country)
    vactype3.countries.append(lu_country)
    vactype3.countries.append(us_country)
    vactype3.countries.append(zh_country)

    # Recovery is available for everyone
    vactype4.countries.append(fr_country)
    vactype4.countries.append(lu_country)
    vactype4.countries.append(us_country)
    vactype4.countries.append(zh_country)

    # Sickness vacation is available for all countries
    vactype5.countries.append(fr_country)
    vactype5.countries.append(lu_country)
    vactype5.countries.append(us_country)
    vactype5.countries.append(zh_country)

    # Exception vacation is available for all countries
    vactype6.countries.append(fr_country)
    vactype6.countries.append(lu_country)
    vactype6.countries.append(us_country)
    vactype6.countries.append(zh_country)

    # Holiday recovery is only available for LU
    vactype7.countries.append(lu_country)

    common_password = u'changeme'

    admin = User(login=u'admin',
                 password=common_password,
                 email=u'*****@*****.**',
                 firstname=u'The',
                 lastname=u'Administrator',
                 role=u'admin',
                 _country=fr_country)
    admin.groups.append(admin_group)
    session.add(admin)

    session.commit()
Пример #15
0
def setUpModule():

    engine = create_engine(settings)
    populate(engine)

    session = DBSession()
    user_group = Group.by_name(session, u'user')
    manager_group = Group.by_name(session, u'manager')
    common_password = u'changeme'

    cp_vacation = VacationType.by_name(session, u'CP')
    rtt_vacation = VacationType.by_name(session, u'RTT')

    fr_country = Countries.by_name(session, u'fr')
    us_country = Countries.by_name(session, u'us')

    manager1 = User(login=u'manager1',
                    password=common_password,
                    email=u'*****@*****.**',
                    firstname=u'First',
                    lastname=u'Manager',
                    role=u'manager',
                    _country=fr_country,
                    )
    manager1.groups.append(manager_group)
    session.add(manager1)

    manager2 = User(login=u'manager2',
                    password=common_password,
                    email=u'*****@*****.**',
                    firstname=u'Second',
                    lastname=u'Manager',
                    role=u'manager',
                    _country=fr_country,
                    )
    manager2.groups.append(manager_group)
    session.add(manager2)

    manager_us = User(login=u'manager3',
                      password=common_password,
                      email=u'*****@*****.**',
                      firstname=u'Third',
                      lastname=u'Manager',
                      role=u'manager',
                      _country=us_country,
                      )
    manager_us.groups.append(manager_group)
    session.add(manager_us)

    user1 = User(login=u'jdoe',
                 password=common_password,
                 email=u'*****@*****.**',
                 manager=manager1,
                 firstname=u'John',
                 lastname=u'Doe',
                 _country=fr_country,
                 )
    user1.groups.append(user_group)
    session.add(user1)

    user2 = User(login=u'janedoe',
                 password=common_password,
                 email=u'*****@*****.**',
                 manager=manager2,
                 firstname=u'Jane',
                 lastname=u'Doe',
                 _country=fr_country,
                 )
    user2.groups.append(user_group)
    session.add(user2)

    date_from = datetime.strptime('10/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('14/04/2015', '%d/%m/%Y')
    req1 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=cp_vacation,
                   status=u'PENDING',
                   user=user1,
                   notified=False)
    session.add(req1)

    date_from = datetime.strptime('10/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('21/04/2015', '%d/%m/%Y')
    req2 = Request(date_from=date_from,
                   date_to=date_to,
                   days=10,
                   vacation_type=cp_vacation,
                   status=u'PENDING',
                   user=user2,
                   notified=False,)
    session.add(req2)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req3 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=rtt_vacation,
                   status=u'ACCEPTED_MANAGER',
                   user=user1,
                   notified=True,)
    session.add(req3)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req4 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=rtt_vacation,
                   status=u'CANCELED',
                   user=user1,
                   notified=True,)
    session.add(req4)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req5 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=rtt_vacation,
                   status=u'APPROVED_ADMIN',
                   user=manager_us,
                   notified=True,)
    session.add(req5)

    date_from = datetime.strptime('24/08/2011', '%d/%m/%Y')
    date_to = datetime.strptime('24/08/2011', '%d/%m/%Y')
    req6 = Request(date_from=date_from,
                   date_to=date_to,
                   days=0.5,
                   vacation_type=rtt_vacation,
                   status=u'APPROVED_ADMIN',
                   user=user1,
                   notified=True,
                   label=u'AM')
    session.add(req6)

    date_from = datetime.strptime('14/07/2014', '%d/%m/%Y')
    date_to = datetime.strptime('14/07/2014', '%d/%m/%Y')
    req7 = Request(date_from=date_from,
                   date_to=date_to,
                   days=0.5,
                   vacation_type=rtt_vacation,
                   status=u'APPROVED_ADMIN',
                   user=user1,
                   notified=True,
                   label=u'AM')
    session.add(req7)

    # used for rtt vacation checks

    date_from = datetime.strptime('01/04/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/04/2016', '%d/%m/%Y')
    req8 = Request(date_from=date_from,
                   date_to=date_to,
                   days=1,
                   vacation_type=rtt_vacation,
                   status=u'PENDING',
                   user=user1,
                   notified=True)
    session.add(req8)

    date_from = datetime.strptime('01/03/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/03/2016', '%d/%m/%Y')
    req9 = Request(date_from=date_from,
                   date_to=date_to,
                   days=1,
                   vacation_type=rtt_vacation,
                   status=u'ACCEPTED_MANAGER',
                   user=user1,
                   notified=True)
    session.add(req9)

    date_from = datetime.strptime('01/02/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/02/2016', '%d/%m/%Y')
    req10 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=rtt_vacation,
                    status=u'APPROVED_ADMIN',
                    user=user1,
                    notified=True)
    session.add(req10)

    session.commit()
Пример #16
0
    def render(self):
        try:
            form_date_from = self.request.params.get('date_from')
            if ' - ' not in form_date_from:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            dates = self.request.params.get('date_from').split(' - ')
            date_from = datetime.strptime(dates[0], '%d/%m/%Y')
            date_to = datetime.strptime(dates[1], '%d/%m/%Y')

            days = float(len([d for d in daterange(date_from, date_to)
                              if d.isoweekday() not in [6, 7]]))

            days_diff = (date_to - date_from).days
            if days_diff < 0:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if (date_to == date_from) and days > 1:
                # same day, asking only for one or less day duration
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if days <= 0:
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            vac_type = VacationType.by_name(self.session,
                                            self.request.params.get('type'))

            # label field is used when requesting half day
            label = u''
            breakdown = self.request.params.get('breakdown')
            if breakdown != 'FULL':
                # handle half day
                if (days > 1):
                    msg = 'AM/PM option must be used only when requesting a single day.'
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                else:
                    days = 0.5
                    label = unicode(breakdown)

            request = Request(date_from=date_from,
                              date_to=date_to,
                              days=days,
                              vacation_type=vac_type,
                              status=u'PENDING',
                              user=self.user,
                              notified=False,
                              label=label,
                              )
            self.session.add(request)
            self.session.flush()

            if request:
                msg = 'Request sent to your manager.'
                self.request.session.flash('info;%s' % msg)
                # call celery task directly, do not wait for polling
                from celery.registry import tasks
                from celery.task import subtask
                req_task = tasks['worker_pending']
                data = {'req_id': request.id}
                subtask(req_task).delay(data=data)

        except Exception as exc:
            log.error(exc)
            msg = ('An error has occured while processing this request: %r'
                   % exc)
            self.request.session.flash('error;%s' % msg)

        return HTTPFound(location=route_url('home', self.request))
Пример #17
0
 def test_by_name_country_no_rtt_ko(self):
     from pyvac.models import User, VacationType
     manager3 = User.by_login(self.session, u'manager3')
     vac = VacationType.by_name_country(self.session, u'RTT',
                                        manager3.country)
     self.assertIsNone(vac)
Пример #18
0
 def test_visibility_ok(self):
     from pyvac.models import VacationType
     vac_type = VacationType.by_id(self.session, 5)
     self.assertEqual(vac_type.visibility, 'admin')
     vac_type = VacationType.by_id(self.session, 1)
     self.assertEqual(vac_type.visibility, None)
Пример #19
0
 def test_by_name_country_no_rtt_ko(self):
     from pyvac.models import User, VacationType
     manager3 = User.by_login(self.session, u'manager3')
     vac = VacationType.by_name_country(self.session, u'RTT',
                                        manager3.country)
     self.assertIsNone(vac)
Пример #20
0
 def test_visibility_ok(self):
     from pyvac.models import VacationType
     vac_type = VacationType.by_id(self.session, 5)
     self.assertEqual(vac_type.visibility, 'admin')
     vac_type = VacationType.by_id(self.session, 1)
     self.assertEqual(vac_type.visibility, None)
Пример #21
0
def setUpModule():

    engine = create_engine(settings)
    populate(engine)

    session = DBSession()
    user_group = Group.by_name(session, 'user')
    manager_group = Group.by_name(session, 'manager')
    sudoer_group = Group.by_name(session, 'sudoer')
    common_password = '******'

    cp_vacation = VacationType.by_name(session, 'CP')
    rtt_vacation = VacationType.by_name(session, 'RTT')
    recovery_vacation = VacationType.by_name(session, 'Récupération')
    sickness_vacation = VacationType.by_name(session, 'Maladie')
    exception_vacation = VacationType.by_name(session, 'Exceptionnel')

    fr_country = Countries.by_name(session, 'fr')
    us_country = Countries.by_name(session, 'us')
    lu_country = Countries.by_name(session, 'lu')

    manager1 = User(
        login='******',
        password=common_password,
        email='*****@*****.**',
        firstname='First',
        lastname='Manager',
        role='manager',
        _country=fr_country,
    )
    manager1.groups.append(manager_group)
    session.add(manager1)

    manager2 = User(
        login='******',
        password=common_password,
        email='*****@*****.**',
        firstname='Second',
        lastname='Manager',
        role='manager',
        _country=fr_country,
    )
    manager2.groups.append(manager_group)
    session.add(manager2)

    manager_us = User(
        login='******',
        password=common_password,
        email='*****@*****.**',
        firstname='Third',
        lastname='Manager',
        role='manager',
        _country=us_country,
    )
    manager_us.groups.append(manager_group)
    session.add(manager_us)

    user1 = User(
        login='******',
        password=common_password,
        email='*****@*****.**',
        manager=manager1,
        firstname='John',
        lastname='Doe',
        _country=fr_country,
        registration_number=1337,
    )
    user1.groups.append(user_group)
    session.add(user1)

    user2 = User(
        login='******',
        password=common_password,
        email='*****@*****.**',
        manager=manager2,
        firstname='Jane',
        lastname='Doe',
        _country=fr_country,
    )
    user2.groups.append(user_group)
    user2.groups.append(sudoer_group)
    session.add(user2)

    session.flush()
    sudoer = Sudoer(source_id=user2.id, target_id=1)
    session.add(sudoer)

    user3 = User(
        login='******',
        password=common_password,
        email='*****@*****.**',
        manager=manager1,
        firstname='Sarah',
        lastname='Doe',
        _country=lu_country,
    )
    user3.groups.append(user_group)
    session.add(user3)

    date_from = datetime.strptime('10/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('14/04/2015', '%d/%m/%Y')
    req1 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=cp_vacation,
                   status='PENDING',
                   user=user1,
                   notified=False)
    session.add(req1)

    date_from = datetime.strptime('10/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('21/04/2015', '%d/%m/%Y')
    req2 = Request(
        date_from=date_from,
        date_to=date_to,
        days=10,
        vacation_type=cp_vacation,
        status='PENDING',
        user=user2,
        notified=False,
    )
    session.add(req2)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req3 = Request(
        date_from=date_from,
        date_to=date_to,
        days=5,
        vacation_type=rtt_vacation,
        status='ACCEPTED_MANAGER',
        user=user1,
        notified=True,
    )
    session.add(req3)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req4 = Request(
        date_from=date_from,
        date_to=date_to,
        days=5,
        vacation_type=rtt_vacation,
        status='CANCELED',
        user=user1,
        notified=True,
    )
    session.add(req4)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req5 = Request(
        date_from=date_from,
        date_to=date_to,
        days=5,
        vacation_type=rtt_vacation,
        status='APPROVED_ADMIN',
        user=manager_us,
        notified=True,
    )
    session.add(req5)

    date_from = datetime.strptime('24/08/2011', '%d/%m/%Y')
    date_to = datetime.strptime('24/08/2011', '%d/%m/%Y')
    req6 = Request(date_from=date_from,
                   date_to=date_to,
                   days=0.5,
                   vacation_type=rtt_vacation,
                   status='APPROVED_ADMIN',
                   user=user1,
                   notified=True,
                   label='AM')
    session.add(req6)

    date_from = datetime.strptime('14/07/2014', '%d/%m/%Y')
    date_to = datetime.strptime('14/07/2014', '%d/%m/%Y')
    req7 = Request(date_from=date_from,
                   date_to=date_to,
                   days=0.5,
                   vacation_type=rtt_vacation,
                   status='APPROVED_ADMIN',
                   user=user1,
                   notified=True,
                   label='AM')
    session.add(req7)

    # used for rtt vacation checks

    date_from = datetime.strptime('01/04/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/04/2016', '%d/%m/%Y')
    req8 = Request(date_from=date_from,
                   date_to=date_to,
                   days=1,
                   vacation_type=rtt_vacation,
                   status='PENDING',
                   user=user1,
                   notified=True)
    session.add(req8)

    date_from = datetime.strptime('01/03/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/03/2016', '%d/%m/%Y')
    req9 = Request(date_from=date_from,
                   date_to=date_to,
                   days=1,
                   vacation_type=rtt_vacation,
                   status='ACCEPTED_MANAGER',
                   user=user1,
                   notified=True)
    session.add(req9)

    date_from = datetime.strptime('01/02/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/02/2016', '%d/%m/%Y')
    req10 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=rtt_vacation,
                    status='APPROVED_ADMIN',
                    user=user1,
                    notified=True)
    session.add(req10)

    date_from = datetime.strptime('01/06/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/06/2016', '%d/%m/%Y')
    req11 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=recovery_vacation,
                    status='APPROVED_ADMIN',
                    user=user1,
                    notified=True)
    session.add(req11)

    date_from = datetime.strptime('12/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('12/04/2015', '%d/%m/%Y')
    req12 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=rtt_vacation,
                    status='DENIED',
                    user=user1,
                    notified=True)
    session.add(req12)

    date_from = datetime.strptime('06/06/2016', '%d/%m/%Y')
    date_to = datetime.strptime('06/06/2016', '%d/%m/%Y')
    req13 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=sickness_vacation,
                    status='APPROVED_ADMIN',
                    user=user1,
                    notified=True)
    session.add(req13)

    date_from = datetime.strptime('13/06/2016', '%d/%m/%Y')
    date_to = datetime.strptime('13/06/2016', '%d/%m/%Y')
    req14 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=exception_vacation,
                    status='APPROVED_ADMIN',
                    user=user2,
                    message="I need to see Star Wars, I'm a huge fan",
                    notified=True)
    session.add(req14)

    session.commit()
Пример #22
0
def setUpModule():

    engine = create_engine(settings)
    populate(engine)

    session = DBSession()
    user_group = Group.by_name(session, u'user')
    manager_group = Group.by_name(session, u'manager')
    sudoer_group = Group.by_name(session, u'sudoer')
    common_password = u'changeme'

    cp_vacation = VacationType.by_name(session, u'CP')
    rtt_vacation = VacationType.by_name(session, u'RTT')
    recovery_vacation = VacationType.by_name(session, u'Récupération')
    sickness_vacation = VacationType.by_name(session, u'Maladie')
    exception_vacation = VacationType.by_name(session, u'Exceptionnel')

    fr_country = Countries.by_name(session, u'fr')
    us_country = Countries.by_name(session, u'us')

    manager1 = User(login=u'manager1',
                    password=common_password,
                    email=u'*****@*****.**',
                    firstname=u'First',
                    lastname=u'Manager',
                    role=u'manager',
                    _country=fr_country,
                    )
    manager1.groups.append(manager_group)
    session.add(manager1)

    manager2 = User(login=u'manager2',
                    password=common_password,
                    email=u'*****@*****.**',
                    firstname=u'Second',
                    lastname=u'Manager',
                    role=u'manager',
                    _country=fr_country,
                    )
    manager2.groups.append(manager_group)
    session.add(manager2)

    manager_us = User(login=u'manager3',
                      password=common_password,
                      email=u'*****@*****.**',
                      firstname=u'Third',
                      lastname=u'Manager',
                      role=u'manager',
                      _country=us_country,
                      )
    manager_us.groups.append(manager_group)
    session.add(manager_us)

    user1 = User(login=u'jdoe',
                 password=common_password,
                 email=u'*****@*****.**',
                 manager=manager1,
                 firstname=u'John',
                 lastname=u'Doe',
                 _country=fr_country,
                 )
    user1.groups.append(user_group)
    session.add(user1)

    user2 = User(login=u'janedoe',
                 password=common_password,
                 email=u'*****@*****.**',
                 manager=manager2,
                 firstname=u'Jane',
                 lastname=u'Doe',
                 _country=fr_country,
                 )
    user2.groups.append(user_group)
    user2.groups.append(sudoer_group)
    session.add(user2)

    session.flush()
    sudoer = Sudoer(source_id=user2.id, target_id=1)
    session.add(sudoer)

    date_from = datetime.strptime('10/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('14/04/2015', '%d/%m/%Y')
    req1 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=cp_vacation,
                   status=u'PENDING',
                   user=user1,
                   notified=False)
    session.add(req1)

    date_from = datetime.strptime('10/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('21/04/2015', '%d/%m/%Y')
    req2 = Request(date_from=date_from,
                   date_to=date_to,
                   days=10,
                   vacation_type=cp_vacation,
                   status=u'PENDING',
                   user=user2,
                   notified=False,)
    session.add(req2)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req3 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=rtt_vacation,
                   status=u'ACCEPTED_MANAGER',
                   user=user1,
                   notified=True,)
    session.add(req3)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req4 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=rtt_vacation,
                   status=u'CANCELED',
                   user=user1,
                   notified=True,)
    session.add(req4)

    date_from = datetime.strptime('24/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('28/04/2015', '%d/%m/%Y')
    req5 = Request(date_from=date_from,
                   date_to=date_to,
                   days=5,
                   vacation_type=rtt_vacation,
                   status=u'APPROVED_ADMIN',
                   user=manager_us,
                   notified=True,)
    session.add(req5)

    date_from = datetime.strptime('24/08/2011', '%d/%m/%Y')
    date_to = datetime.strptime('24/08/2011', '%d/%m/%Y')
    req6 = Request(date_from=date_from,
                   date_to=date_to,
                   days=0.5,
                   vacation_type=rtt_vacation,
                   status=u'APPROVED_ADMIN',
                   user=user1,
                   notified=True,
                   label=u'AM')
    session.add(req6)

    date_from = datetime.strptime('14/07/2014', '%d/%m/%Y')
    date_to = datetime.strptime('14/07/2014', '%d/%m/%Y')
    req7 = Request(date_from=date_from,
                   date_to=date_to,
                   days=0.5,
                   vacation_type=rtt_vacation,
                   status=u'APPROVED_ADMIN',
                   user=user1,
                   notified=True,
                   label=u'AM')
    session.add(req7)

    # used for rtt vacation checks

    date_from = datetime.strptime('01/04/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/04/2016', '%d/%m/%Y')
    req8 = Request(date_from=date_from,
                   date_to=date_to,
                   days=1,
                   vacation_type=rtt_vacation,
                   status=u'PENDING',
                   user=user1,
                   notified=True)
    session.add(req8)

    date_from = datetime.strptime('01/03/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/03/2016', '%d/%m/%Y')
    req9 = Request(date_from=date_from,
                   date_to=date_to,
                   days=1,
                   vacation_type=rtt_vacation,
                   status=u'ACCEPTED_MANAGER',
                   user=user1,
                   notified=True)
    session.add(req9)

    date_from = datetime.strptime('01/02/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/02/2016', '%d/%m/%Y')
    req10 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=rtt_vacation,
                    status=u'APPROVED_ADMIN',
                    user=user1,
                    notified=True)
    session.add(req10)

    date_from = datetime.strptime('01/06/2016', '%d/%m/%Y')
    date_to = datetime.strptime('02/06/2016', '%d/%m/%Y')
    req11 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=recovery_vacation,
                    status=u'APPROVED_ADMIN',
                    user=user1,
                    notified=True)
    session.add(req11)

    date_from = datetime.strptime('12/04/2015', '%d/%m/%Y')
    date_to = datetime.strptime('12/04/2015', '%d/%m/%Y')
    req12 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=rtt_vacation,
                    status=u'DENIED',
                    user=user1,
                    notified=True)
    session.add(req12)

    date_from = datetime.strptime('06/06/2016', '%d/%m/%Y')
    date_to = datetime.strptime('06/06/2016', '%d/%m/%Y')
    req13 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=sickness_vacation,
                    status=u'APPROVED_ADMIN',
                    user=user1,
                    notified=True)
    session.add(req13)

    date_from = datetime.strptime('13/06/2016', '%d/%m/%Y')
    date_to = datetime.strptime('13/06/2016', '%d/%m/%Y')
    req14 = Request(date_from=date_from,
                    date_to=date_to,
                    days=1,
                    vacation_type=exception_vacation,
                    status=u'APPROVED_ADMIN',
                    user=user2,
                    message=u"I need to see Star Wars, I'm a huge fan",
                    notified=True)
    session.add(req14)

    session.commit()
Пример #23
0
    def render(self):
        if not self.user:
            return self.redirect()

        _ = self.request.translate

        holidays = get_holiday(self.user)

        ret_dict = {'types': [], 'holidays': holidays, 'sudo_users': [],
                    'futures_pending': [], 'futures_approved': []}

        vacation_types = VacationType.by_country(self.session,
                                                 self.user.country)
        for vac in vacation_types:
            if vac.visibility and self.user.role not in vac.visibility:
                continue
            # disable RTT for user with feature flag disable_rtt
            if vac.name == 'RTT' and self.user.has_feature('disable_rtt'):
                continue
            ret_dict['types'].append({'name': _(vac.name), 'id': vac.id})

        if self.user.is_admin:
            ret_dict['sudo_users'] = User.for_admin(self.session, self.user)
            managed_users = User.managed_users(self.session, self.user)
            if managed_users:
                ret_dict['sudo_users'].extend(managed_users)
            # special case where LU admin need to have RTT option
            rtt_vacation = VacationType.by_name(self.session, 'RTT')
            rtt_type = {'name': _('RTT'), 'id': rtt_vacation.id}
            if rtt_type not in ret_dict['types']:
                ret_dict['types'].append(rtt_type)
            # remove duplicate entries
            ret_dict['sudo_users'] = list(set(ret_dict['sudo_users']))

        # LU can use their CP if it was on a non working day
        ret_dict['recovered_cp'] = self.user.get_lu_holiday()

        futures_breakdown = [timestamp
                             for req in
                             Request.by_user_future_breakdown(self.session,
                                                              self.user)
                             for timestamp in req.timestamps]
        ret_dict['futures_breakdown'] = futures_breakdown
        futures_pending = [timestamp
                           for req in
                           Request.by_user_future_pending(self.session,
                                                          self.user)
                           for timestamp in req.timestamps]
        ret_dict['futures_pending'] = futures_pending
        futures_approved = [timestamp
                            for req in
                            Request.by_user_future_approved(self.session,
                                                            self.user)
                            for timestamp in req.timestamps]
        ret_dict['futures_approved'] = futures_approved

        exception_info_tooltip = """\
This type is for events which are not covered by other types: \
wedding, funeral, etc.

Providing a reason for this request is mandatory.
"""
        ret_dict['exception_info_tooltip'] = _(exception_info_tooltip)

        recovered_info_tooltip = """\
This type is for holidays which were on a non working day.

You can use them up to 3 months after their date to make a leave request.
Request must be only for 1 day at a time, and not partial (only Full).
"""
        ret_dict['recovered_info_tooltip'] = _(recovered_info_tooltip)

        if self.request.matched_route:
            matched_route = self.request.matched_route.name
            ret_dict.update({
                'matched_route': matched_route,
                'csrf_token': self.request.session.get_csrf_token()})
            return ret_dict

        ret_dict.update({'csrf_token': self.request.session.get_csrf_token()})
        return ret_dict
Пример #24
0
    def render(self):
        try:
            form_date_from = self.request.params.get('date_from')
            if ' - ' not in form_date_from:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            dates = self.request.params.get('date_from').split(' - ')
            date_from = datetime.strptime(dates[0], '%d/%m/%Y')
            date_to = datetime.strptime(dates[1], '%d/%m/%Y')
            breakdown = self.request.params.get('breakdown')

            # retrieve holidays for user so we can remove them from selection
            holidays = get_holiday(self.user,
                                   year=date_from.year,
                                   use_datetime=True)

            submitted = [
                d for d in daterange(date_from, date_to)
                if d.isoweekday() not in [6, 7] and d not in holidays
            ]
            days = float(len(submitted))
            pool = None

            days_diff = (date_to - date_from).days
            if days_diff < 0:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if (date_to == date_from) and days > 1:
                # same day, asking only for one or less day duration
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if days <= 0:
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            # check if user is sudoed
            check_user = self.get_target_user(self.user)
            # retrieve future requests for user so we can check overlap
            futures = [
                d for req in Request.by_user_future(self.session, check_user)
                for d in daterange(req.date_from, req.date_to)
            ]
            intersect = set(futures) & set(submitted)
            if intersect:
                err_intersect = True
                # must check for false warning in case of half day requests
                if len(intersect) == 1:
                    # only one date in conflict, check if it's for an half-day
                    dt = intersect.pop()
                    # retrieve the request for this date
                    req = [
                        req for req in Request.by_user_future(
                            self.session, check_user)
                        for d in daterange(req.date_from, req.date_to)
                        if d == dt
                    ]
                    if len(req) < 2:
                        req = req.pop()
                        if req.label != breakdown:
                            # intersect is false, it's not the same halfday
                            err_intersect = False
                            log.debug(
                                'False positive on intersect '
                                'for %s (%s): request: %d (%s)' %
                                (date_from, breakdown, req.id, req.label))

                if err_intersect:
                    msg = 'Invalid period: days already requested.'
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            vac_type = VacationType.by_id(self.session,
                                          int(self.request.params.get('type')))

            if not self.user.is_admin:
                # check if vacation requires user role
                if (vac_type.visibility
                        and self.user.role not in vac_type.visibility):
                    msg = 'You are not allowed to use type: %s' % vac_type.name
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # check RTT usage access
            if vac_type.name == u'RTT':
                if self.user.has_feature('disable_rtt'):
                    msg = 'You are not allowed to use type: %s' % vac_type.name
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # label field is used when requesting half day
            label = u''
            if breakdown != 'FULL':
                # handle half day
                if (days > 1):
                    msg = ('AM/PM option must be used only when requesting a '
                           'single day.')
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                else:
                    days = 0.5
                    label = unicode(breakdown)

            # check RTT usage
            if vac_type.name == u'RTT':
                pool = rtt_data = check_user.get_rtt_usage(self.session)
                if rtt_data is not None and rtt_data['left'] <= 0:
                    msg = 'No RTT left to take.'
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check that we have enough RTT to take
                if rtt_data is not None and days > rtt_data['left']:
                    msg = 'You only have %s RTT to use.' % rtt_data['left']
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check that we request vacations in the allowed year
                if rtt_data is not None and (date_from.year != rtt_data['year']
                                             or
                                             date_to.year != rtt_data['year']):
                    msg = ('RTT can only be used for year %d.' %
                           rtt_data['year'])
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            message = None
            # check Exceptionnel mandatory field
            if vac_type.name == u'Exceptionnel':
                message = self.request.params.get('exception_text')
                message = message.strip() if message else message
                if not message:
                    msg = ('You must provide a reason for %s requests' %
                           vac_type.name)
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check size
                if len(message) > 140:
                    msg = ('%s reason must not exceed 140 characters' %
                           vac_type.name)
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # check for Compensatoire type (LU holiday recovery)
            if vac_type.name == u'Compensatoire':
                to_recover = self.request.params.get('recovered_holiday')
                if to_recover == '-1':
                    msg = 'You must select a date for %s' % vac_type.name
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

                recover_date = datetime.strptime(to_recover, '%d/%m/%Y')
                vac_class = vac_type.get_class(check_user.country)
                if vac_class:
                    error = vac_class.validate_request(check_user, None, days,
                                                       recover_date, date_to)
                    if error is not None:
                        self.request.session.flash('error;%s' % error)
                        return HTTPFound(
                            location=route_url('home', self.request))
                    message = to_recover

            # check Récupération reason field
            if vac_type.name == u'Récupération':
                message = self.request.params.get('exception_text')
                message = message.strip() if message else message
                # check size
                if message and len(message) > 140:
                    msg = ('%s reason must not exceed 140 characters' %
                           vac_type.name)
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # check CP usage
            if vac_type.name == u'CP':
                cp_class = check_user.get_cp_class(self.session)
                pool = check_user.get_cp_usage(self.session)

                if cp_class:
                    # only FR and LU have a dedicated CP class to use

                    # convert days to hours for LU if needed
                    days = cp_class.convert_days(days)

                    error = cp_class.validate_request(check_user, pool, days,
                                                      date_from, date_to)
                    if error is not None:
                        self.request.session.flash('error;%s' % error)
                        return HTTPFound(
                            location=route_url('home', self.request))

                if pool:
                    # remove expire datetimes as it's not json serializable
                    if 'n_1' in pool:
                        pool['n_1'].pop('expire', None)
                    if 'extra' in pool:
                        pool['extra'].pop('expire', None)
                    pool['acquis'].pop('expire', None)
                    pool['restant'].pop('expire', None)

            # create the request
            # default values
            target_status = u'PENDING'
            target_user = self.user
            target_notified = False

            sudo_use = False
            if self.user.is_admin:
                sudo_user_id = int(self.request.params.get('sudo_user'))
                if sudo_user_id != -1:
                    user = User.by_id(self.session, sudo_user_id)
                    if user:
                        sudo_use = True
                        target_user = user
                        target_status = u'APPROVED_ADMIN'
                        target_notified = True

            # save pool status when making the request
            if pool:
                pool_status = json.dumps(pool)
            else:
                pool_status = json.dumps({})

            request = Request(
                date_from=date_from,
                date_to=date_to,
                days=days,
                vacation_type=vac_type,
                status=target_status,
                user=target_user,
                notified=target_notified,
                label=label,
                message=message,
                pool_status=pool_status,
            )
            self.session.add(request)
            self.session.flush()
            # create history entry
            sudo_user = None
            if sudo_use:
                sudo_user = self.user
            RequestHistory.new(self.session,
                               request,
                               '',
                               target_status,
                               target_user,
                               pool_status,
                               message=message,
                               sudo_user=sudo_user)

            if request and not sudo_use:
                msg = 'Request sent to your manager.'
                self.request.session.flash('info;%s' % msg)
                # call celery task directly, do not wait for polling
                from celery.registry import tasks
                from celery.task import subtask
                req_task = tasks['worker_pending']
                data = {'req_id': request.id}
                subtask(req_task).apply_async(kwargs={'data': data},
                                              countdown=5)
                log.info('scheduling task worker_pending for %s' % data)

            if request and sudo_use:
                settings = self.request.registry.settings
                if 'pyvac.celery.yaml' in settings:
                    with open(settings['pyvac.celery.yaml']) as fdesc:
                        Conf = yaml.load(fdesc, YAMLLoader)
                    caldav_url = Conf.get('caldav').get('url')
                    request.add_to_cal(caldav_url, self.session)
                    msg = 'Request added to calendar and DB.'
                    self.request.session.flash('info;%s' % msg)

        except Exception as exc:
            log.error(exc)
            msg = ('An error has occured while processing this request: %r' %
                   exc)
            self.request.session.flash('error;%s' % msg)

        return HTTPFound(location=route_url('home', self.request))
Пример #25
0
    def render(self):
        try:
            form_date_from = self.request.params.get('date_from')
            if ' - ' not in form_date_from:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            dates = self.request.params.get('date_from').split(' - ')
            date_from = datetime.strptime(dates[0], '%d/%m/%Y')
            date_to = datetime.strptime(dates[1], '%d/%m/%Y')

            # retrieve holidays for user so we can remove them from selection
            holidays = get_holiday(self.user, year=date_from.year,
                                   use_datetime=True)

            submitted = [d for d in daterange(date_from, date_to)
                         if d.isoweekday() not in [6, 7]
                         and d not in holidays]
            days = float(len(submitted))
            pool = None

            days_diff = (date_to - date_from).days
            if days_diff < 0:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if (date_to == date_from) and days > 1:
                # same day, asking only for one or less day duration
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if days <= 0:
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            # retrieve future requests for user so we can check overlap
            futures = [d for req in
                       Request.by_user_future(self.session, self.user)
                       for d in daterange(req.date_from, req.date_to)]

            intersect = set(futures) & set(submitted)
            if intersect:
                msg = 'Invalid period: days already requested.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            vac_type = VacationType.by_id(self.session,
                                          int(self.request.params.get('type')))

            # check if vacation requires user role
            if (vac_type.visibility
                    and self.user.role not in vac_type.visibility):
                msg = 'You are not allowed to use type: %s' % vac_type.name
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            # label field is used when requesting half day
            label = u''
            breakdown = self.request.params.get('breakdown')
            if breakdown != 'FULL':
                # handle half day
                if (days > 1):
                    msg = ('AM/PM option must be used only when requesting a '
                           'single day.')
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                else:
                    days = 0.5
                    label = unicode(breakdown)

            # check RTT usage
            if vac_type.name == u'RTT':
                pool = rtt_data = self.user.get_rtt_usage(self.session)
                if rtt_data is not None and rtt_data['left'] <= 0:
                    msg = 'No RTT left to take.'
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check that we have enough RTT to take
                if rtt_data is not None and days > rtt_data['left']:
                    msg = 'You only have %s RTT to use.' % rtt_data['left']
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check that we request vacations in the allowed year
                if rtt_data is not None and (
                        date_from.year != rtt_data['year'] or
                        date_to.year != rtt_data['year']):
                    msg = ('RTT can only be used for year %d.' %
                           rtt_data['year'])
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            message = None
            # check Exceptionnel mandatory field
            if vac_type.name == u'Exceptionnel':
                message = self.request.params.get('exception_text')
                message = message.strip() if message else message
                if not message:
                    msg = ('You must provide a reason for %s requests' %
                           vac_type.name)
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check size
                if len(message) > 140:
                    msg = ('%s reason must not exceed 140 characters' %
                           vac_type.name)
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # check Récupération reason field
            if vac_type.name == u'Récupération':
                message = self.request.params.get('exception_text')
                message = message.strip() if message else message
                # check size
                if message and len(message) > 140:
                    msg = ('%s reason must not exceed 140 characters' %
                           vac_type.name)
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # create the request
            # default values
            target_status = u'PENDING'
            target_user = self.user
            target_notified = False

            sudo_use = False
            if self.user.is_admin:
                sudo_user_id = int(self.request.params.get('sudo_user'))
                if sudo_user_id != -1:
                    user = User.by_id(self.session, sudo_user_id)
                    if user:
                        sudo_use = True
                        target_user = user
                        target_status = u'APPROVED_ADMIN'
                        target_notified = True

            # save pool status when making the request
            if pool:
                pool_status = json.dumps(pool)
            else:
                pool_status = json.dumps({})

            request = Request(date_from=date_from,
                              date_to=date_to,
                              days=days,
                              vacation_type=vac_type,
                              status=target_status,
                              user=target_user,
                              notified=target_notified,
                              label=label,
                              message=message,
                              pool_status=pool_status,
                              )
            self.session.add(request)
            self.session.flush()

            if request and not sudo_use:
                msg = 'Request sent to your manager.'
                self.request.session.flash('info;%s' % msg)
                # call celery task directly, do not wait for polling
                from celery.registry import tasks
                from celery.task import subtask
                req_task = tasks['worker_pending']
                data = {'req_id': request.id}
                subtask(req_task).apply_async(kwargs={'data': data},
                                              countdown=5)
                log.info('scheduling task worker_pending for %s' % data)

            if request and sudo_use:
                settings = self.request.registry.settings
                if 'pyvac.celery.yaml' in settings:
                    with open(settings['pyvac.celery.yaml']) as fdesc:
                        Conf = yaml.load(fdesc, YAMLLoader)
                    caldav_url = Conf.get('caldav').get('url')
                    request.add_to_cal(caldav_url)
                    msg = 'Request added to calendar and DB.'
                    self.request.session.flash('info;%s' % msg)

        except Exception as exc:
            log.error(exc)
            msg = ('An error has occured while processing this request: %r'
                   % exc)
            self.request.session.flash('error;%s' % msg)

        return HTTPFound(location=route_url('home', self.request))
Пример #26
0
def populate(engine):

    Base.metadata.create_all(engine)
    session = DBSession()

    user_perm = Permission(name='user_view')
    admin_perm = Permission(name='admin_view')
    manager_perm = Permission(name='manager_view')
    sudo_perm = Permission(name='sudo_view')
    session.add(user_perm)
    session.add(admin_perm)
    session.add(manager_perm)
    session.add(sudo_perm)

    admin_group = Group(name='admin')
    admin_group.permissions.append(user_perm)
    admin_group.permissions.append(admin_perm)
    admin_group.permissions.append(manager_perm)
    admin_group.permissions.append(sudo_perm)
    session.add(admin_group)

    manager_group = Group(name='manager')
    manager_group.permissions.append(user_perm)
    manager_group.permissions.append(manager_perm)
    manager_group.permissions.append(sudo_perm)
    session.add(manager_group)

    user_group = Group(name='user')
    user_group.permissions.append(user_perm)
    session.add(user_group)

    sudoer_group = Group(name='sudoer')
    sudoer_group.permissions.append(sudo_perm)
    session.add(sudoer_group)

    vactype1 = VacationType(name='CP')
    session.add(vactype1)
    vactype2 = VacationType(name='RTT')
    session.add(vactype2)
    vactype3 = VacationType(name='Congé Parental')
    session.add(vactype3)
    vactype4 = VacationType(name='Récupération')
    session.add(vactype4)
    vactype5 = VacationType(name='Maladie', visibility='admin')
    session.add(vactype5)
    vactype6 = VacationType(name='Exceptionnel')
    session.add(vactype6)
    vactype7 = VacationType(name='Compensatoire')
    session.add(vactype7)
    vactype8 = VacationType(name='Télétravail')
    session.add(vactype8)

    fr_country = Countries(name='fr')
    session.add(fr_country)
    lu_country = Countries(name='lu')
    session.add(lu_country)
    us_country = Countries(name='us')
    session.add(us_country)
    zh_country = Countries(name='zh')
    session.add(zh_country)

    now = datetime.now()
    cp_pool1 = Pool(name='acquis',
                    date_start=datetime(now.year, 6, 1),
                    date_end=datetime(now.year + 1, 5, 31),
                    status='active',
                    vacation_type=vactype1,
                    country=fr_country,
                    pool_group=1,
                    date_last_increment=now,
                    )
    session.add(cp_pool1)
    cp_pool2 = Pool(name='restant',
                    date_start=datetime(now.year - 1, 6, 1),
                    date_end=datetime(now.year, 5, 31),
                    status='active',
                    vacation_type=vactype1,
                    country=fr_country,
                    pool_group=1,
                    date_last_increment=now,
                    )
    session.add(cp_pool2)
    cplu_pool1 = Pool(name='acquis',
                      alias='légaux',
                      date_start=datetime(now.year, 1, 1),
                      date_end=datetime(now.year + 1, 3, 31),
                      status='active',
                      vacation_type=vactype1,
                      country=lu_country,
                      pool_group=2,
                      date_last_increment=now,
                      )
    session.add(cplu_pool1)
    cplu_pool2 = Pool(name='restant',
                      alias='report',
                      date_start=datetime(now.year - 1, 1, 1),
                      date_end=datetime(now.year, 3, 31),
                      status='active',
                      vacation_type=vactype1,
                      country=lu_country,
                      pool_group=2,
                      date_last_increment=now,
                      )
    session.add(cplu_pool2)
    rtt_pool = Pool(name=vactype2.name,
                    date_start=datetime(now.year, 1, 1),
                    date_end=datetime(now.year + 1, 12, 31),
                    status='active',
                    vacation_type=vactype2,
                    country=fr_country,
                    date_last_increment=now,
                    )
    session.add(rtt_pool)

    # CP is available for everyone
    vactype1.countries.append(fr_country)
    vactype1.countries.append(lu_country)
    vactype1.countries.append(us_country)
    vactype1.countries.append(zh_country)

    # RTT only available for france
    vactype2.countries.append(fr_country)

    # Parental vacation is available for everyone
    vactype3.countries.append(fr_country)
    vactype3.countries.append(lu_country)
    vactype3.countries.append(us_country)
    vactype3.countries.append(zh_country)

    # Recovery is available for everyone
    vactype4.countries.append(fr_country)
    vactype4.countries.append(lu_country)
    vactype4.countries.append(us_country)
    vactype4.countries.append(zh_country)

    # Sickness vacation is available for all countries
    vactype5.countries.append(fr_country)
    vactype5.countries.append(lu_country)
    vactype5.countries.append(us_country)
    vactype5.countries.append(zh_country)

    # Exception vacation is available for all countries
    vactype6.countries.append(fr_country)
    vactype6.countries.append(lu_country)
    vactype6.countries.append(us_country)
    vactype6.countries.append(zh_country)

    # Holiday recovery is only available for LU
    vactype7.countries.append(lu_country)

    # Remote is available for everyone
    vactype8.countries.append(fr_country)
    vactype8.countries.append(lu_country)
    vactype8.countries.append(us_country)
    vactype8.countries.append(zh_country)

    common_password = '******'

    admin = User(login='******',
                 password=common_password,
                 email='*****@*****.**',
                 firstname='The',
                 lastname='Administrator',
                 role='admin',
                 _country=fr_country)
    admin.groups.append(admin_group)
    session.add(admin)

    session.commit()
Пример #27
0
    def render(self):
        try:
            form_date_from = self.request.params.get('date_from')
            if ' - ' not in form_date_from:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            dates = self.request.params.get('date_from').split(' - ')
            date_from = datetime.strptime(dates[0], '%d/%m/%Y')
            date_to = datetime.strptime(dates[1], '%d/%m/%Y')

            days = float(len([d for d in daterange(date_from, date_to)
                              if d.isoweekday() not in [6, 7]]))

            days_diff = (date_to - date_from).days
            if days_diff < 0:
                msg = 'Invalid format for period.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if (date_to == date_from) and days > 1:
                # same day, asking only for one or less day duration
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            if days <= 0:
                msg = 'Invalid value for days.'
                self.request.session.flash('error;%s' % msg)
                return HTTPFound(location=route_url('home', self.request))

            vac_type = VacationType.by_id(self.session,
                                          int(self.request.params.get('type')))

            # label field is used when requesting half day
            label = u''
            breakdown = self.request.params.get('breakdown')
            if breakdown != 'FULL':
                # handle half day
                if (days > 1):
                    msg = ('AM/PM option must be used only when requesting a '
                           'single day.')
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                else:
                    days = 0.5
                    label = unicode(breakdown)

            # check RTT usage
            if vac_type.name == u'RTT':
                rtt_data = self.user.get_rtt_usage(self.session)
                if rtt_data is not None and rtt_data['left'] <= 0:
                    msg = 'No RTT left to take.'
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))
                # check that we have enough RTT to take
                if rtt_data is not None and days > rtt_data['left']:
                    msg = 'You only have %s RTT to use.' % rtt_data['left']
                    self.request.session.flash('error;%s' % msg)
                    return HTTPFound(location=route_url('home', self.request))

            # create the request
            # default values
            target_status = u'PENDING'
            target_user = self.user
            target_notified = False

            sudo_use = False
            if self.user.is_admin:
                sudo_user_id = int(self.request.params.get('sudo_user'))
                if sudo_user_id != -1:
                    user = User.by_id(self.session, sudo_user_id)
                    if user:
                        sudo_use = True
                        target_user = user
                        target_status = u'APPROVED_ADMIN'
                        target_notified = True

            request = Request(date_from=date_from,
                              date_to=date_to,
                              days=days,
                              vacation_type=vac_type,
                              status=target_status,
                              user=target_user,
                              notified=target_notified,
                              label=label,
                              )
            self.session.add(request)
            self.session.flush()

            if request and not sudo_use:
                msg = 'Request sent to your manager.'
                self.request.session.flash('info;%s' % msg)
                # call celery task directly, do not wait for polling
                from celery.registry import tasks
                from celery.task import subtask
                req_task = tasks['worker_pending']
                data = {'req_id': request.id}
                subtask(req_task).apply_async(kwargs={'data': data},
                                              countdown=5)
                log.info('scheduling task worker_pending for %s' % data)

            if request and sudo_use:
                settings = self.request.registry.settings
                if 'pyvac.celery.yaml' in settings:
                    with open(settings['pyvac.celery.yaml']) as fdesc:
                        Conf = yaml.load(fdesc, YAMLLoader)
                    caldav_url = Conf.get('caldav').get('url')
                    request.add_to_cal(caldav_url)
                    msg = 'Request added to calendar and DB.'
                    self.request.session.flash('info;%s' % msg)

        except Exception as exc:
            log.error(exc)
            msg = ('An error has occured while processing this request: %r'
                   % exc)
            self.request.session.flash('error;%s' % msg)

        return HTTPFound(location=route_url('home', self.request))