Esempio n. 1
0
    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"
        )
Esempio n. 2
0
 def check_apply_plan(self, key, value, modulus, difference):
     plan = self.env['medical.guard.plan'].create({
         'location_id': self.center.id,
         'product_id': self.product.id,
         'start_time': 0,
         'delay': 1,
         'weekday': '*',
         'monthday': '*',
         'month': '*'
     })
     self.assertFalse(self.env['medical.guard'].search([
         ('plan_guard_id', '=', plan.id)
     ]))
     plan.write({key: ((value+1) % modulus) + difference})
     self.env['medical.guard.plan.apply'].create({
         'start_date': Date.today(),
         'end_date': Date.to_string(
             Date.from_string(Date.today())),
     }).run()
     self.assertFalse(self.env['medical.guard'].search([
         ('plan_guard_id', '=', plan.id)
     ]))
     plan.write({key: value})
     self.env['medical.guard.plan.apply'].create({
         'start_date': Date.today(),
         'end_date': Date.to_string(
             Date.from_string(Date.today())),
     }).run()
     self.assertTrue(self.env['medical.guard'].search([
         ('plan_guard_id', '=', plan.id)
     ]))
    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
Esempio n. 4
0
 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)
Esempio n. 5
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_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)
Esempio n. 7
0
    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)
Esempio n. 8
0
 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 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"])
Esempio n. 10
0
 def check_apply_plan(self, key, value, modulus, difference):
     plan = self.env["medical.guard.plan"].create(
         {
             "location_id": self.center.id,
             "product_id": self.product.id,
             "start_time": 0,
             "delay": 1,
             "weekday": "*",
             "monthday": "*",
             "month": "*",
         }
     )
     self.assertFalse(
         self.env["medical.guard"].search([("plan_guard_id", "=", plan.id)])
     )
     plan.write({key: ((value + 1) % modulus) + difference})
     self.env["medical.guard.plan.apply"].create(
         {
             "start_date": Date.today(),
             "end_date": Date.to_string(Date.from_string(Date.today())),
         }
     ).run()
     self.assertFalse(
         self.env["medical.guard"].search([("plan_guard_id", "=", plan.id)])
     )
     plan.write({key: value})
     self.env["medical.guard.plan.apply"].create(
         {
             "start_date": Date.today(),
             "end_date": Date.to_string(Date.from_string(Date.today())),
         }
     ).run()
     self.assertTrue(
         self.env["medical.guard"].search([("plan_guard_id", "=", plan.id)])
     )
Esempio n. 11
0
    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
