|
| 1 | +import base64 |
| 2 | +import logging |
| 3 | + |
| 4 | +from dateutil.relativedelta import relativedelta |
| 5 | + |
1 | 6 | from odoo import fields, models |
2 | 7 |
|
| 8 | +logger = logging.getLogger(__name__) |
| 9 | + |
3 | 10 |
|
4 | 11 | class HrLeave(models.Model): |
5 | 12 | _inherit = "hr.leave" |
6 | 13 |
|
7 | 14 | leave_request_id = fields.Many2one("hr.leave.request", string="Leave Request") |
| 15 | + |
| 16 | + def cron_generate_monthly_report(self): |
| 17 | + today = fields.Date.today() |
| 18 | + first_of_this_month = today.replace(day=1) |
| 19 | + first_of_last_month = first_of_this_month - relativedelta(months=1) |
| 20 | + last_of_last_month = first_of_this_month - relativedelta(days=1) |
| 21 | + default_leave_type = ( |
| 22 | + self.env["ir.config_parameter"] |
| 23 | + .sudo() |
| 24 | + .get_param("hr_leave_request.default_leave_type") |
| 25 | + ) |
| 26 | + records = self.search( |
| 27 | + [ |
| 28 | + ("date_from", ">=", first_of_last_month), |
| 29 | + ("date_to", "<=", last_of_last_month), |
| 30 | + ( |
| 31 | + "holiday_status_id", |
| 32 | + "=", |
| 33 | + int(default_leave_type) if default_leave_type else False, |
| 34 | + ), |
| 35 | + ("number_of_days", ">", 0), |
| 36 | + ] |
| 37 | + ) |
| 38 | + |
| 39 | + if not records: |
| 40 | + return |
| 41 | + |
| 42 | + pdf_content, _ = self.env.ref( |
| 43 | + "hr_holidays_webform.report_hr_leave_pdf" |
| 44 | + )._render_qweb_pdf(records.ids) |
| 45 | + |
| 46 | + attachment = self.env["ir.attachment"].create( |
| 47 | + { |
| 48 | + "name": "Monthly_Leave_Report.pdf", |
| 49 | + "type": "binary", |
| 50 | + "datas": base64.b64encode(pdf_content), |
| 51 | + "res_model": "hr.leave", |
| 52 | + "res_id": records[0].id, |
| 53 | + "mimetype": "application/pdf", |
| 54 | + } |
| 55 | + ) |
| 56 | + template = self.env.ref( |
| 57 | + "hr_holidays_webform.mail_template_hr_leave_monthly_report" |
| 58 | + ) |
| 59 | + if template: |
| 60 | + # force_attachment prevents Odoo from regenerating attachments |
| 61 | + # defined in the template |
| 62 | + template.send_mail( |
| 63 | + records[0].id, |
| 64 | + force_send=True, |
| 65 | + email_values={"attachment_ids": [(6, 0, [attachment.id])]}, |
| 66 | + ) |
0 commit comments