def _get_notes(self): self.ensure_one() today = date.today() monday = today - timedelta(days=today.weekday()) sunday = monday + timedelta(days=6) reservation_lines = ( self.env["hotel_reservation.line"].search([ ("line_id.state", "in", ["confirm", "done"]), ("reserve", "=", self.id), # checkin sunday or sooner ("checkin", "<=", Date.to_string(sunday)), # checkout monday or later ("checkout", ">=", Date.to_string(monday)), ]).sorted(lambda rl: rl.checkin)) # Since we cannot in the current code state add note to # reservation lines but only on reservation, the note # is duplicated on each room of the reservation in the report. # We add the date to the housekeeping note to make it clearer. def format_note(rl): if rl.line_id.housekeeping_note: local_timestamp = Datetime.context_timestamp( self, Datetime.from_string(rl.checkin)) checkin = local_timestamp.strftime("%a %d %b") return "{}: {}".format(checkin, rl.line_id.housekeeping_note) else: return False notes = (format_note(rl) for rl in reservation_lines) notes = (note for note in notes if note) # remove empty notes (False) return "\n".join(notes)
def setUpClass(cls): super(TestContractCalendars, cls).setUpClass() cls.calendar_richard = cls.env['resource.calendar'].create( {'name': 'Calendar of Richard'}) cls.employee.resource_calendar_id = cls.calendar_richard cls.calendar_35h = cls.env['resource.calendar'].create( {'name': '35h calendar'}) cls.calendar_35h._onchange_hours_per_day() # update hours/day cls.contract_cdd = cls.env['hr.contract'].create({ 'date_end': Date.to_date('2015-11-15'), 'date_start': Date.to_date('2015-01-01'), 'name': 'First CDD Contract for Richard', 'resource_calendar_id': cls.calendar_35h.id, 'wage': 5000.0, 'employee_id': cls.employee.id, 'state': 'close', })
def test_emc_user_access_to_own_subscription_register(self): self.as_emc_user() partner = self.env["res.users"].browse(self.uid).partner_id partner.structure = self.coopiteasy vals = { "name": "create passes", "register_number_operation": 5, "partner_id": self.ref("easy_my_coop.res_partner_cooperator_1_demo"), "date": Date.today(), "share_product_id": self.cie_share_product_product, "structure": self.coopiteasy.id, } register = self.env["subscription.register"].create(vals) _ = register.structure register.write({"name": "write passes"}) with self.assertRaises(AccessError): register.unlink() vals = { "name": "create fails", "register_number_operation": 5, "partner_id": self.ref("easy_my_coop.res_partner_cooperator_1_demo"), "date": Date.today(), "share_product_id": self.cc_share_product_product, "structure": self.coopcity.id, } with self.assertRaises(AccessError): self.env["subscription.register"].create(vals)
def generate_expenses(self): templates = self.env['hr.expense.template'].search([]) for template in templates: old_date = None next_date = None if template.last_expense_date: old_date = template.last_expense_date elif template.start_date: next_date = template.start_date else: raise exceptions.ValidationError('You Must Fill Start Date !') if not next_date: next_date = self.get_next_date(old_date, template) tz = pytz.timezone(self.env.user.partner_id.tz) current_date = datetime.now(tz=tz).date() if next_date <= current_date: vals = { 'name': template.name, 'product_id': template.product_id.id, 'analytic_account_id': template.analytic_account_id.id, 'analytic_tag_ids': template.analytic_tag_ids.ids, 'tax_ids': template.tax_ids.ids, 'unit_amount': template.unit_amount, 'quantity': template.quantity, 'employee_id': template.employee_id.id, 'date': Date.to_string(next_date), 'template_id': template.id, } res = self.env['hr.expense'].create(vals) template.write( {'last_expense_date': Date.to_string(next_date)}) print(res)
def test_onchange_product_id_recurring_info(self): self.product2.write({ 'recurring_rule_type': 'monthly', 'recurring_invoicing_type': 'pre-paid', 'is_auto_renew': True, 'default_qty': 12, 'termination_notice_interval': '6', 'termination_notice_rule_type': 'weekly', }) self.contract_line.write({ 'date_start': Date.today(), 'date_end': Date.today() + relativedelta(years=1), 'recurring_next_date': Date.today(), 'product_id': self.product2.id, }) self.contract_line._onchange_product_id_recurring_info() self.assertEqual(self.contract_line.recurring_rule_type, 'monthly') self.assertEqual(self.contract_line.recurring_invoicing_type, 'pre-paid') self.assertEqual(self.contract_line.recurring_interval, 1) self.assertEqual(self.contract_line.is_auto_renew, True) self.assertEqual(self.contract_line.auto_renew_interval, 12) self.assertEqual(self.contract_line.auto_renew_rule_type, 'monthly') self.assertEqual(self.contract_line.termination_notice_interval, 6) self.assertEqual(self.contract_line.termination_notice_rule_type, 'weekly')
def _to_dict(self, invoice): invoice.ensure_one() data = { "id": invoice.get_api_external_id(), "name": invoice.name, "state": invoice.state, "type": invoice.type, "date": Date.to_string(invoice.date), "date_due": Date.to_string(invoice.date_due), "date_invoice": Date.to_string(invoice.date_invoice), "partner": self._one_to_many_to_dict(invoice.partner_id), "journal": self._one_to_many_to_dict(invoice.journal_id), "account": self._one_to_many_to_dict(invoice.account_id), "subscription_request": self._one_to_many_to_dict(invoice.subscription_request), "invoice_lines": [self._line_to_dict(line) for line in invoice.invoice_line_ids], } return data
def test_route_search_by_date(self): sr_date = self.demo_request_1.date date_from = Date.to_string(sr_date - timedelta(days=1)) date_to = Date.to_string(sr_date + timedelta(days=1)) route = "/api/subscription-request?date_from=%s" % date_from content = self.http_get_content(route) self.assertIn(self.demo_request_1_dict, content["rows"]) route = "/api/subscription-request?date_to=%s" % date_to content = self.http_get_content(route) self.assertIn(self.demo_request_1_dict, content["rows"]) route = "/api/subscription-request?date_from={}&date_to={}".format( date_from, date_to) content = self.http_get_content(route) self.assertIn(self.demo_request_1_dict, content["rows"]) route = "/api/subscription-request?date_from=%s" % "2300-01-01" content = self.http_get_content(route) self.assertEquals(content["count"], 0) route = "/api/subscription-request?date_to=%s" % "1900-01-01" content = self.http_get_content(route) self.assertEquals(content["count"], 0)
def test_calendar_work_days_intervals_timezone(self): # _get_day_work_intervals converts from the timezone # of the user into UTC self.env.user.tz = 'US/Alaska' (self.leave1 | self.leave2 | self.leave3).unlink() leave = self.env['resource.calendar.leaves'].create({ 'name': 'Timezoned Leaves', 'calendar_id': self.calendar.id, 'resource_id': self.resource1_id, 'date_from': to_naive_utc(Datetime.from_string('2013-02-21 10:00:00'), self.env.user), 'date_to': to_naive_utc(Datetime.from_string('2013-02-26 12:00:00'), self.env.user) }) def to_tuple(interval): return (interval.start_datetime, interval.end_datetime) intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-26'), time(10), time(18), False, self.resource1_id) self.assertEqual(to_tuple(intervals[0]), (Datetime.from_string('2013-02-26 19:00:00'), Datetime.from_string('2013-02-27 01:00:00'))) intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-26'), time(10), time(18), True, self.resource1_id) self.assertEqual(to_tuple(intervals[0]), (Datetime.from_string('2013-02-26 21:00:00'), Datetime.from_string('2013-02-27 01:00:00'))) self.env.user.tz = 'Japan' intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-26'), time(10), time(18), False, self.resource1_id) self.assertEqual(to_tuple(intervals[0]), (Datetime.from_string('2013-02-26 01:00:00'), Datetime.from_string('2013-02-26 07:00:00'))) intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-26'), time(10), time(18), True, self.resource1_id) self.assertEqual(to_tuple(intervals[0]), (Datetime.from_string('2013-02-26 03:00:00'), Datetime.from_string('2013-02-26 07:00:00')))
def test_complete_loan_flow(self): loan_issue_values = { "name": "test loan issue", "default_issue": "xx", "subscription_start_date": Date.today(), "subscription_end_date": Date.today() + timedelta(days=60), "user_id": self.ref("easy_my_coop.res_users_manager_emc_demo"), "term_date": Date.today() + timedelta(days=600), # ? "gross_rate": 0.03, "face_value": 100, "minimum_amount": 4000, "maximum_amount": 10000, "interest_payment": "end", "by_company": True, "by_individual": True, "display_on_website": True, "taxes_rate": 0.08, "loan_term": 12, } self.as_emc_manager() loan_issue = self.env["loan.issue"].create(loan_issue_values) loan_issue.action_confirm() loan_issue.action_open() loan_issue.action_cancel() loan_issue.action_draft() loan_issue.action_open()
def _get_archive_groups( self, model, domain=None, fields=None, groupby="create_date", order="create_date desc", ): # TODO make without copy-pasting. Probably add ir.rule for portal user? if not model: return [] if domain is None: domain = [] if fields is None: fields = ["name", "create_date"] groups = [] for group in (request.env[model].sudo()._read_group_raw( domain, fields=fields, groupby=groupby, orderby=order)): dates, label = group[groupby] date_begin, date_end = dates.split("/") groups.append({ "date_begin": Date.to_string(Date.from_string(date_begin)), "date_end": Date.to_string(Date.from_string(date_end)), "name": label, "item_count": group[groupby + "_count"], }) return groups
def setUp(self): super(TestContract, self).setUp() self.brand_id = self.env["res.brand"].create({"name": "brand"}) self.line_vals["date_start"] = Date.today() self.line_vals["recurring_next_date"] = Date.today() self.acct_line = (self.env["contract.line"].with_context( test_queue_job_no_delay=True).create(self.line_vals))
def test_route_create(self): url = "/api/subscription-request" data = { "name": "Lisa des Danses", "email": "*****@*****.**", "ordered_parts": 3, "share_product": self.demo_share_product.id, "address": { "street": "schaerbeekstraat", "zip_code": "1111", "city": "Brussels", "country": "BE", }, "lang": "en_US", } response = self.http_post(url, data=data) self.assertEquals(response.status_code, 200) content = json.loads(response.content.decode("utf-8")) content.pop("id") # can't know id in advance expected = { **data, **{ "date": Date.to_string(Date.today()), "state": "draft", "share_product": { "id": self.demo_share_product.get_api_external_id(), "name": self.demo_share_product.name, }, "capital_release_request": [], }, } self.assertEquals(expected, content)
def test_leave(self): def to_tuple(interval): return (interval.start_datetime, interval.end_datetime) # Here we test if the leaves are correctly computed in the case our user is in UTC # NB: Beware of winter/spring time work_no_tz = [ to_tuple(x) for x in self.calendar._get_day_leave_intervals( Date.from_string('2018-12-25'), time(0), time(23, 59, 59), self.resource1_id) ] self.assertEqual(work_no_tz[0], (Datetime.from_string('2018-12-25 08:00:00'), Datetime.from_string('2018-12-25 16:00:00'))) work_user_tz = [ to_tuple(x) for x in self.calendar._get_day_leave_intervals( Date.from_string('2018-05-01'), time(0), time(23, 59, 59), self.resource1_id) ] self.assertEqual(work_user_tz[0], (Datetime.from_string('2018-05-01 08:00:00'), Datetime.from_string('2018-05-01 16:00:00'))) work_spec = [ to_tuple(x) for x in self.calendar._get_day_leave_intervals( Date.from_string('2018-04-06'), time(0), time(23, 59, 59), self.resource1_id) ] self.assertEqual(work_spec[0], (Datetime.from_string('2018-04-06 08:00:00'), Datetime.from_string('2018-04-06 13:00:00')))
def test_settings_pls_start_date(self): # We test here that settings never crash due to ill-configured config param 'crm.pls_start_date' set_param = self.env['ir.config_parameter'].sudo().set_param str_date_8_days_ago = Date.to_string(Date.today() - timedelta(days=8)) resConfig = self.env['res.config.settings'] set_param("crm.pls_start_date", "2021-10-10") res_config_new = resConfig.new() self.assertEqual( Date.to_string(res_config_new.predictive_lead_scoring_start_date), "2021-10-10", "If config param is a valid date, date in settings should match with config param" ) set_param("crm.pls_start_date", "") res_config_new = resConfig.new() self.assertEqual( Date.to_string(res_config_new.predictive_lead_scoring_start_date), str_date_8_days_ago, "If config param is empty, date in settings should be set to 8 days before today" ) set_param( "crm.pls_start_date", "One does not simply walk into system parameters to corrupt them") res_config_new = resConfig.new() self.assertEqual( Date.to_string(res_config_new.predictive_lead_scoring_start_date), str_date_8_days_ago, "If config param is not a valid date, date in settings should be set to 8 days before today" )
def setUp(self): super(TestPayslipBase, self).setUp() # Some salary rules references self.hra_rule_id = self.ref( 'hr_payroll.hr_salary_rule_houserentallowance1') self.conv_rule_id = self.ref( 'hr_payroll.hr_salary_rule_convanceallowance1') self.prof_tax_rule_id = self.ref( 'hr_payroll.hr_salary_rule_professionaltax1') self.pf_rule_id = self.ref('hr_payroll.hr_salary_rule_providentfund1') self.mv_rule_id = self.ref('hr_payroll.hr_salary_rule_meal_voucher') self.comm_rule_id = self.ref( 'hr_payroll.hr_salary_rule_sales_commission') # I create a new employee "Richard" self.richard_emp = self.env['hr.employee'].create({ 'name': 'Richard', 'gender': 'male', 'birthday': '1984-05-01', 'country_id': self.ref('base.be'), 'department_id': self.ref('hr.dep_rd') }) # I create a salary structure for "Software Developer" self.developer_pay_structure = self.env['hr.payroll.structure'].create( { 'name': 'Salary Structure for Software Developer', 'code': 'SD', 'company_id': self.ref('base.main_company'), 'rule_ids': [(4, self.hra_rule_id), (4, self.conv_rule_id), (4, self.prof_tax_rule_id), (4, self.pf_rule_id), (4, self.mv_rule_id), (4, self.comm_rule_id)], }) # I create a contract for "Richard" self.env['hr.contract'].create({ 'date_end': Date.to_string((datetime.now() + timedelta(days=365))), 'date_start': Date.today(), 'name': 'Contract for Richard', 'wage': 5000.0, 'type_id': self.ref('hr_contract.hr_contract_type_emp'), 'employee_id': self.richard_emp.id, 'struct_id': self.developer_pay_structure.id, })
def setUp(self): super(TestPartnerTimeToPay, self).setUp() self.payment_model = self.env["account.payment"] self.register_payments_model = self.env["account.payment.register"] self.partner_id = self.env.ref("base.res_partner_1") self.product_id = self.env.ref("product.product_product_4") self.account_model = self.env["account.account"] self.account_move_model = self.env["account.move"] self.account_journal = self.env["account.journal"] self.payment_method_manual_in = self.env.ref( "account.account_payment_method_manual_in") self.account_receivable_id = self.env.ref( "account.data_account_type_receivable") self.account_revenue_id = self.env.ref( "account.data_account_type_revenue") self.account_revenue = self.account_model.search( [("user_type_id", "=", self.account_revenue_id.id)], limit=1) self.today = Date.from_string(Date.context_today(self.env.user)) self.invoice_id = self.account_move_model.create({ "partner_id": self.partner_id.id, "type": "out_invoice", "invoice_date": self.today, "invoice_line_ids": [( 0, 0, { "product_id": self.product_id.id, "name": self.product_id.name, "price_unit": 100, "quantity": 10, "account_id": self.account_revenue.id, }, )], }) self.invoice_id._onchange_invoice_line_ids() self.invoice_id._onchange_recompute_dynamic_lines() self.invoice_id.action_post() self.bank_journal_euro = self.account_journal.create({ "name": "Bank", "type": "bank", "code": "BNK67" }) ctx = { "active_model": "account.invoice", "active_ids": [self.invoice_id.id] } self.register_payments = self.register_payments_model.with_context( ctx).create({ "payment_date": self.today + relativedelta(days=10), "journal_id": self.bank_journal_euro.id, "payment_method_id": self.payment_method_manual_in.id, }) self.register_payments.create_payments() self.payment = self.payment_model.search([], order="id desc", limit=1)
def test_payslip_generation_with_extra_work(self): # /!\ this is in the weekend (Sunday) => no calendar attendance at this time start = self.to_datetime_tz('2015-11-01 10:00:00', tz=pytz.utc) end = self.to_datetime_tz('2015-11-01 17:00:00', tz=pytz.utc) benef = self.env['hr.benefit'].create({ 'name': 'Extra', 'employee_id': self.richard_emp.id, 'contract_id': self.richard_emp.contract_id.id, 'benefit_type_id': self.benefit_type.id, 'date_start': start, 'date_stop': end, }) benef.action_validate(benef.ids) payslip_wizard = self.env['hr.payslip.employees'].create({'employee_ids': [(4, self.richard_emp.id)]}) payslip_wizard.with_context({ 'default_date_start': Date.to_string(start), 'default_date_end': Date.to_string(end + relativedelta(days=1)) }).compute_sheet() payslip = self.env['hr.payslip'].search([('employee_id', '=', self.richard_emp.id)]) work_line = payslip.worked_days_line_ids.filtered(lambda l: l.code == 'WORK100') # From default calendar.attendance leave_line = payslip.worked_days_line_ids.filtered(lambda l: l.code == 'WORK200') self.assertTrue(work_line, "It should have a work line in the payslip") self.assertTrue(leave_line, "It should have an extra work line in the payslip") self.assertEqual(work_line.number_of_hours, 8.0, "It should have 8 hours of work") # Monday self.assertEqual(leave_line.number_of_hours, 7.0, "It should have 5 hours of extra work") # Sunday
def test_register_payment_for_capital_release(self): self.as_emc_user() self.request.validate_subscription_request() invoice = self.request.capital_release_request ctx = {"active_model": "account.invoice", "active_ids": [invoice.id]} register_payments = ( self.env["account.register.payments"].with_context(ctx).create({ "payment_date": Date.today(), "journal_id": self.bank_journal_euro.id, "payment_method_id": self.payment_method_manual_in.id, })) register_payments.create_payments() self.assertEquals(self.request.capital_release_request.state, "paid") partner = self.request.partner_id self.assertFalse(partner.coop_candidate) self.assertTrue(partner.member) self.assertTrue(partner.share_ids) self.assertEquals(self.request.partner_id.effective_date, Date.today()) share = partner.share_ids[0] self.assertEquals(share.share_number, self.request.ordered_parts) self.assertEquals(share.share_product_id, self.request.share_product_id) self.assertEquals(share.effective_date, Date.today())
def _get_archive_groups(self, model, domain=None, fields=None, groupby="create_date", order="create_date desc"): if not model: return [] if domain is None: domain = [] if fields is None: fields = ['name', 'create_date'] groups = [] for group in request.env[model]._read_group_raw(domain, fields=fields, groupby=groupby, orderby=order): dates, label = group[groupby] date_begin, date_end = dates.split('/') groups.append({ 'date_begin': Date.to_string(Date.from_string(date_begin)), 'date_end': Date.to_string(Date.from_string(date_end)), 'name': label, 'item_count': group[groupby + '_count'] }) return groups
def test_calendar_working_day_intervals_leaves_generic(self): # Test: day0 with leaves outside range: 1 interval intervals = self.calendar._get_day_work_intervals( Date.from_string('2013-02-12'), start_time=time(7, 0, 0), compute_leaves=True) self.assertEqual(len(intervals), 1) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-12 08:00:00'), Datetime.from_string('2013-02-12 16:00:00'))) # Test: day0 with leaves: 2 intervals because of leave between 9 and 12, ending at 15:45:30 intervals = self.calendar._get_day_work_intervals( Date.from_string('2013-02-19'), start_time=time(8, 15, 0), end_time=time(15, 45, 30), compute_leaves=True) self.assertEqual(len(intervals), 2) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-19 08:15:00'), Datetime.from_string('2013-02-19 09:00:00'))) self.assertEqual(intervals[1][:2], (Datetime.from_string('2013-02-19 12:00:00'), Datetime.from_string('2013-02-19 15:45:30'))) self.assertEqual(intervals[0][2]['attendances'], self.att_1) self.assertEqual(intervals[0][2]['leaves'], self.leave1) self.assertEqual(intervals[1][2]['attendances'], self.att_1) self.assertEqual(intervals[0][2]['leaves'], self.leave1)
def _test_contract(self): struct = self.create_salary_structure(self.hr_payroll_user, 'Salary Structure', 'SOO1') # Contract without car and without fleet access rights contract_cdd = self.create_contract( user=self.hr_contract_manager, name="%s's CDD" % self.user.employee_id, employee=self.user.employee_id, structure=struct, start=Date.today() + relativedelta(day=1, months=-1), end=Date.today().replace(day=15), wage=1500, state='close', ) # Contract with a car and with access rights with additional_groups(self.hr_contract_manager, 'fleet.fleet_group_manager'): contract_cdi = self.create_contract( user=self.hr_contract_manager, name="%s's CDD" % self.user.employee_id, structure=struct, employee=self.user.employee_id, start=Date.today().replace(day=16), car=self.env['fleet.vehicle'].search([ ('driver_id', '=', self.user.employee_id.address_home_id.id), ('company_id', '=', self.user.employee_id.company_id.id), ], limit=1), wage=2500, state='draft', ) contract_cdi.state = 'open'
def test_leaves_timezones(self): self.env.user.tz = 'US/Alaska' # UTC-9 def to_tuple(interval): return (interval.start_datetime, interval.end_datetime) # Here we test if the leaves are correctly computed in the case our user is in tz Alaska # NB: Beware of winter/spring time work_no_tz = [ to_tuple(x) for x in self.calendar._get_day_leave_intervals( Date.from_string('2018-12-25'), time(0), time(23, 59, 59), self.resource1_id) ] self.assertEqual(work_no_tz[0], (Datetime.from_string('2018-12-25 17:00:00'), Datetime.from_string('2018-12-26 01:00:00'))) work_user_tz = [ to_tuple(x) for x in self.calendar._get_day_leave_intervals( Date.from_string('2018-05-01'), time(0), time(23, 59, 59), self.resource1_id) ] self.assertEqual(work_user_tz[0], (Datetime.from_string('2018-05-01 16:00:00'), Datetime.from_string('2018-05-02 00:00:00'))) work_spec = [ to_tuple(x) for x in self.calendar._get_day_leave_intervals( Date.from_string('2018-04-06'), time(0), time(23, 59, 59), self.resource1_id) ] self.assertEqual(work_spec[0], (Datetime.from_string('2018-04-06 16:00:00'), Datetime.from_string('2018-04-06 21:00:00')))
def test_service_create(self): self.demo_request_1.validate_subscription_request() invoice = self.demo_request_1.capital_release_request journal = self.bank_journal result = self.ap_service.create( payment_date=Date.to_string(Date.today()), amount=self.demo_request_1.subscription_amount, payment_type="inbound", payment_method="manual", communication=invoice.reference, invoice=invoice.get_api_external_id(), journal=journal.get_api_external_id(), ) demo_payment_dict = { "id": result["id"], "communication": invoice.reference, "invoice": { "id": invoice.get_api_external_id(), "name": invoice.name, }, "amount": self.demo_request_1.subscription_amount, "payment_date": Date.to_string(Date.today()), "journal": { "id": self.bank_journal.get_api_external_id(), "name": self.bank_journal.name, }, } self.assertEquals(demo_payment_dict, result) invoice = self.ai_service.get(invoice.get_api_external_id()) self.assertEquals("paid", invoice["state"])
def test_calendar_working_day_intervals_no_leaves(self): # Test: day0 without leaves: 1 interval intervals = self.calendar._get_day_work_intervals( Date.from_string('2013-02-12'), start_time=time(9, 8, 7)) self.assertEqual(len(intervals), 1) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-12 09:08:07'), Datetime.from_string('2013-02-12 16:00:00'))) self.assertEqual(intervals[0][2]['attendances'], self.att_1) # Test: day1, beginning at 10:30 -> work from 10:30 (arrival) until 16:00 intervals = self.calendar._get_day_work_intervals( Date.from_string('2013-02-19'), start_time=time(10, 30, 0)) self.assertEqual(len(intervals), 1) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-19 10:30:00'), Datetime.from_string('2013-02-19 16:00:00'))) self.assertEqual(intervals[0][2]['attendances'], self.att_1) # Test: day3 without leaves: 2 interval intervals = self.calendar._get_day_work_intervals( Date.from_string('2013-02-15'), start_time=time(10, 11, 12)) self.assertEqual(len(intervals), 2) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-15 10:11:12'), Datetime.from_string('2013-02-15 13:00:00'))) self.assertEqual(intervals[1][:2], (Datetime.from_string('2013-02-15 16:00:00'), Datetime.from_string('2013-02-15 23:00:00'))) self.assertEqual(intervals[0][2]['attendances'], self.att_2) self.assertEqual(intervals[1][2]['attendances'], self.att_3)
def test_02_account_move_date_range_fm_id_search(self): january_2017_1st = Date.from_string('2017-01-01') february_2017_1st = Date.from_string('2017-02-01') march_2017_1st = Date.from_string('2017-03-01') january_2018_1st = Date.from_string('2018-01-01') move_jan_2017 = self.create_account_move(january_2017_1st) move_feb_2017 = self.create_account_move(february_2017_1st) move_march_2017 = self.create_account_move(march_2017_1st) move_jan_2018 = self.create_account_move(january_2018_1st) moves = self.AccountMoveObj.search([ ('date_range_fm_id', 'ilike', 'January'), ]) self.assertTrue(all([ move_jan_2017 in moves, move_feb_2017 not in moves, move_march_2017 not in moves, move_jan_2018 in moves, ]), msg="There should be only moves in January") moves = self.AccountMoveObj.search([ ('date_range_fm_id', 'ilike', '2017'), ]) self.assertTrue( all([ move_jan_2017 in moves, move_feb_2017 in moves, move_march_2017 not in moves, move_jan_2018 not in moves, ])) moves = self.AccountMoveObj.search([ ('date_range_fm_id', '=', self.date_range_january_2017.id), ]) self.assertTrue( all([ move_jan_2017 in moves, move_feb_2017 not in moves, move_march_2017 not in moves, move_jan_2018 not in moves, ])) moves = self.AccountMoveObj.search([ ('date_range_fm_id', 'in', (self.date_range_january_2017.id, self.date_range_february_2017.id)), ]) self.assertTrue( all([ move_jan_2017 in moves, move_feb_2017 in moves, move_march_2017 not in moves, move_jan_2018 not in moves, ]))
def setUp(self): super(TestPartnerTimeToPay, self).setUp() self.payment_model = self.env['account.payment'] self.register_payments_model = self.env['account.register.payments'] self.partner_id = self.env.ref('base.res_partner_1') self.product_id = self.env.ref('product.product_product_4') self.account_model = self.env['account.account'] self.account_invoice_model = self.env['account.invoice'] self.account_journal = self.env['account.journal'] self.payment_method_manual_in =\ self.env.ref("account.account_payment_method_manual_in") self.account_receivable_id =\ self.env.ref('account.data_account_type_receivable') self.account_revenue_id =\ self.env.ref('account.data_account_type_revenue') self.account_receivable = self.account_model.search( [('user_type_id', '=', self.account_receivable_id.id)], limit=1) self.account_revenue = self.account_model.search( [('user_type_id', '=', self.account_revenue_id.id)], limit=1) self.today = Date.from_string(Date.context_today(self.env.user)) self.invoice_id = self.account_invoice_model.create({ 'partner_id': self.partner_id.id, 'type': 'out_invoice', 'account_id': self.account_receivable.id, 'date_invoice': self.today, 'invoice_line_ids': [(0, 0, { 'product_id': self.product_id.id, 'name': self.product_id.name, 'price_unit': 100, 'quantity': 10, 'account_id': self.account_revenue.id, })] }) self.invoice_id._onchange_invoice_line_ids() self.invoice_id._onchange_cash_rounding() self.invoice_id.action_invoice_open() self.bank_journal_euro =\ self.account_journal.create({ 'name': 'Bank', 'type': 'bank', 'code': 'BNK67' }) ctx = { 'active_model': 'account.invoice', 'active_ids': [self.invoice_id.id] } self.register_payments =\ self.register_payments_model.with_context(ctx).create({ 'payment_date': self.today + relativedelta(days=10), 'journal_id': self.bank_journal_euro.id, 'payment_method_id': self.payment_method_manual_in.id, }) self.register_payments.create_payments() self.payment = self.payment_model.search([], order="id desc", limit=1)
def _compute_age(self): today = fDate.from_string(fDate.today()) for lote in self.filtered('removal_date'): fecha_vencimiento = dateutil.parser.parse(lote.removal_date).date() # import pdb; pdb.set_trace() delta = (fecha_vencimiento - today) lote.dias_vencimiento = delta.days
def setUp(self): self.env = self.env( context=dict(self.env.context, test_queue_job_no_delay=True)) super(TestContractLineForecastPeriod, self).setUp() self.this_year = Date.today().year self.line_vals["date_start"] = Date.today() self.line_vals["recurring_next_date"] = Date.today() self.acct_line = self.env["contract.line"].create(self.line_vals)
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): """Override read_group to perform pro-rata temporis adjustments. When read_group is invoked with a domain that filters on a time period (date >= from and date <= to, or date_from <= to and date_to >= from), adjust the accumulated values pro-rata temporis. """ date_from = None date_to = None assert isinstance(domain, list) for domain_item in domain: if isinstance(domain_item, (list, tuple)): field, op, value = domain_item if field == "date" and op == ">=": date_from = value elif field == "date_to" and op == ">=": date_from = value elif field == "date" and op == "<=": date_to = value elif field == "date_from" and op == "<=": date_to = value if (date_from is not None and date_to is not None and not any(":" in f for f in fields)): dt_from = Date.from_string(date_from) dt_to = Date.from_string(date_to) res = {} sum_fields = set(fields) - set(groupby) read_fields = set(fields + ["date_from", "date_to"]) for item in self.search(domain).read(read_fields): key = tuple(item[k] for k in groupby) if key not in res: res[key] = {k: item[k] for k in groupby} res[key].update({k: 0.0 for k in sum_fields}) res_item = res[key] for sum_field in sum_fields: item_dt_from = Date.from_string(item["date_from"]) item_dt_to = Date.from_string(item["date_to"]) i_days, item_days = self._intersect_days( item_dt_from, item_dt_to, dt_from, dt_to) res_item[sum_field] += item[sum_field] * i_days / item_days return res.values() return super(ProRataReadGroupMixin, self).read_group( domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy, )
def fetch_dashboard_data(self, website_id, date_from, date_to): datetime_from = datetime.combine(Date.from_string(date_from), time.min) datetime_to = datetime.combine(Date.from_string(date_to), time.max) results = super(WebsiteSaleLinkTrackerBackend, self).fetch_dashboard_data(website_id, date_from, date_to) results['dashboards']['sales']['utm_graph'] = self.fetch_utm_data( datetime_from, datetime_to) return results
def _search_age(self, operator, value): today = fDate.from_string(fDate.context_today(self)) value_days = timedelta(days=value) value_date = fDate.to_string(today - value_days) # convert the operator: # book with age > value have a date < value_date operator_map = {'>': '<', '>=': '<=', '<': '>', '<=': '>='} new_op = operator_map.get(operator, operator) return [('date_release', new_op, value_date)]
def test_leave(self): def to_tuple(interval): return (interval.start_datetime, interval.end_datetime) # Here we test if the leaves are correctly computed in the case our user is in UTC # NB: Beware of winter/spring time work_no_tz = [to_tuple(x) for x in self.calendar._get_day_leave_intervals(Date.from_string('2018-12-25'), time(0), time(23, 59, 59), self.resource1_id)] self.assertEqual(work_no_tz[0], (Datetime.from_string('2018-12-25 08:00:00'), Datetime.from_string('2018-12-25 16:00:00'))) work_user_tz = [to_tuple(x) for x in self.calendar._get_day_leave_intervals(Date.from_string('2018-05-01'), time(0), time(23, 59, 59), self.resource1_id)] self.assertEqual(work_user_tz[0], (Datetime.from_string('2018-05-01 08:00:00'), Datetime.from_string('2018-05-01 16:00:00'))) work_spec = [to_tuple(x) for x in self.calendar._get_day_leave_intervals(Date.from_string('2018-04-06'), time(0), time(23, 59, 59), self.resource1_id)] self.assertEqual(work_spec[0], (Datetime.from_string('2018-04-06 08:00:00'), Datetime.from_string('2018-04-06 13:00:00')))
def test_calendar_next_day(self): # Test: next day: next day after day1 is day4 date = self.calendar._get_next_work_day(day_date=Date.from_string('2013-02-12')) self.assertEqual(date, self.date2.date()) # Test: next day: next day after day4 is (day1+7) date = self.calendar._get_next_work_day(day_date=Date.from_string('2013-02-15')) self.assertEqual(date, self.date1.date() + relativedelta(days=7)) # Test: next day: next day after day4+1 is (day1+7) date = self.calendar._get_next_work_day(day_date=Date.from_string('2013-02-15') + relativedelta(days=1)) self.assertEqual(date, self.date1.date() + relativedelta(days=7)) # Test: next day: next day after day1-1 is day1 date = self.calendar._get_next_work_day(day_date=Date.from_string('2013-02-12') + relativedelta(days=-1)) self.assertEqual(date, self.date1.date())
def test_calendar_previous_day(self): # Test: previous day: previous day before day1 is (day4-7) date = self.calendar._get_previous_work_day(day_date=Date.from_string('2013-02-12')) self.assertEqual(date, self.date2.date() + relativedelta(days=-7)) # Test: previous day: previous day before day4 is day1 date = self.calendar._get_previous_work_day(day_date=Date.from_string('2013-02-15')) self.assertEqual(date, self.date1.date()) # Test: previous day: previous day before day4+1 is day4 date = self.calendar._get_previous_work_day(day_date=Date.from_string('2013-02-15') + relativedelta(days=1)) self.assertEqual(date, self.date2.date()) # Test: previous day: previous day before day1-1 is (day4-7) date = self.calendar._get_previous_work_day(day_date=Date.from_string('2013-02-12') + relativedelta(days=-1)) self.assertEqual(date, self.date2.date() + relativedelta(days=-7))
def test_leaves_timezones(self): self.env.user.tz = 'US/Alaska' # UTC-9 def to_tuple(interval): return (interval.start_datetime, interval.end_datetime) # Here we test if the leaves are correctly computed in the case our user is in tz Alaska # NB: Beware of winter/spring time work_no_tz = [to_tuple(x) for x in self.calendar._get_day_leave_intervals(Date.from_string('2018-12-25'), time(0), time(23, 59, 59), self.resource1_id)] self.assertEqual(work_no_tz[0], (Datetime.from_string('2018-12-25 17:00:00'), Datetime.from_string('2018-12-26 01:00:00'))) work_user_tz = [to_tuple(x) for x in self.calendar._get_day_leave_intervals(Date.from_string('2018-05-01'), time(0), time(23, 59, 59), self.resource1_id)] self.assertEqual(work_user_tz[0], (Datetime.from_string('2018-05-01 16:00:00'), Datetime.from_string('2018-05-02 00:00:00'))) work_spec = [to_tuple(x) for x in self.calendar._get_day_leave_intervals(Date.from_string('2018-04-06'), time(0), time(23, 59, 59), self.resource1_id)] self.assertEqual(work_spec[0], (Datetime.from_string('2018-04-06 16:00:00'), Datetime.from_string('2018-04-06 21:00:00')))
def _get_car_atn(self, acquisition_date, car_value, fuel_type, co2): # Compute the correction coefficient from the age of the car now = Date.today() if acquisition_date: number_of_month = ((now.year - acquisition_date.year) * 12.0 + now.month - acquisition_date.month + int(bool(now.day - acquisition_date.day + 1))) if number_of_month <= 12: age_coefficient = 1.00 elif number_of_month <= 24: age_coefficient = 0.94 elif number_of_month <= 36: age_coefficient = 0.88 elif number_of_month <= 48: age_coefficient = 0.82 elif number_of_month <= 60: age_coefficient = 0.76 else: age_coefficient = 0.70 car_value = car_value * age_coefficient # Compute atn value from corrected car_value magic_coeff = 6.0 / 7.0 # Don't ask me why if fuel_type == 'electric': atn = 0.0 else: if fuel_type in ['diesel', 'hybrid']: reference = 87.0 else: reference = 105.0 if co2 <= reference: atn = car_value * max(0.04, (0.055 - 0.001 * (reference - co2))) * magic_coeff else: atn = car_value * min(0.18, (0.055 + 0.001 * (co2 - reference))) * magic_coeff return max(1280, atn) / 12.0
def test_calendar_working_day_intervals_leaves_generic(self): # Test: day0 with leaves outside range: 1 interval intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-12'), start_time=time(7, 0, 0), compute_leaves=True) self.assertEqual(len(intervals), 1) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-12 08:00:00'), Datetime.from_string('2013-02-12 16:00:00'))) # Test: day0 with leaves: 2 intervals because of leave between 9 and 12, ending at 15:45:30 intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-19'), start_time=time(8, 15, 0), end_time=time(15, 45, 30), compute_leaves=True) self.assertEqual(len(intervals), 2) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-19 08:15:00'), Datetime.from_string('2013-02-19 09:00:00'))) self.assertEqual(intervals[1][:2], (Datetime.from_string('2013-02-19 12:00:00'), Datetime.from_string('2013-02-19 15:45:30'))) self.assertEqual(intervals[0][2]['attendances'], self.att_1) self.assertEqual(intervals[0][2]['leaves'], self.leave1) self.assertEqual(intervals[1][2]['attendances'], self.att_1) self.assertEqual(intervals[0][2]['leaves'], self.leave1)
def test_calendar_working_day_intervals_leaves_resource(self): # Test: day1+14 on leave, with resource leave computation intervals = self.calendar._get_day_work_intervals( Date.from_string('2013-02-26'), start_time=time(7, 0, 0), compute_leaves=True, resource_id=self.resource1_id ) # Result: nothing, because on leave self.assertEqual(len(intervals), 0)
def _get_archive_groups(self, model, domain=None, fields=None, groupby="create_date", order="create_date desc"): if not model: return [] if domain is None: domain = [] if fields is None: fields = ["name", "create_date"] groups = [] for group in request.env[model]._read_group_raw(domain, fields=fields, groupby=groupby, orderby=order): dates, label = group[groupby] date_begin, date_end = dates.split("/") groups.append( { "date_begin": Date.to_string(Date.from_string(date_begin)), "date_end": Date.to_string(Date.from_string(date_end)), "name": label, "item_count": group[groupby + "_count"], } ) return groups
def test_calendar_working_day_intervals_no_leaves(self): # Test: day0 without leaves: 1 interval intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-12'), start_time=time(9, 8, 7)) self.assertEqual(len(intervals), 1) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-12 09:08:07'), Datetime.from_string('2013-02-12 16:00:00'))) self.assertEqual(intervals[0][2]['attendances'], self.att_1) # Test: day1, beginning at 10:30 -> work from 10:30 (arrival) until 16:00 intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-19'), start_time=time(10, 30, 0)) self.assertEqual(len(intervals), 1) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-19 10:30:00'), Datetime.from_string('2013-02-19 16:00:00'))) self.assertEqual(intervals[0][2]['attendances'], self.att_1) # Test: day3 without leaves: 2 interval intervals = self.calendar._get_day_work_intervals(Date.from_string('2013-02-15'), start_time=time(10, 11, 12)) self.assertEqual(len(intervals), 2) self.assertEqual(intervals[0][:2], (Datetime.from_string('2013-02-15 10:11:12'), Datetime.from_string('2013-02-15 13:00:00'))) self.assertEqual(intervals[1][:2], (Datetime.from_string('2013-02-15 16:00:00'), Datetime.from_string('2013-02-15 23:00:00'))) self.assertEqual(intervals[0][2]['attendances'], self.att_2) self.assertEqual(intervals[1][2]['attendances'], self.att_3)
def setUp(self): super(TestPayslipBase, self).setUp() # Some salary rules references self.hra_rule_id = self.ref('hr_payroll.hr_salary_rule_houserentallowance1') self.conv_rule_id = self.ref('hr_payroll.hr_salary_rule_convanceallowance1') self.prof_tax_rule_id = self.ref('hr_payroll.hr_salary_rule_professionaltax1') self.pf_rule_id = self.ref('hr_payroll.hr_salary_rule_providentfund1') self.mv_rule_id = self.ref('hr_payroll.hr_salary_rule_meal_voucher') self.comm_rule_id = self.ref('hr_payroll.hr_salary_rule_sales_commission') # I create a new employee "Richard" self.richard_emp = self.env['hr.employee'].create({ 'name': 'Richard', 'gender': 'male', 'birthday': '1984-05-01', 'country_id': self.ref('base.be'), 'department_id': self.ref('hr.dep_rd') }) # I create a salary structure for "Software Developer" self.developer_pay_structure = self.env['hr.payroll.structure'].create({ 'name': 'Salary Structure for Software Developer', 'code': 'SD', 'company_id': self.ref('base.main_company'), 'rule_ids': [(4, self.hra_rule_id), (4, self.conv_rule_id), (4, self.prof_tax_rule_id), (4, self.pf_rule_id), (4, self.mv_rule_id), (4, self.comm_rule_id)], }) # I create a contract for "Richard" self.env['hr.contract'].create({ 'date_end': Date.to_string((datetime.now() + timedelta(days=365))), 'date_start': Date.today(), 'name': 'Contract for Richard', 'wage': 5000.0, 'type_id': self.ref('hr_contract.hr_contract_type_emp'), 'employee_id': self.richard_emp.id, 'struct_id': self.developer_pay_structure.id, })
def test_account_budget(self): # Creating a crossovered.budget record budget = self.env["crossovered.budget"].create( { "date_from": Date.from_string("%s-01-01" % (datetime.datetime.now().year + 1)), "date_to": Date.from_string("%s-12-31" % (datetime.datetime.now().year + 1)), "name": "Budget %s" % (datetime.datetime.now().year + 1), "state": "draft", } ) # I created two different budget lines # Modifying a crossovered.budget record self.env["crossovered.budget.lines"].create( { "crossovered_budget_id": budget.id, "analytic_account_id": self.ref("analytic.analytic_partners_camp_to_camp"), "date_from": Date.from_string("%s-01-01" % (datetime.datetime.now().year + 1)), "date_to": Date.from_string("%s-12-31" % (datetime.datetime.now().year + 1)), "general_budget_id": self.account_budget_post_purchase0.id, "planned_amount": 10000.0, } ) self.env["crossovered.budget.lines"].create( { "crossovered_budget_id": budget.id, "analytic_account_id": self.ref("analytic.analytic_our_super_product"), "date_from": Date.from_string("%s-09-01" % (datetime.datetime.now().year + 1)), "date_to": Date.from_string("%s-09-30" % (datetime.datetime.now().year + 1)), "general_budget_id": self.account_budget_post_sales0.id, "planned_amount": 400000.0, } ) # I check that Initially Budget is in "draft" state self.assertEqual(budget.state, "draft") # I pressed the confirm button to confirm the Budget # Performing an action confirm on module crossovered.budget budget.action_budget_confirm() # I check that budget is in "Confirmed" state self.assertEqual(budget.state, "confirm") # I pressed the validate button to validate the Budget # Performing an action validate on module crossovered.budget budget.action_budget_validate() # I check that budget is in "Validated" state self.assertEqual(budget.state, "validate") # I pressed the done button to set the Budget to "Done" state # Performing an action done on module crossovered.budget budget.action_budget_done() # I check that budget is in "done" state self.assertEqual(budget.state, "done")
def test_theoritical_amount_with_paid_date(self): test_list = [ (str(datetime.now().year) + '-01-01', 0), (str(datetime.now().year) + '-01-02', 0), (str(datetime.now().year) + '-09-08', 0), (str(datetime.now().year) + '-09-09', 0), (str(datetime.now().year) + '-09-10', -364), (str(self.last_day_of_budget.date()), -364), ] for date, expected_amount in test_list: _logger.info("Checking theoritical amount for the date: " + date) self.mock_date.today.return_value = Date.from_string(date) self.assertAlmostEqual(self.paid_date_line.theoritical_amount, expected_amount) #invalidate the cache of the budget lines to recompute the theoritical amount at next iteration self.paid_date_line.invalidate_cache()
def setUp(self): super(TestTheoreticalAmount, self).setUp() #create the budgetary position user_type_id = self.ref('account.data_account_type_revenue') tag_id = self.ref('account.account_tag_operating') account_rev = self.env['account.account'].create({ 'code': 'Y2020', 'name': 'Budget - Test Revenue Account', 'user_type_id': user_type_id, 'tag_ids': [(4, tag_id, 0)] }) buget_post = self.env['account.budget.post'].create({ 'name': 'Sales', 'account_ids': [(4, account_rev.id, 0)], }) #create the budget and budget lines first_january = Datetime.now().replace(day=1, month=1) self.last_day_of_budget = first_january + timedelta(days=364) # will be 30th of December or 31th in case of leap year date_from = first_january.date() date_to = self.last_day_of_budget.date() crossovered_budget = self.env['crossovered.budget'].create({ 'name': 'test budget name', 'date_from': date_from, 'date_to': date_to, }) crossovered_budget_line_obj = self.env['crossovered.budget.lines'] self.line = crossovered_budget_line_obj.create({ 'crossovered_budget_id': crossovered_budget.id, 'general_budget_id': buget_post.id, 'date_from': date_from, 'date_to': date_to, 'planned_amount': -364, }) self.paid_date_line = crossovered_budget_line_obj.create({ 'crossovered_budget_id': crossovered_budget.id, 'general_budget_id': buget_post.id, 'date_from': date_from, 'date_to': date_to, 'planned_amount': -364, 'paid_date': Date.today().replace(day=9, month=9), }) self.patcher = patch('odoo.addons.account_budget.models.account_budget.fields.Date', wraps=Date) self.mock_date = self.patcher.start()
def test_account_budget(self): # Creating a crossovered.budget record budget = self.env['crossovered.budget'].create({ 'date_from': Date.from_string('%s-01-01' % (datetime.datetime.now().year + 1)), 'date_to': Date.from_string('%s-12-31' % (datetime.datetime.now().year + 1)), 'name': 'Budget %s' % (datetime.datetime.now().year + 1), 'state': 'draft' }) # I created two different budget lines # Modifying a crossovered.budget record self.env['crossovered.budget.lines'].create({ 'crossovered_budget_id': budget.id, 'analytic_account_id': self.ref('analytic.analytic_partners_camp_to_camp'), 'date_from': Date.from_string('%s-01-01' % (datetime.datetime.now().year + 1)), 'date_to': Date.from_string('%s-12-31' % (datetime.datetime.now().year + 1)), 'general_budget_id': self.account_budget_post_purchase0.id, 'planned_amount': 10000.0, }) self.env['crossovered.budget.lines'].create({ 'crossovered_budget_id': budget.id, 'analytic_account_id': self.ref('analytic.analytic_our_super_product'), 'date_from': Date.from_string('%s-09-01' % (datetime.datetime.now().year + 1)), 'date_to': Date.from_string('%s-09-30' % (datetime.datetime.now().year + 1)), 'general_budget_id': self.account_budget_post_sales0.id, 'planned_amount': 400000.0, }) # I check that Initially Budget is in "draft" state self.assertEqual(budget.state, 'draft') # I pressed the confirm button to confirm the Budget # Performing an action confirm on module crossovered.budget budget.action_budget_confirm() # I check that budget is in "Confirmed" state self.assertEqual(budget.state, 'confirm') # I pressed the validate button to validate the Budget # Performing an action validate on module crossovered.budget budget.action_budget_validate() # I check that budget is in "Validated" state self.assertEqual(budget.state, 'validate') # I pressed the done button to set the Budget to "Done" state # Performing an action done on module crossovered.budget budget.action_budget_done() # I check that budget is in "done" state self.assertEqual(budget.state, 'done')
def test_payslip_generation_with_leave(self): # /!\ this is a week day => it exists an calendar attendance at this time start = self.to_datetime_tz('2015-11-02 10:00:00', tz=pytz.utc) end = self.to_datetime_tz('2015-11-02 17:00:00', tz=pytz.utc) leave_benef = self.env['hr.benefit'].create({ 'name': '1leave', 'employee_id': self.richard_emp.id, 'contract_id': self.richard_emp.contract_id.id, 'benefit_type_id': self.benefit_type_leave.id, 'date_start': start, 'date_stop': end, }) leave_benef.action_validate(leave_benef.ids) payslip_wizard = self.env['hr.payslip.employees'].create({'employee_ids': [(4, self.richard_emp.id)]}) payslip_wizard.with_context({'default_date_start': Date.to_string(start), 'default_date_end': Date.to_string(end)}).compute_sheet() payslip = self.env['hr.payslip'].search([('employee_id', '=', self.richard_emp.id)]) work_line = payslip.worked_days_line_ids.filtered(lambda l: l.code == 'WORK100') # From default calendar.attendance leave_line = payslip.worked_days_line_ids.filtered(lambda l: l.code == 'LEAVE100') self.assertTrue(work_line, "It should have a work line in the payslip") self.assertTrue(leave_line, "It should have a leave line in the payslip") self.assertEqual(work_line.number_of_hours, 3.0, "It should have 3 hours of work") self.assertEqual(leave_line.number_of_hours, 5.0, "It should have 5 hours of leave")
def test_duplicate_benefit_to_attendance(self): start = self.to_datetime_tz('2015-11-01 09:00:00') end = self.to_datetime_tz('2015-11-03 18:00:00') # Benefit (not leave) should be split in three attendance benef = self.env['hr.benefit'].create({ 'name': '1', 'employee_id': self.richard_emp.id, 'benefit_type_id': self.benefit_type.id, 'contract_id': self.richard_emp.contract_id.id, 'date_start': start, 'date_stop': end, }) benef._duplicate_to_calendar() attendance_nb = self.env['resource.calendar.attendance'].search_count([ ('date_from', '>=', start.date()), ('date_to', '<=', end.date()) ]) self.assertEqual(attendance_nb, 3, "It should create one calendar attendance per day") self.assertTrue(self.env['resource.calendar.attendance'].search([ ('date_from', '=', Date.to_date('2015-11-01')), ('date_to', '=', Date.to_date('2015-11-01')), ('hour_from', '=', 9.0), ('hour_to', '>=', 23.9) ])) self.assertTrue(self.env['resource.calendar.attendance'].search([ ('date_from', '=', Date.to_date('2015-11-02')), ('date_to', '=', Date.to_date('2015-11-02')), ('hour_from', '=', 0.0), ('hour_to', '>=', 23.9) ])) self.assertTrue(self.env['resource.calendar.attendance'].search([ ('date_from', '=', Date.to_date('2015-11-03')), ('date_to', '=', Date.to_date('2015-11-03')), ('hour_from', '=', 0.0), ('hour_to', '=', 18.0) ]))
def dump_date(self, value, write): value = Date.to_string(value) self.dump_unicode(value, write)
def test_leaves_other(self): # Here we test if setting the value to other has the effect intended leave = self.calendar._get_day_leave_intervals(Date.from_string('2013-02-26'), time(0), time(23, 59, 59), self.resource1_id, [('time_type', '=', 'other')]) self.assertEqual(len(leave), 0, "When asking for other should ignore leaves") leave = self.calendar._get_day_leave_intervals(Date.from_string('2013-02-15'), time(0), time(23, 59, 59), self.resource1_id, [('time_type', '=', 'other')]) self.assertEqual(len(leave), 2, "When asking for other should compute others")
def test_account_budget(self): # In order to check account budget module in Odoo I created a budget with few budget positions # Checking if the budgetary positions have accounts or not if not self.account_budget_post_sales0.account_ids: a_sale = self.env['account.account'].create({ 'name': 'Product Sales - (test)', 'code': 'X2020', 'user_type_id': self.ref('account.data_account_type_revenue'), 'tag_ids': [(6, 0, [self.ref('account.account_tag_operating')])], }) self.account_budget_post_sales0.write({'account_ids': [(6, 0, [a_sale.id])]}) if not self.account_budget_post_purchase0.account_ids: a_expense = self.env['account.account'].create({ 'name': 'Expense - (test)', 'code': 'X2120', 'user_type_id': self.ref('account.data_account_type_expenses'), 'tag_ids': [(6, 0, [self.ref('account.account_tag_operating')])], }) self.account_budget_post_purchase0.write({'account_ids': [(6, 0, [a_expense.id])]}) # Creating a crossovered.budget record budget = self.env['crossovered.budget'].create({ 'date_from': Date.from_string('%s-01-01' % (datetime.datetime.now().year + 1)), 'date_to': Date.from_string('%s-12-31' % (datetime.datetime.now().year + 1)), 'name': 'Budget %s' % (datetime.datetime.now().year + 1), 'state': 'draft' }) # I created two different budget lines # Modifying a crossovered.budget record self.env['crossovered.budget.lines'].create({ 'crossovered_budget_id': budget.id, 'analytic_account_id': self.ref('analytic.analytic_partners_camp_to_camp'), 'date_from': Date.from_string('%s-01-01' % (datetime.datetime.now().year + 1)), 'date_to': Date.from_string('%s-12-31' % (datetime.datetime.now().year + 1)), 'general_budget_id': self.account_budget_post_purchase0.id, 'planned_amount': 10000.0, }) self.env['crossovered.budget.lines'].create({ 'crossovered_budget_id': budget.id, 'analytic_account_id': self.ref('analytic.analytic_our_super_product'), 'date_from': Date.from_string('%s-09-01' % (datetime.datetime.now().year + 1)), 'date_to': Date.from_string('%s-09-30' % (datetime.datetime.now().year + 1)), 'general_budget_id': self.account_budget_post_sales0.id, 'planned_amount': 400000.0, }) # I check that Initially Budget is in "draft" state self.assertEqual(budget.state, 'draft') # I pressed the confirm button to confirm the Budget # Performing a workflow action confirm on module crossovered.budget budget.signal_workflow('confirm') # I check that budget is in "Confirmed" state self.assertEqual(budget.state, 'confirm') # I pressed the validate button to validate the Budget # Performing a workflow action validate on module crossovered.budget budget.signal_workflow('validate') # I check that budget is in "Validated" state self.assertEqual(budget.state, 'validate') # I pressed the done button to set the Budget to "Done" state # Performing a workflow action done on module crossovered.budget budget.signal_workflow('done') # I check that budget is in "done" state self.assertEqual(budget.state, 'done')