Esempio n. 12
0
 def setUpClass(cls, chart_template_ref=None):
     super().setUpClass(chart_template_ref=chart_template_ref)
     cls.AccountObj = cls.env["account.account"]
     cls.InvoiceObj = cls.env["account.move"]
     cls.JournalObj = cls.env["account.journal"]
     cls.MoveObj = cls.env["account.move"]
     cls.TaxObj = cls.env["account.tax"]
     cls.JournalLedgerReportWizard = cls.env["journal.ledger.report.wizard"]
     cls.JournalLedgerReport = cls.env[
         "report.account_financial_report.journal_ledger"]
     cls.company = cls.company_data["company"]
     cls.company.account_sale_tax_id = False
     cls.company.account_purchase_tax_id = False
     today = datetime.today()
     last_year = today - relativedelta(years=1)
     cls.previous_fy_date_start = Date.to_string(
         last_year.replace(month=1, day=1))
     cls.previous_fy_date_end = Date.to_string(
         last_year.replace(month=12, day=31))
     cls.fy_date_start = Date.to_string(today.replace(month=1, day=1))
     cls.fy_date_end = Date.to_string(today.replace(month=12, day=31))
     cls.receivable_account = cls.company_data["default_account_receivable"]
     cls.income_account = cls.company_data["default_account_revenue"]
     cls.expense_account = cls.company_data["default_account_expense"]
     cls.payable_account = cls.company_data["default_account_payable"]
     cls.journal_sale = cls.company_data["default_journal_sale"]
     cls.journal_purchase = cls.company_data["default_journal_purchase"]
     cls.tax_15_s = cls.company_data["default_tax_sale"]
     cls.tax_15_s.sequence = 30
     cls.tax_15_s.amount = 15.0
     cls.tax_15_s.amount_type = "percent"
     cls.tax_15_s.include_base_amount = False
     cls.tax_15_s.type_tax_use = "sale"
     cls.tax_20_s = cls.tax_15_s.copy({
         "sequence": 30,
         "name": "Tax 20.0% (Percentage of Price)",
         "amount": 20.0,
         "amount_type": "percent",
         "include_base_amount": False,
         "type_tax_use": "sale",
     })
     cls.tax_15_p = cls.company_data["default_tax_purchase"]
     cls.tax_15_p.sequence = 30
     cls.tax_15_p.amount = 15.0
     cls.tax_15_p.amount_type = "percent"
     cls.tax_15_p.include_base_amount = False
     cls.tax_15_p.type_tax_use = "purchase"
     cls.tax_20_p = cls.tax_15_p.copy({
         "sequence": 30,
         "name": "Tax 20.0% (Percentage of Price)",
         "amount": 20.0,
         "amount_type": "percent",
         "include_base_amount": False,
         "type_tax_use": "purchase",
     })
     cls.partner_2 = cls.env.ref("base.res_partner_2")
Esempio n. 13
0
 def test_locking(self):
     vals = {
         'journal_ids': [(4, self.cust_invoices_journal.id, 0)],
         'date_start': Date.to_string(datetime.now() - timedelta(days=335)),
         'date_end': Date.to_string(datetime.now() + timedelta(days=30)),
     }
     lock_wiz = self.env['lock.account.move'].create(vals)
     lock_wiz.lock_move({})
     for move in self.entries:
         self.assertTrue(move.locked)
    def test_program_rules_one_date(self):
        # Test case: Based on the validity dates and the number of allowed uses

        # VFE NOTE the .rule_id is necessary to ensure the dates constraints doesn't raise
        # because the orm applies the related inverse one by one, raising the constraint...
        self.immediate_promotion_program.rule_id.write({
            'rule_date_from': False,
            'rule_date_to': Date.to_string((datetime.now() - timedelta(days=2))),
        })

        order = self.empty_order
        order.write({'order_line': [
            (0, False, {
                'product_id': self.product_A.id,
                'name': '1 Product A',
                'product_uom': self.uom_unit.id,
                'product_uom_qty': 1.0,
            }),
            (0, False, {
                'product_id': self.product_B.id,
                'name': '2 Product B',
                'product_uom': self.uom_unit.id,
                'product_uom_qty': 1.0,
            })
        ]})
        order.recompute_coupon_lines()
        self.assertNotIn(self.immediate_promotion_program, order._get_applicable_programs())
        self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied we're not between the validity dates")

        self.immediate_promotion_program.rule_id.write({
            'rule_date_from': Date.to_string((datetime.now() + timedelta(days=1))),
            'rule_date_to': False,
        })
        order.recompute_coupon_lines()
        self.assertNotIn(self.immediate_promotion_program, order._get_applicable_programs())
        self.assertEqual(len(order.order_line.ids), 2, "The promo offert shouldn't have been applied we're not between the validity dates")

        self.immediate_promotion_program.rule_id.write({
            'rule_date_from': False,
            'rule_date_to': Date.to_string((datetime.now() + timedelta(days=2))),
        })
        order.recompute_coupon_lines()
        self.assertIn(self.immediate_promotion_program, order._get_applicable_programs())
        self.assertEqual(len(order.order_line.ids), 3, "The promo offer should have been applied as we're between the validity dates")

        self.immediate_promotion_program.rule_id.write({
            'rule_date_from': Date.to_string((datetime.now() - timedelta(days=1))),
            'rule_date_to': False,
        })
        order.recompute_coupon_lines()
        self.assertIn(self.immediate_promotion_program, order._get_applicable_programs())
        self.assertEqual(len(order.order_line.ids), 3, "The promo offer should have been applied as we're between the validity dates")
    def test_service(self):
        # kept as example
        # useful if you need to change data in database and check db type

        result = self.sr_service.get(self.demo_request_1.get_api_external_id())
        self.assertEquals(self.demo_request_1_dict, result)

        all_sr = self.sr_service.search()
        self.assertTrue(all_sr)

        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))

        date_sr = self.sr_service.search(date_from=date_from, date_to=date_to)
        self.assertTrue(date_sr)
