Example #1
0
    def _interval_dates(self, frequency, company):
        """
        Method used to compute the theoretical date from which account move lines should be fetched
        @param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually)
            frequencies are literal (daily means 24 hours and so on)
        @param {recordset} company: the company for which the closing is done
        @return {dict} the theoretical date from which account move lines are fetched.
            date_stop date to which the move lines are fetched, always now()
            the dates are in their ALWAFI Database string representation
        """
        date_stop = datetime.utcnow()
        interval_from = None
        name_interval = ''
        if frequency == 'daily':
            interval_from = date_stop - timedelta(days=1)
            name_interval = _('Daily Closing')
        elif frequency == 'monthly':
            month_target = date_stop.month > 1 and date_stop.month - 1 or 12
            year_target = month_target < 12 and date_stop.year or date_stop.year - 1
            interval_from = date_stop.replace(year=year_target,
                                              month=month_target)
            name_interval = _('Monthly Closing')
        elif frequency == 'annually':
            year_target = date_stop.year - 1
            interval_from = date_stop.replace(year=year_target)
            name_interval = _('Annual Closing')

        return {
            'interval_from': FieldDateTime.to_string(interval_from),
            'date_stop': FieldDateTime.to_string(date_stop),
            'name_interval': name_interval
        }
Example #2
0
    def test_event_mail_default_config(self):
        event = self.env['event.event'].create({
            'name':
            'Event Update Type',
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })
        self.assertEqual(event.date_tz, self.env.user.tz)
        self.assertFalse(event.seats_limited)
        self.assertFalse(event.auto_confirm)

        #Event Communications: when no event type, default configuration
        self.assertEqual(len(event.event_mail_ids), 3)
        self.assertEqual(event.event_mail_ids[0].interval_unit, 'now')
        self.assertEqual(event.event_mail_ids[0].interval_type, 'after_sub')
        self.assertEqual(event.event_mail_ids[0].template_ref,
                         self.env.ref('event.event_subscription'))
        self.assertEqual(event.event_mail_ids[1].interval_nbr, 1)
        self.assertEqual(event.event_mail_ids[1].interval_unit, 'hours')
        self.assertEqual(event.event_mail_ids[1].interval_type, 'before_event')
        self.assertEqual(event.event_mail_ids[1].template_ref,
                         self.env.ref('event.event_reminder'))
        self.assertEqual(event.event_mail_ids[2].interval_nbr, 3)
        self.assertEqual(event.event_mail_ids[2].interval_unit, 'days')
        self.assertEqual(event.event_mail_ids[2].interval_type, 'before_event')
        self.assertEqual(event.event_mail_ids[2].template_ref,
                         self.env.ref('event.event_reminder'))

        event.write({'event_mail_ids': False})
        self.assertEqual(event.event_mail_ids, self.env['event.mail'])
Example #3
0
    def _interval_dates(self, frequency, company):
        """
        Method used to compute the theoretical date from which account move lines should be fetched
        @param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually)
            frequencies are literal (daily means 24 hours and so on)
        @param {recordset} company: the company for which the closing is done
        @return {dict} the theoretical date from which account move lines are fetched.
            date_stop date to which the move lines are fetched, always now()
            the dates are in their Odoo Database string representation
        """
        date_stop = datetime.utcnow()
        interval_from = None
        name_interval = ''
        if frequency == 'daily':
            interval_from = date_stop - timedelta(days=1)
            name_interval = _('Daily Closing')
        elif frequency == 'monthly':
            month_target = date_stop.month > 1 and date_stop.month - 1 or 12
            year_target = month_target < 12 and date_stop.year or date_stop.year - 1
            interval_from = date_stop.replace(year=year_target, month=month_target)
            name_interval = _('Monthly Closing')
        elif frequency == 'annually':
            year_target = date_stop.year - 1
            interval_from = date_stop.replace(year=year_target)
            name_interval = _('Annual Closing')

        return {'interval_from': FieldDateTime.to_string(interval_from),
                'date_stop': FieldDateTime.to_string(date_stop),
                'name_interval': name_interval}