Esempio n. 16
0
    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,
        })
Esempio n. 17
0
    def _to_dict(self, sr):
        sr.ensure_one()

        if sr.capital_release_request:
            invoice_ids = [
                invoice.get_api_external_id()
                for invoice in sr.capital_release_request
            ]
        else:
            invoice_ids = []

        share_product = sr.share_product_id.product_tmpl_id
        return {
            "id": sr.get_api_external_id(),
            "name": sr.name,
            "email": sr.email,
            "state": sr.state,
            "date": Date.to_string(sr.date),
            "ordered_parts": sr.ordered_parts,
            "share_product": self._one_to_many_to_dict(share_product),
            "address": {
                "street": sr.address,
                "zip_code": sr.zip_code,
                "city": sr.city,
                "country": sr.country_id.code,
            },
            "lang": sr.lang,
            "capital_release_request": invoice_ids,
        }
    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)
Esempio n. 19
0
    def test_crm_lead_pls_update(self):
        """ We test here that the wizard for updating probabilities from settings
            is getting correct value from config params and after updating values
            from the wizard, the config params are correctly updated
        """
        # Set the PLS config
        frequency_fields = self.env['crm.lead.scoring.frequency.field'].search([])
        pls_fields_str = ','.join(frequency_fields.mapped('field_id.name'))
        pls_start_date_str = "2021-01-01"
        IrConfigSudo = self.env['ir.config_parameter'].sudo()
        IrConfigSudo.set_param("crm.pls_start_date", pls_start_date_str)
        IrConfigSudo.set_param("crm.pls_fields", pls_fields_str)

        date_to_update = "2021-02-02"
        fields_to_remove = frequency_fields.filtered(lambda f: f.field_id.name in ['source_id', 'lang_id'])
        fields_after_updation_str = ','.join((frequency_fields - fields_to_remove).mapped('field_id.name'))

        # Check that wizard to update lead probabilities has correct value set by default
        pls_update_wizard = Form(self.env['crm.lead.pls.update'])
        with pls_update_wizard:
            self.assertEqual(Date.to_string(pls_update_wizard.pls_start_date), pls_start_date_str, 'Correct date is taken from config')
            self.assertEqual(','.join([f.field_id.name for f in pls_update_wizard.pls_fields]), pls_fields_str, 'Correct fields are taken from config')
            # Update the wizard values and check that config values and probabilities are updated accordingly
            pls_update_wizard.pls_start_date =  date_to_update
            for field in fields_to_remove:
                pls_update_wizard.pls_fields.remove(field.id)

        pls_update_wizard0 = pls_update_wizard.save()
        pls_update_wizard0.action_update_crm_lead_probabilities()

        # Config params should have been updated
        self.assertEqual(IrConfigSudo.get_param("crm.pls_start_date"), date_to_update, 'Correct date is updated in config')
        self.assertEqual(IrConfigSudo.get_param("crm.pls_fields"), fields_after_updation_str, 'Correct fields are updated in config')