Example #4
0
    def test_process_attendees_form(self):
        event = self.env['event.event'].create({
            'name': 'Event Update Type',
            'event_type_id': self.event_type_complex.with_user(self.env.user).id,
            'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })

        form_details = {
            '1-name': 'Pixis',
            '1-email': '*****@*****.**',
            '1-phone': '+32444444444',
            '1-event_ticket_id': '2',
            '1-answer_ids-8': '5',
            '2-name': 'Geluchat',
            '2-email': '*****@*****.**',
            '2-phone': '+32777777777',
            '2-event_ticket_id': '3',
            '2-answer_ids-8': '9',
            '0-answer_ids-3': '7',
            '0-answer_ids-4': '1',
        }

        with MockRequest(self.env):
            registrations = WebsiteEvent()._process_attendees_form(event, form_details)

        self.assertEqual(registrations, [
            {'name': 'Pixis', 'email': '*****@*****.**', 'phone': '+32444444444', 'event_ticket_id': 2, 'answer_ids': [[4, 5], [4, 7], [4, 1]]},
            {'name': 'Geluchat', 'email': '*****@*****.**', 'phone': '+32777777777', 'event_ticket_id': 3, 'answer_ids': [[4, 9], [4, 7], [4, 1]]}
        ])
Example #5
0
    def test_event_type_configuration_from_type(self):
        event_type = self.event_type_questions.with_user(self.env.user)

        event = self.env['event.event'].create({
            'name':
            'Event Update Type',
            'event_type_id':
            event_type.id,
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })

        self.assertEqual(event.question_ids.mapped('question_type'),
                         ['simple_choice', 'simple_choice', 'text_box'])
        self.assertEqual(event.specific_question_ids.title, 'Question1')
        self.assertEqual(
            set(event.specific_question_ids.mapped('answer_ids.name')),
            set(['Q1-Answer1', 'Q1-Answer2']))
        self.assertEqual(len(event.general_question_ids), 2)
        self.assertEqual(event.general_question_ids[0].title, 'Question2')
        self.assertEqual(event.general_question_ids[1].title, 'Question3')
        self.assertEqual(
            set(event.general_question_ids[0].mapped('answer_ids.name')),
            set(['Q2-Answer1', 'Q2-Answer2']))
Example #6
0
    def test_02_right(self):
        """When a leave request is created on a period which starts within
        another leave request period and ends without overlapping, the new
        leave request should be adapted to start exactly after the overlapping
        period ends"""
        self.leave_request_model.create({
            'name': 'Test Leave Request B',
            'holiday_status_id': self.test_leave_type_id.id,
            'holiday_type': 'employee',
            'employee_id': self.test_employee_id.id,
            'type': 'remove',
            'date_from': Datetime.to_string(
                self.today + timedelta(days=9)),
            'date_to': Datetime.to_string(
                self.today + timedelta(days=12))
        })

        res = self.leave_request_model.search([
            ('employee_id', '=', self.test_employee_id.id),
            ('date_from', '=', Datetime.to_string(
                self.today + timedelta(days=11, seconds=1))),
            ('date_to', '=', Datetime.to_string(
                self.today + timedelta(days=12)))
        ])
        self.assertNotEquals(res, False)
Example #7
0
    def test_event_date_range(self):
        self.patcher = patch('odoo.addons.event.models.event.fields.Datetime',
                             wraps=Datetime)
        self.mock_datetime = self.patcher.start()

        self.mock_datetime.now.return_value = Datetime.to_string(
            datetime.datetime(2015, 12, 31, 12, 0))

        self.event_0.registration_ids.event_begin_date = datetime.datetime(
            2015, 12, 31, 18, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(),
                         u'today')

        self.event_0.registration_ids.event_begin_date = datetime.datetime(
            2016, 1, 1, 6, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(),
                         u'tomorrow')

        self.event_0.registration_ids.event_begin_date = datetime.datetime(
            2016, 1, 2, 6, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(),
                         u'in 2 days')

        self.mock_datetime.now.return_value = Datetime.to_string(
            datetime.datetime(2015, 12, 10, 12, 0))
        self.event_0.registration_ids.event_begin_date = datetime.datetime(
            2016, 1, 25, 6, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(),
                         u'next month')

        self.patcher.stop()
Example #8
0
    def test_event_configuration_from_type(self):
        """ In addition to event test, also test tickets configuration coming
        from event_sale capabilities. """
        event_type = self.event_type_tickets.with_user(self.env.user)
        self.assertEqual(event_type.event_type_ticket_ids.description,
                         self.event_product.description_sale)

        event = self.env['event.event'].create({
            'name':
            'Event Update Type',
            'event_type_id':
            event_type.id,
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })

        # synchronize event
        event.write({'event_type_id': event_type.id})
        self.assertEqual(event.event_ticket_ids.name,
                         event.event_type_id.event_type_ticket_ids.name)
        self.assertTrue(event.event_ticket_ids.seats_limited)
        self.assertEqual(event.event_ticket_ids.seats_max, 5)
        self.assertEqual(event.event_ticket_ids.product_id, self.event_product)
        self.assertEqual(event.event_ticket_ids.price,
                         self.event_product.list_price)
        self.assertEqual(event.event_ticket_ids.description,
                         self.event_product.description_sale)
Example #9
0
    def _check_presence(self):
        company = self.env.company
        if not company.hr_presence_last_compute_date or \
                company.hr_presence_last_compute_date.day != Datetime.now().day:
            self.env['hr.employee'].search([
                ('department_id.company_id', '=', company.id)
            ]).write({'hr_presence_state': 'to_define'})

        employees = self.env['hr.employee'].search([
            ('department_id.company_id', '=', company.id),
            ('user_id', '!=', False),
            ('hr_presence_state', '=', 'to_define')])

        # Remove employees on holidays
        leaves = self.env['hr.leave'].search([
            ('state', '=', 'validate'),
            ('date_from', '<=', Datetime.to_string(Datetime.now())),
            ('date_to', '>=', Datetime.to_string(Datetime.now()))])
        employees_on_holiday = leaves.mapped('employee_id')
        employees_on_holiday.write({'hr_presence_state': 'absent'})
        employees = employees - employees_on_holiday

        # Check on system login
        if self.env['ir.config_parameter'].sudo().get_param('hr_presence.hr_presence_control_login'):
            online_employees = employees.filtered(lambda employee: employee.user_id.im_status in ['away', 'online'])
            online_employees.write({'hr_presence_state': 'present'})
            employees = employees - online_employees

        # Check on IP
        if self.env['ir.config_parameter'].sudo().get_param('hr_presence.hr_presence_control_ip'):
            ip_list = company.hr_presence_control_ip_list
            ip_list = ip_list.split(',') if ip_list else []
            ip_employees = self.env['hr.employee']
            for employee in employees:
                employee_ips = self.env['res.users.log'].search([
                    ('create_uid', '=', employee.user_id.id),
                    ('ip', '!=', False),
                    ('create_date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)))]
                ).mapped('ip')
                if any([ip in ip_list for ip in employee_ips]):
                    ip_employees |= employee
            ip_employees.write({'hr_presence_state': 'present'})
            employees = employees - ip_employees

        # Check on sent emails
        if self.env['ir.config_parameter'].sudo().get_param('hr_presence.hr_presence_control_email'):
            email_employees = self.env['hr.employee']
            threshold = company.hr_presence_control_email_amount
            for employee in employees:
                sent_emails = self.env['mail.message'].search_count([
                    ('author_id', '=', employee.user_id.partner_id.id),
                    ('date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))),
                    ('date', '<=', Datetime.to_string(Datetime.now()))])
                if sent_emails >= threshold:
                    email_employees |= employee
            email_employees.write({'hr_presence_state': 'present'})
            employees = employees - email_employees

        company.hr_presence_last_compute_date = Datetime.now()
Example #10
0
    def test_event_configuration_from_type(self):
        """ Test data computation of event coming from its event.type template.
        Some one2many notably are duplicated from type configuration and some
        advanced testing is required, notably mail schedulers. """

        self.assertEqual(self.env.user.tz, 'Europe/Brussels')

        event_type = self.event_type_complex.with_user(self.env.user)
        event_type.write({
            'use_mail_schedule': False,
        })
        self.assertEqual(event_type.event_type_mail_ids,
                         self.env['event.type.mail'])

        event = self.env['event.event'].create({
            'name':
            'Event Update Type',
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
            'is_online':
            True,
        })
        self.assertEqual(event.date_tz, self.env.user.tz)
        self.assertEqual(event.seats_availability, 'unlimited')
        self.assertFalse(event.auto_confirm)
        self.assertTrue(event.is_online)
        self.assertEqual(event.event_mail_ids, self.env['event.mail'])

        event_type.write({
            'use_mail_schedule':
            True,
            'event_type_mail_ids':
            [(5, 0),
             (0, 0, {
                 'interval_nbr':
                 1,
                 'interval_unit':
                 'days',
                 'interval_type':
                 'before_event',
                 'template_id':
                 self.env['ir.model.data'].xmlid_to_res_id(
                     'event.event_reminder')
             })]
        })
        event.write({'event_type_id': event_type.id})
        self.assertEqual(event.date_tz, 'Europe/Paris')
        self.assertEqual(event.seats_availability, 'limited')
        self.assertEqual(event.seats_max, event_type.seats_max)
        self.assertTrue(event.auto_confirm)
        self.assertFalse(event.is_online)
        self.assertEqual(event.event_mail_ids.interval_nbr, 1)
        self.assertEqual(event.event_mail_ids.interval_unit, 'days')
        self.assertEqual(event.event_mail_ids.interval_type, 'before_event')
        self.assertEqual(event.event_mail_ids.template_id,
                         self.env.ref('event.event_reminder'))
Example #11
0
    def test_registration_answer_search(self):
        """ Test our custom name_search implementation in 'event.registration.answer'.
        We search on both the 'value_answer_id' and 'value_text_box' fields to allow users to easily
        filter registrations based on the selected answers of the attendees. """

        event = self.env['event.event'].create({
            'name': 'Test Event',
            'event_type_id': self.event_type_questions.id,
            'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })

        [registration_1, registration_2, registration_3] = self.env['event.registration'].create([{
            'event_id': event.id,
            'partner_id': self.env.user.partner_id.id,
            'registration_answer_ids': [
                (0, 0, {
                    'question_id': self.event_question_1.id,
                    'value_answer_id': self.event_question_1.answer_ids[0].id,
                }),
            ]
        }, {
            'event_id': event.id,
            'partner_id': self.env.user.partner_id.id,
            'registration_answer_ids': [
                (0, 0, {
                    'question_id': self.event_question_1.id,
                    'value_answer_id': self.event_question_1.answer_ids[1].id,
                }),
                (0, 0, {
                    'question_id': self.event_question_3.id,
                    'value_text_box': "My Answer",
                }),
            ]
        }, {
            'event_id': event.id,
            'partner_id': self.env.user.partner_id.id,
            'registration_answer_ids': [
                (0, 0, {
                    'question_id': self.event_question_3.id,
                    'value_text_box': "Answer2",
                }),
            ]
        }])

        search_res = self.env['event.registration'].search([
            ('registration_answer_ids', 'ilike', 'Answer1')
        ])
        # should fetch "registration_1" because the answer to the first question is "Q1-Answer1"
        self.assertEqual(search_res, registration_1)

        search_res = self.env['event.registration'].search([
            ('registration_answer_ids', 'ilike', 'Answer2')
        ])
        # should fetch "registration_2" because the answer to the first question is "Q1-Answer2"
        # should fetch "registration_3" because the answer to the third question is "Answer2" (as free text)
        self.assertEqual(search_res, registration_2 | registration_3)
    def test_event_fields(self):
        event_type = self.event_type_complex.with_user(self.env.user)
        event = self.env['event.event'].create({
            'name':
            'Event Update Type',
            'event_type_id':
            event_type.id,
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })
        event._onchange_type()
        self.assertFalse(event.is_online)
        self.assertEqual(event.address_id, self.env.user.company_id.partner_id)
        # seats: coming from event type configuration
        self.assertEqual(event.seats_availability, 'limited')
        self.assertEqual(event.seats_available,
                         event.event_type_id.default_registration_max)
        self.assertEqual(event.seats_unconfirmed, 0)
        self.assertEqual(event.seats_reserved, 0)
        self.assertEqual(event.seats_used, 0)
        self.assertEqual(event.seats_expected, 0)

        # set is_online: should reset the address_id field
        event.update({'is_online': True})
        event._onchange_is_online()
        self.assertTrue(event.is_online)
        self.assertFalse(event.address_id)

        # create registration in order to check the seats computation
        self.assertTrue(event.auto_confirm)
        for x in range(5):
            reg = self.env['event.registration'].create({
                'event_id': event.id,
                'name': 'reg_open',
            })
            self.assertEqual(reg.state, 'open')
        reg_draft = self.env['event.registration'].create({
            'event_id': event.id,
            'name': 'reg_draft',
        })
        reg_draft.write({'state': 'draft'})
        reg_done = self.env['event.registration'].create({
            'event_id': event.id,
            'name': 'reg_done',
        })
        reg_done.write({'state': 'done'})
        self.assertEqual(event.seats_available,
                         event.event_type_id.default_registration_max - 6)
        self.assertEqual(event.seats_unconfirmed, 1)
        self.assertEqual(event.seats_reserved, 5)
        self.assertEqual(event.seats_used, 1)
        self.assertEqual(event.seats_expected, 7)
Example #13
0
    def test_05_all(self):
        """This test will check the more complex case in which a new leave
        request's period includes multiple distinct periods covered by already
         existing leave requests. In this case, the system is expected to
         create multiple non-overlapping leave requests filling the gaps"""
        self.leave_request_model.create({
            'name': 'Test Leave Request E',
            'holiday_status_id': self.test_leave_type_id.id,
            'holiday_type': 'employee',
            'employee_id': self.test_employee_id.id,
            'type': 'remove',
            'date_from': Datetime.to_string(
                self.today - timedelta(days=1)),
            'date_to': Datetime.to_string(
                self.today + timedelta(days=13))
        })

        res = self.leave_request_model.search([
            ('employee_id', '=', self.test_employee_id.id),
            ('date_from', '=', Datetime.to_string(
                self.today - timedelta(days=1))),
            ('date_to', '=', Datetime.to_string(
                self.today - timedelta(seconds=1)))
        ])
        self.assertNotEquals(res, False)

        res = self.leave_request_model.search([
            ('employee_id', '=', self.test_employee_id.id),
            ('date_from', '=', Datetime.to_string(
                self.today + timedelta(days=2, seconds=1))),
            ('date_to', '=', Datetime.to_string(
                self.today + timedelta(days=4) - timedelta(seconds=1)))
        ])
        self.assertNotEquals(res, False)

        res = self.leave_request_model.search([
            ('employee_id', '=', self.test_employee_id.id),
            ('date_from', '=', Datetime.to_string(
                self.today + timedelta(days=7, seconds=1))),
            ('date_to', '=', Datetime.to_string(
                self.today + timedelta(days=9) - timedelta(seconds=1)))
        ])
        self.assertNotEquals(res, False)

        res = self.leave_request_model.search([
            ('employee_id', '=', self.test_employee_id.id),
            ('date_from', '=', Datetime.to_string(
                self.today + timedelta(days=11, seconds=1))),
            ('date_to', '=', Datetime.to_string(
                self.today + timedelta(days=13)))
        ])
        self.assertNotEquals(res, False)
Example #14
0
    def _check_presence(self):
        company = self.env.company
        if not company.hr_presence_last_compute_date or \
                company.hr_presence_last_compute_date.day != Datetime.now().day:
            self.env['hr.employee'].search([
                ('company_id', '=', company.id)
            ]).write({
                'email_sent': False,
                'ip_connected': False,
                'manually_set_present': False
            })

        employees = self.env['hr.employee'].search([('company_id', '=', company.id)])
        all_employees = employees


        # Check on IP
        if literal_eval(self.env['ir.config_parameter'].sudo().get_param('hr.hr_presence_control_ip', 'False')):
            ip_list = company.hr_presence_control_ip_list
            ip_list = ip_list.split(',') if ip_list else []
            ip_employees = self.env['hr.employee']
            for employee in employees:
                employee_ips = self.env['res.users.log'].search([
                    ('create_uid', '=', employee.user_id.id),
                    ('ip', '!=', False),
                    ('create_date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)))]
                ).mapped('ip')
                if any(ip in ip_list for ip in employee_ips):
                    ip_employees |= employee
            ip_employees.write({'ip_connected': True})
            employees = employees - ip_employees

        # Check on sent emails
        if literal_eval(self.env['ir.config_parameter'].sudo().get_param('hr.hr_presence_control_email', 'False')):
            email_employees = self.env['hr.employee']
            threshold = company.hr_presence_control_email_amount
            for employee in employees:
                sent_emails = self.env['mail.message'].search_count([
                    ('author_id', '=', employee.user_id.partner_id.id),
                    ('date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))),
                    ('date', '<=', Datetime.to_string(Datetime.now()))])
                if sent_emails >= threshold:
                    email_employees |= employee
            email_employees.write({'email_sent': True})
            employees = employees - email_employees

        company.sudo().hr_presence_last_compute_date = Datetime.now()

        for employee in all_employees:
            employee.hr_presence_state_display = employee.hr_presence_state
Example #15
0
    def test_event_configuration_from_type(self):
        """ In addition to event test, also test tickets configuration coming
        from event_sale capabilities. """
        event_type = self.event_type_complex.with_user(self.env.user)
        event_type.write({
            'use_mail_schedule': False,
            'use_ticket': False,
        })
        self.assertEqual(event_type.event_type_ticket_ids,
                         self.env['event.type.ticket'])

        event = self.env['event.event'].create({
            'name':
            'Event Update Type',
            'event_type_id':
            event_type.id,
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })
        event._onchange_type()
        self.assertEqual(event.event_ticket_ids,
                         self.env['event.event.ticket'])

        event_type.write({
            'use_ticket':
            True,
            'event_type_ticket_ids': [(5, 0),
                                      (0, 0, {
                                          'name': 'First Ticket',
                                          'product_id': self.event_product.id,
                                          'seats_max': 5,
                                      })]
        })
        event_type.event_type_ticket_ids._onchange_product_id()
        self.assertEqual(event_type.event_type_ticket_ids.description,
                         self.event_product.description_sale)

        # synchronize event
        event._onchange_type()
        self.assertEqual(event.event_ticket_ids.name,
                         event.event_type_id.event_type_ticket_ids.name)
        self.assertEqual(event.event_ticket_ids.seats_availability, 'limited')
        self.assertEqual(event.event_ticket_ids.seats_max, 5)
        self.assertEqual(event.event_ticket_ids.product_id, self.event_product)
        self.assertEqual(event.event_ticket_ids.price,
                         self.event_product.list_price)
        self.assertEqual(event.event_ticket_ids.description,
                         self.event_product.description_sale)
Example #16
0
    def test_event_booth_contact(self):
        """ Test contact details computation """
        customer = self.env['res.partner'].browse(self.event_customer.ids)
        category = self.env['event.booth.category'].browse(
            self.event_booth_category_1.ids)
        self.assertTrue(
            all(
                bool(customer[fname])
                for fname in ['name', 'email', 'country_id', 'phone']))
        customer_email = customer.email

        event = self.env['event.event'].create({
            'name':
            'Event',
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
            'event_type_id':
            False,
        })
        self.assertEqual(event.event_booth_ids, self.env['event.booth'])

        booth = self.env['event.booth'].create({
            'name': 'Test Booth',
            'booth_category_id': category.id,
            'event_id': event.id,
            'partner_id': customer.id,
        })
        self.assertEqual(booth.contact_name, customer.name)
        self.assertEqual(booth.contact_email, customer_email)
        self.assertEqual(booth.contact_phone, customer.phone)
        self.assertFalse(booth.contact_mobile, 'Data has no mobile')

        booth.write({
            'contact_email': '"New Emails" <*****@*****.**',
            'contact_phone': False,
        })
        self.assertEqual(booth.contact_email,
                         '"New Emails" <*****@*****.**')
        self.assertEqual(booth.contact_phone, False)
        self.assertEqual(customer.email, customer_email,
                         'No sync from booth to partner')

        # partial update of contact fields: we may end up with mixed contact information, is it a good idea ?
        booth.write({'partner_id': self.event_customer2.id})
        self.assertEqual(booth.contact_name, customer.name)
        self.assertEqual(booth.contact_email,
                         '"New Emails" <*****@*****.**')
        self.assertEqual(booth.contact_phone, self.event_customer2.phone)
Example #17
0
    def test_in_date_5(self):
        """ Receive the same lot at different times, once they're in the same location, the quants
        are merged and only the earliest incoming date is kept.
        """
        stock_location = self.env.ref('stock.stock_location_stock')
        product1 = self.env['product.product'].create({
            'name': 'Product A',
            'type': 'product',
            'tracking': 'lot',
        })
        lot1 = self.env['stock.production.lot'].create({
            'name':
            'lot1',
            'product_id':
            product1.id,
        })

        in_date1 = datetime.now()
        self.env['stock.quant']._update_available_quantity(product1,
                                                           stock_location,
                                                           1.0,
                                                           lot_id=lot1,
                                                           in_date=in_date1)

        quant = self.env['stock.quant'].search([
            ('product_id', '=', product1.id),
            ('location_id', '=', stock_location.id),
        ])
        self.assertEqual(len(quant), 1)
        self.assertEqual(quant.quantity, 1)
        self.assertEqual(quant.lot_id.id, lot1.id)
        from odoo.fields import Datetime
        self.assertEqual(quant.in_date, Datetime.to_string(in_date1))

        in_date2 = datetime.now() - timedelta(days=5)
        self.env['stock.quant']._update_available_quantity(product1,
                                                           stock_location,
                                                           1.0,
                                                           lot_id=lot1,
                                                           in_date=in_date2)

        quant = self.env['stock.quant'].search([
            ('product_id', '=', product1.id),
            ('location_id', '=', stock_location.id),
        ])
        self.assertEqual(len(quant), 1)
        self.assertEqual(quant.quantity, 2)
        self.assertEqual(quant.lot_id.id, lot1.id)
        self.assertEqual(quant.in_date, Datetime.to_string(in_date2))
Example #18
0
 def test_expiration(self):
     self.assertTrue(
         self.lock.check_access_unique_virtual_key(
             self.key_1.unique_virtual_key))
     now = Datetime.from_string(Datetime.now())
     self.key_1.expiration_date = Datetime.to_string(now +
                                                     timedelta(hours=1))
     self.assertTrue(
         self.lock.check_access_unique_virtual_key(
             self.key_1.unique_virtual_key))
     self.key_1.expiration_date = Datetime.to_string(now +
                                                     timedelta(hours=-1))
     self.assertFalse(
         self.lock.check_access_unique_virtual_key(
             self.key_1.unique_virtual_key))
Example #19
0
 def test_04_included(self):
     """When a leave request is created on a period completely included in
     the period of an already existing leave request, the system shouldn't
     allow it and raise a ValidationError"""
     with self.assertRaises(ValidationError):
         self.leave_request_model.create({
             'name': 'Test Leave Request D',
             'holiday_status_id': self.test_leave_type_id.id,
             'holiday_type': 'employee',
             'employee_id': self.test_employee_id.id,
             'type': 'remove',
             'date_from': Datetime.to_string(
                 self.today + timedelta(days=5)),
             'date_to': Datetime.to_string(
                 self.today + timedelta(days=6))
         })
Example #20
0
 def test_room_capacity_exceeded_raises_validation_error(self):
     # todo creation should pass in draft state
     with self.assertRaises(ValidationError):
         self.env["hotel.reservation"].create({
             "partner_id":
             self.partner_1.id,
             "pricelist_id":
             self.pricelist.id,
             "checkin":
             Datetime.to_string(self.tomorrow),
             "checkout":
             Datetime.to_string(self.next_week),
             "adults":
             2,
             "children":
             1,
         })
Example #21
0
    def test_mfa_login_post_pass_not_expired(self, super_mock):
        """Should return result of super if user's password not expired"""
        test_response = 'Test Response'
        super_mock.return_value = test_response
        self.test_user.password_write_date = Datetime.to_string(datetime.now())
        result = self.test_controller.mfa_login_post().get_data()

        self.assertEqual(result, test_response)
Example #22
0
 def _get_odoo_date_format(self, iso_date):
     if iso_date:
         try:
             str_date = Datetime.to_string(dateutil.parser.parse(iso_date))
             return str_date
         except:
             return ''
     return ''
Example #23
0
    def test_event_type_configuration(self):
        event_type = self.event_type_complex.with_user(self.env.user)

        event = self.env['event.event'].create({
            'name': 'Event Update Type',
            'event_type_id': event_type.id,
            'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })

        self.assertEqual(event.specific_question_ids.title, 'Question1')
        self.assertEqual(
            set(event.specific_question_ids.mapped('answer_ids.name')),
            set(['Q1-Answer1', 'Q1-Answer2']))
        self.assertEqual(event.general_question_ids.title, 'Question2')
        self.assertEqual(
            set(event.general_question_ids.mapped('answer_ids.name')),
            set(['Q2-Answer1', 'Q2-Answer2']))
Example #24
0
    def test_event_configuration_from_type(self):
        """ In addition to event test, also test tickets configuration coming
        from event_sale capabilities. """
        event_type = self.event_type_complex.with_user(self.env.user)
        event_type.write({
            'use_mail_schedule': False,
            'use_ticketing': False,
        })
        # Event type does not use tickets but data is kept for compatibility and avoid recreating them
        self.assertEqual(len(event_type.event_ticket_ids), 1)
        self.assertEqual(event_type.event_ticket_ids.name, 'Registration')

        event = self.env['event.event'].create({
            'name':
            'Event Update Type',
            'event_type_id':
            event_type.id,
            'date_begin':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end':
            FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })
        event._onchange_type()
        self.assertEqual(event.event_ticket_ids,
                         self.env['event.event.ticket'])

        event_type.write({
            'use_ticketing':
            True,
            'event_ticket_ids': [(5, 0),
                                 (0, 0, {
                                     'name': 'First Ticket',
                                     'product_id': self.event_product.id,
                                 })]
        })
        event_type.event_ticket_ids._onchange_product_id()
        event._onchange_type()
        self.assertEqual(event.event_ticket_ids.name,
                         'Registration for %s' % event.name)
        self.assertEqual(event.event_ticket_ids.product_id, self.event_product)
        self.assertEqual(event.event_ticket_ids.price,
                         self.event_product.list_price)
Example #25
0
    def test_event_configuration_note_from_type(self):
        event_type = self.env['event.type'].browse(self.event_type_complex.id)

        event = self.env['event.event'].create({
            'name': 'Event Update Type Note',
            'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })

        # verify that note is not propagated if the event type contains blank html
        event.write({'note': '<p>Event Note</p>'})
        event_type.write({'note': '<p><br></p>'})
        event.write({'event_type_id': event_type.id})
        self.assertEqual(event.note, '<p>Event Note</p>')

        # verify that note is correctly propagated if it contains non empty html
        event.write({'event_type_id': False})
        event_type.write({'note': '<p>Event Type Note</p>'})
        event.write({'event_type_id': event_type.id})
        self.assertEqual(event.note, '<p>Event Type Note</p>')
Example #26
0
    def test_event_date_range(self):
        self.patcher = patch('odoo.addons.event.models.event.fields.Datetime', wraps=Datetime)
        self.mock_datetime = self.patcher.start()

        self.mock_datetime.now.return_value = Datetime.to_string(datetime.datetime(2015, 12, 31, 12, 0))

        self.event_0.registration_ids.event_begin_date = datetime.datetime(2015, 12, 31, 18, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(), u'today')

        self.event_0.registration_ids.event_begin_date = datetime.datetime(2016, 1, 1, 6, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(), u'tomorrow')

        self.event_0.registration_ids.event_begin_date = datetime.datetime(2016, 1, 2, 6, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(), u'in 2 days')

        self.mock_datetime.now.return_value = Datetime.to_string(datetime.datetime(2015, 12, 10, 12, 0))
        self.event_0.registration_ids.event_begin_date = datetime.datetime(2016, 1, 25, 6, 0)
        self.assertEqual(self.event_0.registration_ids.get_date_range_str(), u'next month')

        self.patcher.stop()
Example #27
0
 def poll(self, channels, last, options=None):
     if request.env.user.has_group('base.group_user'):
         ip_address = request.httprequest.remote_addr
         users_log = request.env['res.users.log'].search_count([
             ('create_uid', '=', request.env.user.id),
             ('ip', '=', ip_address),
             ('create_date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)))])
         if not users_log:
             with registry(request.env.cr.dbname).cursor() as cr:
                 env = Environment(cr, request.env.user.id, {})
                 env['res.users.log'].create({'ip': ip_address})
     return super(BusController, self).poll(channels, last, options=options)
Example #28
0
    def test_in_date_5(self):
        """ Receive the same lot at different times, once they're in the same location, the quants
        are merged and only the earliest incoming date is kept.
        """
        stock_location = self.env.ref('stock.stock_location_stock')
        product1 = self.env['product.product'].create({
            'name': 'Product A',
            'type': 'product',
            'tracking': 'lot',
        })
        lot1 = self.env['stock.production.lot'].create({
            'name': 'lot1',
            'product_id': product1.id,
        })

        in_date1 = datetime.now()
        self.env['stock.quant']._update_available_quantity(product1, stock_location, 1.0, lot_id=lot1, in_date=in_date1)

        quant = self.env['stock.quant'].search([
            ('product_id', '=', product1.id),
            ('location_id', '=', stock_location.id),
        ])
        self.assertEqual(len(quant), 1)
        self.assertEqual(quant.quantity, 1)
        self.assertEqual(quant.lot_id.id, lot1.id)
        from odoo.fields import Datetime
        self.assertEqual(quant.in_date, Datetime.to_string(in_date1))

        in_date2 = datetime.now() - timedelta(days=5)
        self.env['stock.quant']._update_available_quantity(product1, stock_location, 1.0, lot_id=lot1, in_date=in_date2)

        quant = self.env['stock.quant'].search([
            ('product_id', '=', product1.id),
            ('location_id', '=', stock_location.id),
        ])
        self.assertEqual(len(quant), 1)
        self.assertEqual(quant.quantity, 2)
        self.assertEqual(quant.lot_id.id, lot1.id)
        self.assertEqual(quant.in_date, Datetime.to_string(in_date2))
Example #29
0
    def test_process_attendees_form(self):
        event = self.env['event.event'].create({
            'name': 'Event Update Type',
            'event_type_id': self.event_type_questions.with_user(self.env.user).id,
            'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)),
            'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)),
        })

        form_details = {
            '1-name': 'Pixis',
            '1-email': '*****@*****.**',
            '1-phone': '+32444444444',
            '1-event_ticket_id': '2',
            '2-name': 'Geluchat',
            '2-email': '*****@*****.**',
            '2-phone': '+32777777777',
            '2-event_ticket_id': '3',
            'question_answer-1-%s' % self.event_question_1.id: '5',
            'question_answer-2-%s' % self.event_question_1.id: '9',
            'question_answer-0-%s' % self.event_question_2.id: '7',
            'question_answer-0-%s' % self.event_question_3.id: 'Free Text',
        }

        with MockRequest(self.env):
            registrations = WebsiteEvent()._process_attendees_form(event, form_details)

        self.assertEqual(registrations, [
            {'name': 'Pixis', 'email': '*****@*****.**', 'phone': '+32444444444', 'event_ticket_id': 2,
            'registration_answer_ids': [
                (0, 0, {'question_id': self.event_question_1.id, 'value_answer_id': 5}),
                (0, 0, {'question_id': self.event_question_2.id, 'value_answer_id': 7}),
                (0, 0, {'question_id': self.event_question_3.id, 'value_text_box': 'Free Text'})]},
            {'name': 'Geluchat', 'email': '*****@*****.**', 'phone': '+32777777777', 'event_ticket_id': 3,
            'registration_answer_ids': [
                (0, 0, {'question_id': self.event_question_1.id, 'value_answer_id': 9}),
                (0, 0, {'question_id': self.event_question_2.id, 'value_answer_id': 7}),
                (0, 0, {'question_id': self.event_question_3.id, 'value_text_box': 'Free Text'})]}
        ])
Example #30
0
    def test_book_busy_room_raises_error(self):
        Reservation = self.env["hotel.reservation"]

        reservation_2 = Reservation.create({
            "partner_id":
            self.partner_1.id,
            "pricelist_id":
            self.pricelist.id,
            "checkin":
            Datetime.to_string(self.tomorrow),
            "checkout":
            Datetime.to_string(self.next_week),
            "adults":
            2,
            "reservation_line": [(0, 0, {
                "reserve": [(6, 0, [self.room_0.id])]
            })],
        })
        reservation_2.confirmed_reservation()

        reservation_2 = Reservation.create({
            "partner_id":
            self.partner_2.id,
            "pricelist_id":
            self.pricelist.id,
            "checkin":
            Datetime.to_string(self.tomorrow),
            "checkout":
            Datetime.to_string(self.next_week),
            "adults":
            2,
            "reservation_line": [(0, 0, {
                "reserve": [(6, 0, [self.room_0.id])]
            })],
        })
        with self.assertRaises(ValidationError):
            reservation_2.confirmed_reservation()
Example #31
0
 def test_lock_find_keys(self):
     result = self.lock.get_virtual_keys()
     self.assertEqual(len(result), 1)
     self.assertEqual(result[0]["id"], self.key_1.id)
     key = self.env["oddoor.key"].create({
         "name": "Key 1",
         "group_ids": [(4, self.group_1.id)]
     })
     result = self.lock.get_virtual_keys()
     self.assertEqual(len(result), 2)
     ids = [r["id"] for r in result]
     self.assertIn(self.key_1.id, ids)
     self.assertIn(key.id, ids)
     now = Datetime.from_string(Datetime.now())
     key.expiration_date = Datetime.to_string(now + timedelta(hours=-1))
     result = self.lock.get_virtual_keys()
     self.assertEqual(len(result), 1)
     self.assertEqual(result[0]["id"], self.key_1.id)
     key.expiration_date = Datetime.to_string(now + timedelta(hours=1))
     result = self.lock.get_virtual_keys()
     self.assertEqual(len(result), 2)
     ids = [r["id"] for r in result]
     self.assertIn(self.key_1.id, ids)
     self.assertIn(key.id, ids)
Example #32
0
    def setUp(self):
        super(TestLeaveOverlap, self).setUp()

        self.employee_model = self.env['hr.employee']
        self.user_model = self.env['res.users']
        self.leave_type_model = self.env['hr.holidays.status']
        self.leave_request_model = self.env['hr.holidays']
        self.today = Datetime.from_string(Datetime.now()).replace(
            hour=0, minute=0, second=0, microsecond=0)

        # Create an employee user to make leave requests
        self.test_user_id = self.user_model.create({
            'name': 'Test User',
            'login': '******',
            'email': '*****@*****.**'
        })

        # Create an employee related to the user to make leave requests
        self.test_employee_id = self.employee_model.create(
            {'name': 'Test Employee', 'user_id': self.test_user_id.id})

        # Create 1 leave type
        self.test_leave_type_id = self.leave_type_model.create(
            {'name': 'Test Leave Type1'})

        # Create some leave request
        self.leave_request1 = self.leave_request_model.create({
            'name': 'Test Leave Request 1',
            'holiday_status_id': self.test_leave_type_id.id,
            'holiday_type': 'employee',
            'employee_id': self.test_employee_id.id,
            'type': 'remove',
            'date_from': Datetime.to_string(self.today),
            'date_to': Datetime.to_string(self.today + timedelta(days=2))
        })

        self.leave_request2 = self.leave_request_model.create({
            'name': 'Test Leave Request 2',
            'holiday_status_id': self.test_leave_type_id.id,
            'holiday_type': 'employee',
            'employee_id': self.test_employee_id.id,
            'type': 'remove',
            'date_from': Datetime.to_string(self.today + timedelta(days=4)),
            'date_to': Datetime.to_string(self.today + timedelta(days=7))
        })

        self.leave_request3 = self.leave_request_model.create({
            'name': 'Test Leave Request 3',
            'holiday_status_id': self.test_leave_type_id.id,
            'holiday_type': 'employee',
            'employee_id': self.test_employee_id.id,
            'type': 'remove',
            'date_from': Datetime.to_string(self.today + timedelta(days=9)),
            'date_to': Datetime.to_string(self.today + timedelta(days=11))
        })
Example #33
0
 def poll(self, channels, last, options=None):
     if request.env.user.has_group('base.group_user'):
         ip_address = request.httprequest.remote_addr
         users_log = request.env['res.users.log'].search_count([
             ('create_uid', '=', request.env.user.id),
             ('ip', '=', ip_address),
             ('create_date', '>=',
              Datetime.to_string(Datetime.now().replace(hour=0,
                                                        minute=0,
                                                        second=0,
                                                        microsecond=0)))
         ])
         if not users_log:
             with registry(request.env.cr.dbname).cursor() as cr:
                 env = Environment(cr, request.env.user.id, {})
                 env['res.users.log'].create({'ip': ip_address})
     return super(BusController, self).poll(channels, last, options=None)
Example #34
0
    def setUp(self):
        super(TestAuthTotpPasswordSecurity, self).setUp()

        self.test_controller = AuthTotpPasswordSecurity()

        self.test_user = self.env.ref('base.user_root')
        self.test_user.company_id.password_expiration = 1
        pass_date = datetime(year=2016, month=1, day=1)
        self.test_user.password_write_date = Datetime.to_string(pass_date)

        request_patcher = patch(CONTROLLER_PATH + '.request')
        self.addCleanup(request_patcher.stop)
        self.request_mock = request_patcher.start()
        self.request_mock.params = {'login_success': True}
        self.request_mock.uid = self.test_user.id
        self.request_mock.env = self.env

        # Needed when tests are run with no prior requests
        base_request_patcher = patch('odoo.http.request')
        self.addCleanup(base_request_patcher.stop)
        base_request_patcher.start()
Example #35
0
 def test_03(self):
     """After 36 hours"""
     date = Datetime.to_string(Datetime.from_string("2014-01-02 12:00:00"))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -1.5)
Example #36
0
 def test_04(self):
     """After 48 hours"""
     date = Datetime.to_string(Datetime.from_string('2014-01-03 00:00:00'))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -2)
Example #37
0
 def test_06(self):
     """After 50 days"""
     date = Datetime.to_string(Datetime.from_string('2014-02-20 00:00:00'))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -50)
Example #38
0
 def test_07(self):
     """After 182 days, exactly half of the budget line"""
     date = Datetime.to_string(Datetime.from_string('2014-07-02 00:00:00'))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -182)
Example #39
0
 def test_08(self):
     """After 308 days at noon"""
     date = Datetime.to_string(Datetime.from_string('2014-11-05 12:00:00'))  # remember, remember
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -308.5)
Example #40
0
 def test_09(self):
     """One day before"""
     date = Datetime.to_string(Datetime.from_string('2014-12-30 00:00:00'))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -363)
Example #41
0
 def test_10(self):
     """At last"""
     date = Datetime.to_string(Datetime.from_string('2014-12-31 00:00:00'))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -364)
Example #42
0
    def _action_open_presence_view(self):
        # Compute the presence/absence for the employees on the same
        # company than the HR/manager. Then opens the kanban view
        # of the employees with an undefined presence/absence

        _logger.info("Employees presence checked by: %s" % self.env.user.name)

        company = self.env.user.company_id
        if not company.hr_presence_last_compute_date or \
                company.hr_presence_last_compute_date.day != Datetime.now().day:
            self.env['hr.employee'].search([
                ('department_id.company_id', '=', company.id)
            ]).write({'hr_presence_state': 'to_define'})

        employees = self.env['hr.employee'].search([
            ('department_id.company_id', '=', company.id),
            ('user_id', '!=', False),
            ('hr_presence_state', '=', 'to_define')])

        # Remove employees on holidays
        leaves = self.env['hr.leave'].search([
            ('state', '=', 'validate'),
            ('date_from', '<=', Datetime.to_string(Datetime.now())),
            ('date_to', '>=', Datetime.to_string(Datetime.now()))])
        employees_on_holiday = leaves.mapped('employee_id')
        employees_on_holiday.write({'hr_presence_state': 'absent'})
        employees = employees - employees_on_holiday

        # Check on system login
        if self.env['ir.config_parameter'].sudo().get_param('hr_presence.hr_presence_control_login'):
            online_employees = employees.filtered(lambda employee: employee.user_id.im_status in ['away', 'online'])
            online_employees.write({'hr_presence_state': 'present'})
            employees = employees - online_employees

        # Check on IP
        if self.env['ir.config_parameter'].sudo().get_param('hr_presence.hr_presence_control_ip'):
            ip_list = company.hr_presence_control_ip_list
            ip_list = ip_list.split(',') if ip_list else []
            ip_employees = self.env['hr.employee']
            for employee in employees:
                employee_ips = self.env['res.users.log'].search([
                    ('create_uid', '=', employee.user_id.id),
                    ('ip', '!=', False),
                    ('create_date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)))]
                ).mapped('ip')
                if any([ip in ip_list for ip in employee_ips]):
                    ip_employees |= employee
            ip_employees.write({'hr_presence_state': 'present'})
            employees = employees - ip_employees

        # Check on sent emails
        if self.env['ir.config_parameter'].sudo().get_param('hr_presence.hr_presence_control_email'):
            email_employees = self.env['hr.employee']
            threshold = company.hr_presence_control_email_amount
            for employee in employees:
                sent_emails = self.env['mail.message'].search_count([
                    ('author_id', '=', employee.user_id.partner_id.id),
                    ('date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))),
                    ('date', '<=', Datetime.to_string(Datetime.now()))])
                if sent_emails >= threshold:
                    email_employees |= employee
            email_employees.write({'hr_presence_state': 'present'})
            employees = employees - email_employees

        company.hr_presence_last_compute_date = Datetime.now()

        return {
            "type": "ir.actions.act_window",
            "res_model": "hr.employee",
            "views": [[self.env.ref('hr_presence.hr_employee_view_kanban').id, "kanban"], [False, "tree"], [False, "form"]],
            'view_mode': 'kanban,tree,form',
            "domain": [],
            "name": "Employee's Presence to Define",
            "context": {'search_default_group_hr_presence_state': 1},
        }
Example #43
0
    def test_basic(self):
        """ Basic order test: no routing (thus no workorders), no lot """
        inventory = self.env['stock.inventory'].create({
            'name': 'Initial inventory',
            'filter': 'partial',
            'line_ids': [(0, 0, {
                'product_id': self.product_1.id,
                'product_uom_id': self.product_1.uom_id.id,
                'product_qty': 500,
                'location_id': self.warehouse_1.lot_stock_id.id
            }), (0, 0, {
                'product_id': self.product_2.id,
                'product_uom_id': self.product_2.uom_id.id,
                'product_qty': 500,
                'location_id': self.warehouse_1.lot_stock_id.id
            })]
        })
        inventory.action_done()

        test_date_planned = datetime.now() - timedelta(days=1)
        test_quantity = 2.0
        self.bom_1.routing_id = False
        man_order = self.env['mrp.production'].sudo(self.user_mrp_user).create({
            'name': 'Stick-0',
            'product_id': self.product_4.id,
            'product_uom_id': self.product_4.uom_id.id,
            'product_qty': test_quantity,
            'bom_id': self.bom_1.id,
            'date_planned_start': test_date_planned,
            'location_src_id': self.location_1.id,
            'location_dest_id': self.warehouse_1.wh_output_stock_loc_id.id,
        })
        self.assertEqual(man_order.state, 'confirmed', "Production order should be in confirmed state.")

        # check production move
        production_move = man_order.move_finished_ids
        self.assertEqual(production_move.date, Dt.to_string(test_date_planned))
        self.assertEqual(production_move.product_id, self.product_4)
        self.assertEqual(production_move.product_uom, man_order.product_uom_id)
        self.assertEqual(production_move.product_qty, man_order.product_qty)
        self.assertEqual(production_move.location_id, self.product_4.property_stock_production)
        self.assertEqual(production_move.location_dest_id, man_order.location_dest_id)

        # check consumption moves
        for move in man_order.move_raw_ids:
            self.assertEqual(move.date, Dt.to_string(test_date_planned))
        first_move = man_order.move_raw_ids.filtered(lambda move: move.product_id == self.product_2)
        self.assertEqual(first_move.product_qty, test_quantity / self.bom_1.product_qty * self.product_4.uom_id.factor_inv * 2)
        first_move = man_order.move_raw_ids.filtered(lambda move: move.product_id == self.product_1)
        self.assertEqual(first_move.product_qty, test_quantity / self.bom_1.product_qty * self.product_4.uom_id.factor_inv * 4)

        # waste some material, create a scrap
        # scrap = self.env['stock.scrap'].with_context(
        #     active_model='mrp.production', active_id=man_order.id
        # ).create({})
        # scrap = self.env['stock.scrap'].create({
        #     'production_id': man_order.id,
        #     'product_id': first_move.product_id.id,
        #     'product_uom_id': first_move.product_uom.id,
        #     'scrap_qty': 5.0,
        # })
        # check created scrap


        # procurements = self.env['procurement.order'].search([('move_dest_id', 'in', man_order.move_raw_ids.ids)])
        # print procurements
        # procurements = self.env['procurement.order'].search([('production_id', '=', man_order.id)])
        # print procurements
        # for proc in self.env['procurement.order'].browse(procurements):
        #     date_planned = self.mrp_production_test1.date_planned
        #     if proc.product_id.type not in ('product', 'consu'):
        #         continue
        #     if proc.product_id.id == order_line.product_id.id:
        #         self.assertEqual(proc.date_planned, date_planned, "Planned date does not correspond")
        #       # procurement state should be `confirmed` at this stage, except if procurement_jit is installed, in which
        #       # case it could already be in `running` or `exception` state (not enough stock)
        #         expected_states = ('confirmed', 'running', 'exception')
        #         self.assertEqual(proc.state in expected_states, 'Procurement state is `%s` for %s, expected one of %s' % (proc.state, proc.product_id.name, expected_states))

        # Change production quantity
        qty_wizard = self.env['change.production.qty'].create({
            'mo_id': man_order.id,
            'product_qty': 3.0,
        })
        # qty_wizard.change_prod_qty()

        # # I check qty after changed in production order.
        # #self.assertEqual(self.mrp_production_test1.product_qty, 3, "Qty is not changed in order.")
        # move = self.mrp_production_test1.move_finished_ids[0]
        # self.assertEqual(move.product_qty, self.mrp_production_test1.product_qty, "Qty is not changed in move line.")

        # # I run scheduler.
        # self.env['procurement.order'].run_scheduler()

        # # The production order is Waiting Goods, will force production which should set consume lines as available
        # self.mrp_production_test1.button_plan()
        # # I check that production order in ready state after forcing production.

        # #self.assertEqual(self.mrp_production_test1.availability, 'assigned', 'Production order availability should be set as available')

        # produce product
        produce_wizard = self.env['mrp.product.produce'].sudo(self.user_mrp_user).with_context({
            'active_id': man_order.id,
            'active_ids': [man_order.id],
        }).create({
            'product_qty': 1.0,
        })
        produce_wizard.do_produce()

        # man_order.button_mark_done()
        man_order.button_mark_done()
        self.assertEqual(man_order.state, 'done', "Production order should be in done state.")
Example #44
0
 def test_05(self):
     """After 10 days"""
     date = Datetime.to_string(Datetime.from_string("2014-01-11 00:00:00"))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, -10)
Example #45
0
 def test_01(self):
     """Start"""
     date = Datetime.to_string(Datetime.from_string('2014-01-01 00:00:00'))
     self.mock_datetime.now.return_value = date
     self.assertAlmostEqual(self.line.theoritical_amount, 0)
Example #46
0
File: rpc.py Project: Gorrice/odoo
 def dump_datetime(self, value, write):
     # override to marshall as a string for backwards compatibility
     value = Datetime.to_string(value)
     self.dump_unicode(value, write)