Esempio n. 20
0
    def test_payslip_generation_with_extra_work(self):
        # /!\ this is in the weekend (Sunday) => no calendar attendance at this time
        start = datetime(2015, 11, 1, 10, 0, 0)
        end = datetime(2015, 11, 1, 17, 0, 0)
        work_entries = self.richard_emp.contract_id._generate_work_entries(
            start, end + relativedelta(days=2))
        work_entries.action_validate()

        work_entry = self.env['hr.work.entry'].create({
            'name':
            'Extra',
            'employee_id':
            self.richard_emp.id,
            'contract_id':
            self.richard_emp.contract_id.id,
            'work_entry_type_id':
            self.work_entry_type.id,
            'date_start':
            start,
            'date_stop':
            end,
        })
        work_entry.action_validate()
        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.work_entry_type_id == self.env.ref(
                'hr_work_entry.work_entry_type_attendance')
        )  # From default calendar.attendance
        leave_line = payslip.worked_days_line_ids.filtered(
            lambda l: l.work_entry_type_id == self.work_entry_type)

        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
Esempio n. 21
0
File: main.py Progetto: anybox/odoo
 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
Esempio n. 22
0
 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 _to_dict(self, payment):
     return {
         "id": payment.get_api_external_id(),
         "journal": self._one_to_many_to_dict(payment.journal_id),
         "invoice": self._one_to_many_to_dict(payment.invoice_ids),
         "payment_date": Date.to_string(payment.payment_date),
         "amount": payment.amount,
         "communication": payment.communication,
     }
Esempio n. 24
0
 def _inverse_age(self):
     today = fDate.from_string(fDate.context_today(self))
     for book in self.filtered('date_release'):
         try:
             d = today - timedelta(days=book.age_days)
             book.date_release = fDate.to_string(d)
         except (IOError, OSError) as exc:
             message = _('Unable to inverse age') % exc
             raise UserError(message)
Esempio n. 25
0
    def setUp(self):
        res = super().setUp()
        collection = _PseudoCollection("emc.services", self.env)
        emc_services_env = WorkContext(model_name="rest.service.registration",
                                       collection=collection)
        self.ai_service = emc_services_env.component(usage="invoice")

        self.share_type_A = self.browse_ref(
            "easy_my_coop.product_template_share_type_1_demo")
        self._capital_release_create()

        today = Date.to_string(Date.today())
        self.demo_invoice_dict = {
            "id":
            1,
            "name":
            "Capital Release Example",
            "partner": {
                "id": 1,
                "name": "Catherine des Champs"
            },
            "account": {
                "id": 1,
                "name": "Cooperators"
            },
            "journal": {
                "id": 1,
                "name": "Subscription Journal"
            },
            "subscription_request": {},
            "state":
            "open",
            "date":
            today,
            "date_invoice":
            today,
            "date_due":
            today,
            "type":
            "out_invoice",
            "invoice_lines": [{
                "name": "Share Type A",
                "product": {
                    "id": 1,
                    "name": "Part A - Founder"
                },
                "price_unit": 100.0,
                "quantity": 2.0,
                "account": {
                    "id": 2,
                    "name": "Equity"
                },
            }],
        }
        return res
Esempio n. 26
0
 def _search_age(self, operator, value):
     try:
         today = fDate.from_string(fDate.context_today(self))
         value_days = timedelta(days=value)
         value_date = fDate.to_string(today - value_days)
         operator_map = {'>': '<', '>=': '<=', '<': '>', '<=': '>=', }
         new_op = operator_map.get(operator, operator)
         return [('date_release', new_op, value_date)]
     except (IOError, OSError) as exc:
         message = _('Unable to search by age') % exc
         raise UserError(message)
Esempio n. 27
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
Esempio n. 28
0
    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
Esempio n. 29
0
 def _get_archive_groups_sudo(
     self,
     model,
     domain=None,
     fields=None,
     groupby="create_date",
     order="create_date desc",
 ):
     """Same as the one from website_portal_v10 except that it runs
     in root.
     """
     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(domain,
                                                        fields=fields,
                                                        groupby=groupby,
                                                        orderby=order)):
         label = group[groupby]
         date_begin = date_end = None
         for leaf in group["__domain"]:
             if leaf[0] == groupby:
                 if leaf[1] == ">=":
                     date_begin = leaf[2]
                 elif leaf[1] == "<":
                     date_end = leaf[2]
         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
Esempio n. 30
0
    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")
Esempio n. 31
0
 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(template.employee_id.tz)
         if not tz:
             tz = pytz.UTC
         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)})
             mail_template = self.env.ref(
                 'danfresh_hr_update_Removed.mail_template_notification_hr_expense'
             )
             self.env['mail.template'].browse(mail_template.id).send_mail(
                 template.id, force_send=True, raise_exception=True)
    def test_01_test_total(self):
        today_date = Date.today()
        last_year_date = Date.to_string(datetime.today() -
                                        relativedelta(years=1))

        move1 = self._add_move(today_date, self.journal_sale, 0, 100, 100, 0)
        move2 = self._add_move(last_year_date, self.journal_sale, 0, 100, 100,
                               0)

        wiz = self.JournalLedgerReportWizard.create({
            "date_from":
            self.fy_date_start,
            "date_to":
            self.fy_date_end,
            "company_id":
            self.company.id,
            "journal_ids": [(6, 0, self.journal_sale.ids)],
            "move_target":
            "all",
        })
        data = wiz._prepare_report_journal_ledger()
        res_data = self.JournalLedgerReport._get_report_values(wiz, data)
        self.check_report_journal_debit_credit(res_data, 100, 100)

        move3 = self._add_move(today_date, self.journal_sale, 0, 100, 100, 0)

        res_data = self.JournalLedgerReport._get_report_values(wiz, data)
        self.check_report_journal_debit_credit(res_data, 200, 200)
        wiz.move_target = "posted"
        data = wiz._prepare_report_journal_ledger()
        res_data = self.JournalLedgerReport._get_report_values(wiz, data)
        self.check_report_journal_debit_credit(res_data, 0, 0)

        move1.action_post()
        res_data = self.JournalLedgerReport._get_report_values(wiz, data)
        self.check_report_journal_debit_credit(res_data, 100, 100)

        move2.action_post()
        res_data = self.JournalLedgerReport._get_report_values(wiz, data)
        self.check_report_journal_debit_credit(res_data, 100, 100)

        move3.action_post()
        res_data = self.JournalLedgerReport._get_report_values(wiz, data)
        self.check_report_journal_debit_credit(res_data, 200, 200)

        wiz.date_from = self.previous_fy_date_start
        data = wiz._prepare_report_journal_ledger()
        res_data = self.JournalLedgerReport._get_report_values(wiz, data)
        self.check_report_journal_debit_credit(res_data, 300, 300)
Esempio n. 33
0
    def get_occupation(self, day):
        """day: date object"""
        assert type(day) == date, "day should be of type datetime.date"
        self.ensure_one()

        reservation_lines = self.env["hotel_reservation.line"].search([
            ("line_id.state", "in", ["confirm", "done"]),
            ("reserve", "=", self.id),
            # checkin during the day or sooner
            ("checkin", "<=", Date.to_string(day)),
            # checkout during the day or later
            ("checkout", ">=", Date.to_string(day)),
        ])

        if len(reservation_lines) >= 2:
            return "departure_arrival"
        elif len(reservation_lines) == 0:
            return "free"
        elif Datetime.from_string(reservation_lines.checkin).date() == day:
            return "arrival"
        elif Datetime.from_string(reservation_lines.checkout).date() == day:
            return "departure"
        else:
            return "busy"
Esempio n. 34
0
File: common.py Progetto: 10537/odoo
    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,
        })
Esempio n. 35
0
    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")
Esempio n. 36
0
File: rpc.py Progetto: Gorrice/odoo
 def dump_date(self, value, write):
     value = Date.to_string(value)
     self.dump_unicode(value, write)