from odoo import fields, models, api, _ from odoo.exceptions import UserError, ValidationError from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta class ServiceRequest(models.Model): _name = 'service.request' _inherit = ['mail.thread', 'mail.activity.mixin'] _order = "date desc" name = fields.Char(string='Reference', required=True, copy=False, readonly=True, index=True, default=lambda self: _('New')) benefit_type = fields.Selection(string='Benefit Type', selection=[('family', 'Family'), ('member', 'Member')]) date = fields.Datetime(string='Request Date', default=fields.Datetime.now) marriage_contract_date = fields.Date(string="Marriage Contract Date") family_id = fields.Many2one('grant.benefit', string='Family', domain="['|',('state','=','second_approve'),'&',('state','in',['waiting_approve','first_approve']),('action_type','=','suspended')]") researcher_id = fields.Many2one("committees.line", string="Researcher", related="family_id.researcher_id", store=True) family_category = fields.Many2one('benefit.category', string='Family Category', related='family_id.benefit_category_id') benefit_member_count = fields.Integer(string="Benefit Member count", related='family_id.benefit_member_count') branch_custom_id = fields.Many2one('branch.settings', string="Branch", related='family_id.branch_custom_id', store=True) member_id = fields.Many2one('family.member', domain="[('benefit_id','=',family_id)]", string='Member') description = fields.Char(string='Description') need_status = fields.Selection(string='Need Status', selection=[('urgent', 'urgent'), ('not_urgent', 'Not urgent')]) main_service_category = fields.Many2one('services.settings', domain="[('service_type','=','main_service')]", string="Main Service Category") sub_service_category = fields.Many2one('services.settings', domain="[('service_type','=','main_service'),('service_type','=',False),('parent_service','=',main_service_category)]", string='Sub Service Category') service_cat = fields.Many2one('services.settings', string='Service Cat.') available_service_cats = fields.Many2many('services.settings', compute='_compute_available_service_cats', store=True) service_attach = fields.Many2many('ir.attachment', 'rel_service_attachment_service_request', 'service_request_id', 'attachment_id', string='Service Attachment') requested_service_amount = fields.Float(string="Requested Service Amount") # yearly Estimated Rent Amount estimated_rent_amount = fields.Float(string="Estimated Rent Amount", compute="_get_estimated_rent_amount") # The value of payment by payment method(yearly-half-quartarly) estimated_rent_amount_payment = fields.Float(string="Estimated Rent Amount Payment", compute="_get_estimated_rent_amount_payment") paid_rent_amount = fields.Float(string="Paid Rent Amount", compute="_get_paid_rent_amount") service_type = fields.Selection([('rent', 'Rent')], string='Service Type', related='service_cat.service_type') max_limit_period = fields.Selection(string='Maximum Limit Period', related='service_cat.max_limit_period') # is_alternative_housing = fields.Boolean(string='Is Alternative Housing?') rent_contract_number = fields.Char(string="Rent Contract Number", compute='_compute_rent_details', store=True) rent_start_date = fields.Date(string='Rent Start Date', compute='_compute_rent_details', store=True) rent_end_date = fields.Date(string='Rent End Date', compute='_compute_rent_details', store=True) rent_amount = fields.Float(string='Rent Amount', compute='_compute_rent_details', store=True) rent_amount_payment = fields.Float(string='Rent Amount Payment', compute='_get_rent_amount_payment') payment_type = fields.Selection( [ ('1', 'Yearly'), ('2', 'Half-yearly'), ('4', 'Quarterly'), ('5', 'Monthly') ], string='Payment Type', compute='_compute_rent_details', store=True ) rent_attachment = fields.Many2many('ir.attachment', 'rel_rent_attachment_service_request', 'service_request_id', 'attachment_id', string='Rent Attachment', compute='_compute_rent_details', store=True) rent_payment_date = fields.Date(string='Rent Payment Date') rent_payment_date_exception = fields.Boolean(string='Rent Payment Date Exception?') start = fields.Date(string="Start Date") end = fields.Date(string='End Date') # New Rent Contract new_rent_contract = fields.Boolean(string='New Rent Contract?') new_start = fields.Date(string="Start Date") new_end = fields.Date(string='End Date') new_rent_contract_number = fields.Char(string="Rent Contract Number") new_rent_start_date = fields.Date(string='Rent Start Date') new_rent_end_date = fields.Date(string='Rent End Date') new_rent_amount = fields.Float(string='Rent Amount') new_rent_amount_payment = fields.Float(string='New Rent Amount Payment', compute='_get_new_rent_amount_payment') new_payment_type = fields.Selection([ ('1', 'Yearly'), ('2', 'Half-yearly'), ('4', 'Quarterly'), ('5', 'Monthly') ], string='Payment Type' ) new_rent_attachment = fields.Many2many('ir.attachment', 'rel_rent_attachment_service_request', 'service_request_id', 'attachment_id', string='Rent Attachment') new_rent_payment_date = fields.Date(string='Rent Payment Date') new_rent_payment_date_exception = fields.Boolean(string='Rent Payment Date Exception?') # Rent details for member member_rent_contract_number = fields.Char(string="Rent Contract Number") member_rent_start_date = fields.Date(string='Rent Start Date') member_rent_end_date = fields.Date(string='Rent End Date') member_rent_attachment = fields.Many2many('ir.attachment', 'rel_member_rent_attachment_service_request', 'service_request_id', 'attachment_id', string='Rent Attachment') added_amount_if_mother_dead = fields.Float(string="Added Amount (If mother dead)", compute="_get_added_amount_if_mother_dead") attachment_lines = fields.One2many( 'service.attachments.settings', 'service_request_id', compute='_compute_attachment_lines', readonly=False, copy=False, store=True ) account_id = fields.Many2one( 'account.account', string='Expenses Account', compute="_compute_account_id" ) device_account_id = fields.Many2one('account.account', string='Expenses Account', related='device_id.account_id') accountant_id = fields.Many2one('res.users', string='Accountant', related='service_cat.accountant_id', readonly=False) service_producer_id = fields.Many2one('res.partner', string='Service Producer', related='service_cat.service_producer_id') is_service_producer = fields.Boolean(string='Is Service Producer?', related='service_cat.is_service_producer') # maintenance_items_id = fields.Many2one('home.maintenance.lines', string="Maintenance Items") maintenance_items_ids = fields.One2many('home.maintenance.items', 'service_request_id', string="Maintenance Items", ) payment_order_ids = fields.Many2many(comodel_name='payment.orders', relation='service_request_payment_order_rel', column1='service_request_id', column2='payment_order_id', string='Payment Orders', copy=False, ) payment_order_id = fields.Many2one('payment.orders', string='Payment Order', copy=False) payment_order_count = fields.Integer(compute='_compute_payment_order', string='Number of Payment Orders') is_payment_order_done = fields.Boolean(string='Is Payment Order Done?') aid_amount = fields.Float(string='Aid Amount', compute='_get_aid_amount') # Fields for alternative house providing_alternative_housing_based_rent = fields.Boolean(string='Providing alternative housing based on rent') rent_for_alternative_housing = fields.Many2one('services.settings', compute='_get_rent_for_alternative_housing') # Fields for electrical_devices service device_id = fields.Many2one('electrical.devices', string='Device', domain="[('min_count_member','<=',benefit_member_count),('max_count_member','>=',benefit_member_count)]") vendor_bill = fields.Many2one('account.move', copy=False) requested_quantity = fields.Integer(string='Requested Quantity') exception_or_steal = fields.Boolean(string='Exception Or Steal?') exception_or_steal_attach = fields.Many2many('ir.attachment', 'rel_exception_or_steal_attachment_service_request', 'exception_or_steal_id', 'attachment_id', string='Exception or steal Attachment') # Home furnishing Exception home_furnishing_exception = fields.Boolean(string='Exception(Fire Or Steal or Natural disaster)') furnishing_items_ids = fields.One2many('home.furnishing.items', 'service_request_id', string="Furnishing Items") # Transportation insurance # service_reason = fields.Selection(selection=[ # ('government_transportation', 'Government Transportation'), # ('universities_training_institutes_transportation', 'Universities Training Institutes Transportation'), # ('hospitals_transportation', 'Hospitals Transportation'), # ('programs_transportation', 'Programs Transportation'), # ], string='Service Reason') service_reason_id = fields.Many2one('transportation.insurance') max_amount = fields.Float(string='Max Transportation Amount') requests_counts = fields.Integer(string='Requests Counts', default=1) # Marriage member_age = fields.Integer(string="Member Age", related="member_id.age") member_payroll = fields.Float(string="Member Payroll", related="member_id.member_income") has_marriage_course = fields.Selection(selection=[ ('yes', 'Yes'), ('no', 'No'), ], string='Has Marriage Course') service_benefit_count = fields.Integer(string='Service Benefit Count', compute="_compute_service_benefit_count") # Buy home amount_for_buy_home_for_member_count = fields.Float(string="Amount For Buy Home for member count") home_age = fields.Integer(string='Home Age') required_attach = fields.Boolean(string='Required Attach', related='service_cat.required_attach') state = fields.Selection(selection=[ ('draft', 'Draft'), ('waiting_family', 'Waiting Family'), ('researcher', 'Researcher'), ('waiting_approve', 'Waiting for Operation Manager'), ('first_approve', 'Waiting for Branch Manager'), ('family_services_manager', 'Waiting Family Services Manager'), ('legal_department', 'Waiting Legal Department'), ('projects_department', 'Waiting Projects Department'), ('gm_assistant', 'Waiting Assistant General Manager'), ('accounting_approve', 'Accounting Approve'), ('return_to_bank', 'Return to Bank'), ('approval_of_beneficiary_services', 'Approval of beneficiary services'), ('send_request_to_supplier', 'Send Request To Supplier'), ('family_received_device', 'Family Received Device'), ('refused', 'Refused') ], string='state', default='draft', tracking=True, group_expand='_expand_states') # dynamic_state = fields.Selection(selection=[],string="State",default='draft',tracking=True,) state_a = fields.Selection(related='state', tracking=False) state_b = fields.Selection(related='state', tracking=False) refuse_reason_id = fields.Many2one('service.refuse.reason', string="Refuse Reason") return_reason = fields.Text(string="Reason for Returning the Request") refuse_reason = fields.Text(string="Reason for Refusal") specialist_note = fields.Text(string="Specialist's Note After Return") exception = fields.Boolean(string='Exception', default=False) exception_attach = fields.Many2many('ir.attachment', 'rel_exception_attachment_service_request', 'service_request_id', 'attachment_id', string='Exception Attachment') service_conditions = fields.Html(related='service_cat.service_conditions', string="Service Conditions") service_approval_date = fields.Datetime(string="Service Approval Date", readonly=True, ) company_id = fields.Many2one('res.company', string="Company", default=lambda self: self.env.user.company_id) currency_id = fields.Many2one('res.currency', string="Currency", related='company_id.currency_id') service_max_amount = fields.Float(string="Maximum Amount", copy=False) rent_period = fields.Integer('Rent Period') is_orphan = fields.Boolean(string='Orphaned (Both Parents Deceased)', compute='_compute_is_orphan', store=True) has_money_for_payment_is_appearance = fields.Boolean(string='Has money Field is appearance?', compute='_get_money_for_payment_is_appearance') has_money_for_payment = fields.Selection([('yes', 'Yes'), ('no', 'No')], string='Has money for payment?') has_money_to_pay_first_payment = fields.Selection([('yes', 'Yes'), ('no', 'No')], string='Has money to pay first payment?') has_money_field_is_appearance = fields.Boolean(string='Has money Field is appearance?', compute='_get_money_field_is_appearance') car_name = fields.Char(string='Car Name') car_owner_id = fields.Many2one('family.member', domain="[('benefit_id','=',family_id)]", string="Car Owner") car_model_id = fields.Many2one('benefit.vehicle.model', string='Car model') application_form = fields.Many2many('ir.attachment', 'request_application_form_rel', 'request_id', 'attachment_id', string="Application Form") driving_license = fields.Many2many('ir.attachment', 'request_driving_license_rel', 'request_id', 'attachment_id', string="Driving License") owner_identity = fields.Many2many('ir.attachment', 'request_owner_identity_rel', 'request_id', 'attachment_id', string="Owner Identity") seasonal_service_id = fields.Many2one('seasonal.service', string='Seasonal Service', ondelete='cascade') is_seasonal = fields.Boolean(string='Is Seasonal Service?', related='service_cat.is_seasonal_service') is_in_kind = fields.Boolean(string="In Kind", default=False) service_qty = fields.Float(string='Quantity', default=1) payment_order_state = fields.Selection(string='Payment Order State', selection=[ ('none', 'None'), ('waiting', 'Waiting Payment'), ('done', 'Done Payment'), ], copy=False, compute="_compute_payment_order_state", store=True) total_moves = fields.Integer(string="Total Move", compute='_get_total_move_lines') return_reason_id = fields.Many2one("return.reason", string="Return Reason") @api.depends('payment_order_ids') def _compute_payment_order(self): for rec in self: if rec.payment_order_ids: rec.payment_order_count = len(rec.payment_order_ids) else: rec.payment_order_count = 0 @api.depends('payment_order_id', 'payment_order_id.state', 'vendor_bill', 'vendor_bill.state') def _compute_payment_order_state(self): for rec in self: payment_order_state = 'none' if rec.payment_order_id: if rec.payment_order_id.state == "done": payment_order_state = "done" rec.service_approval_date = fields.Datetime.now() if rec.state == 'accounting_approve': rec.state = 'send_request_to_supplier' rec.is_payment_order_done = True else: payment_order_state = "waiting" elif rec.vendor_bill: if rec.vendor_bill.state == "posted": payment_order_state = "done" rec.state = 'send_request_to_supplier' else: payment_order_state = "waiting" rec.payment_order_state = payment_order_state def action_return_bank(self): self.ensure_one() return { 'name': _("Bank Return"), 'type': 'ir.actions.act_window', 'res_model': 'return.reason.wizard', 'view_mode': 'form', 'target': 'new', 'context': { 'default_line_id': self.id, 'default_line_model': 'service.request', } } def action_processed(self): for record in self: record.state = 'accounting_approve' @api.depends('requested_service_amount', 'service_max_amount') def _get_money_for_payment_is_appearance(self): for rec in self: if rec.requested_service_amount and rec.service_max_amount and rec.requested_service_amount > rec.service_max_amount: rec.has_money_for_payment_is_appearance = True else: rec.has_money_for_payment_is_appearance = False @api.depends('requested_service_amount', 'service_max_amount') def _get_money_field_is_appearance(self): for rec in self: if rec.requested_service_amount and rec.service_max_amount and rec.requested_service_amount > rec.service_max_amount: rec.has_money_field_is_appearance = True else: rec.has_money_field_is_appearance = False @api.depends('family_id.mother_marital_conf', 'family_id.replacement_mother_marital_conf') def _compute_is_orphan(self): for rec in self: if not rec.family_id.add_replacement_mother: mother_dead = bool(getattr(rec.family_id.mother_marital_conf, 'is_dead', False)) else: mother_dead = bool(getattr(rec.family_id.replacement_mother_marital_conf, 'is_dead', False)) rec.is_orphan = mother_dead def _expand_states(self, states, domain, order): return [key for key, val in type(self).state.selection] @api.depends('service_cat', 'service_reason_id') def _compute_account_id(self): for rec in self: if rec.service_type == 'transportation_insurance': rec.account_id = rec.service_reason_id.account_id else: rec.account_id = rec.service_cat.account_id @api.depends('service_cat') def _compute_attachment_lines(self): for rec in self: commands = [(5, 0, 0)] if rec.service_cat: for attachment_line in rec.service_cat.attachment_lines: commands.append((0, 0, { 'service_id': False, 'service_request_id': rec.id, 'name': attachment_line.name, 'notes': attachment_line.notes, 'previous_service_attachment_settings_id': attachment_line.id, })) rec.attachment_lines = commands @api.model def create(self, vals): # Define the list of fields to check new_rent_fields = [ 'new_rent_contract_number', 'new_rent_start_date', 'new_rent_end_date', 'new_rent_amount', 'new_payment_type', 'new_rent_attachment' ] res = super(ServiceRequest, self).create(vals) if not res.name or res.name == _('New'): res.name = self.env['ir.sequence'].sudo().next_by_code('service.request.sequence') or _('New') # Check if any of the specified fields are present in vals if any(field in vals for field in new_rent_fields) and vals['new_rent_contract']: if res.family_id: # Prepare values for family_id write update_values = {} if 'new_rent_contract_number' in vals: update_values['contract_num'] = vals['new_rent_contract_number'] if 'new_rent_start_date' in vals: update_values['rent_start_date'] = vals['new_rent_start_date'] if 'new_rent_end_date' in vals: update_values['rent_end_date'] = vals['new_rent_end_date'] if 'new_rent_amount' in vals: update_values['rent_amount'] = vals['new_rent_amount'] if 'new_payment_type' in vals: update_values['payment_type'] = vals['new_payment_type'] if 'new_rent_attachment' in vals: update_values['rent_attachment'] = vals['new_rent_attachment'] # Write updates to the related family_id res.family_id.write(update_values) return res def write(self, vals): # Define the list of fields you want to check new_rent_fields = ['new_rent_contract_number', 'new_rent_start_date', 'new_rent_end_date', 'new_rent_amount', 'new_payment_type', 'new_rent_attachment'] result = super(ServiceRequest, self).write(vals) update_values = {} if any(field in vals for field in new_rent_fields) and self.new_rent_contract: for record in self: # Ensure family_id exists before proceeding if record.family_id: # Prepare values for family_id write update_values = {} # Add fields to update_values only if they exist in vals if 'new_rent_contract_number' in vals: update_values['contract_num'] = vals['new_rent_contract_number'] if 'new_rent_start_date' in vals: update_values['rent_start_date'] = vals['new_rent_start_date'] if 'new_rent_end_date' in vals: update_values['rent_end_date'] = vals['new_rent_end_date'] if 'new_rent_amount' in vals: update_values['rent_amount'] = vals['new_rent_amount'] if 'new_payment_type' in vals: update_values['payment_type'] = vals['new_payment_type'] if 'new_rent_attachment' in vals: update_values['rent_attachment'] = vals['new_rent_attachment'] # Write the prepared update values to `family_id` record.family_id.write(update_values) return result def unlink(self): for request in self: if request.state not in ['draft']: raise UserError(_('You cannot delete this record')) return super(ServiceRequest, self).unlink() @api.depends('family_id') def _compute_rent_details(self): for rec in self: # Compute values only if they are not already set if rec.family_id: if not rec.rent_contract_number: rec.rent_contract_number = rec.family_id.contract_num if not rec.rent_start_date: rec.rent_start_date = rec.family_id.rent_start_date if not rec.rent_end_date: rec.rent_end_date = rec.family_id.rent_end_date if not rec.rent_amount: rec.rent_amount = rec.family_id.rent_amount if not rec.payment_type: rec.payment_type = rec.family_id.payment_type if not rec.rent_attachment: rec.rent_attachment = rec.family_id.rent_attachment def _get_estimated_rent_amount(self): for rec in self: rec.estimated_rent_amount = 0.0 # Default value if not rec.family_id: continue if rec.service_type == 'rent': for item in rec.service_cat.rent_lines: # Check if benefit category and member count match if rec.family_id.benefit_category_id != item.benefit_category_id or rec.family_id.benefit_member_count != item.benefit_count: continue # Determine rent amount based on branch type and property type branch_type = rec.family_id.branch_custom_id.branch_type is_shared_rent = rec.family_id.property_type == 'rent_shared' if branch_type == 'branches': rec.estimated_rent_amount = item.estimated_rent_branches * ( item.discount_rate_shared_housing if is_shared_rent else 1) elif branch_type == 'governorates': rec.estimated_rent_amount = item.estimated_rent_governorate * ( item.discount_rate_shared_housing if is_shared_rent else 1) if rec.service_type == 'alternative_housing': for item in rec.rent_for_alternative_housing.rent_lines: # Check if benefit category and member count match if rec.family_id.benefit_category_id != item.benefit_category_id or rec.family_id.benefit_member_count != item.benefit_count: continue # Determine rent amount based on branch type and property type branch_type = rec.family_id.branch_custom_id.branch_type is_shared_rent = rec.family_id.property_type == 'rent_shared' if branch_type == 'branches': rec.estimated_rent_amount = item.estimated_rent_branches * ( item.discount_rate_shared_housing if is_shared_rent else 1) elif branch_type == 'governorates': rec.estimated_rent_amount = item.estimated_rent_governorate * ( item.discount_rate_shared_housing if is_shared_rent else 1) def _get_estimated_rent_amount_payment(self): for rec in self: rec.estimated_rent_amount_payment = 0.0 if rec.estimated_rent_amount and rec.payment_type: rec.estimated_rent_amount_payment = rec.estimated_rent_amount / int(rec.payment_type) if rec.estimated_rent_amount and rec.new_payment_type: rec.estimated_rent_amount_payment = rec.estimated_rent_amount / int(rec.new_payment_type) def _get_rent_amount_payment(self): for rec in self: if rec.rent_amount and rec.payment_type: rec.rent_amount_payment = rec.rent_amount / int(rec.payment_type) else: rec.rent_amount_payment = 0.0 def _get_new_rent_amount_payment(self): for rec in self: if rec.new_rent_amount and rec.new_payment_type: rec.new_rent_amount_payment = rec.new_rent_amount / int(rec.new_payment_type) else: rec.new_rent_amount_payment = 0.0 def _get_paid_rent_amount(self): for rec in self: rec.paid_rent_amount = min(rec.estimated_rent_amount_payment, rec.requested_service_amount) def _get_added_amount_if_mother_dead(self): for rec in self: rec.added_amount_if_mother_dead = 0.0 if rec.family_id.mother_marital_conf.is_dead: rec.added_amount_if_mother_dead = rec.service_cat.raise_amount_for_orphan def _get_aid_amount(self): for rec in self: if rec.service_type == 'rent': rec.aid_amount = rec.paid_rent_amount + rec.added_amount_if_mother_dead else: rec.aid_amount = rec.requested_service_amount def _get_rent_for_alternative_housing(self): for rec in self: if rec.service_cat.service_type == 'alternative_housing': rec.rent_for_alternative_housing = self.env['services.settings'].search([('service_type', '=', 'rent')], limit=1).id else: rec.rent_for_alternative_housing = False @api.depends('family_id', 'service_cat') def _compute_service_benefit_count(self): for rec in self: count = 1 if rec.benefit_type == "family": count = len(rec.family_id.member_ids.filtered(lambda m: m.member_status == 'benefit')) if rec.service_cat.max_age > 0: count = len( rec.family_id.member_ids.filtered(lambda x: x.age <= rec.service_cat.max_age)) rec.service_benefit_count = count @api.onchange('requests_counts', 'service_type', 'service_reason_id') def _get_max_transportation_amounts(self): for rec in self: rec.max_amount = rec.requests_counts * rec.service_reason_id.limit_amount def action_send_to_researcher(self): for rec in self: rec.state = 'researcher' def action_return_to_family(self): for rec in self: rec.state = 'waiting_family' def action_researcher_send_request(self): for rec in self: if not rec.requested_service_amount or rec.requested_service_amount <= 0: raise UserError(_("Please enter a valid service amount.")) if rec.attachment_lines: for attach_line in rec.attachment_lines: if not attach_line.service_attach: raise UserError(_( "Some attachment records are missing files. Please make sure all required attachments are uploaded before submitting." )) rec.state = 'waiting_approve' def action_operations_chief_approve(self): for rec in self: rec.state = 'first_approve' def action_branch_manager_approve(self): for rec in self: if rec.service_cat.needs_services_head_approval or rec.exception: rec.state = 'family_services_manager' else: rec.state = 'accounting_approve' def action_family_services_manager_approve(self): for rec in self: if rec.service_cat.needs_legal_approval: rec.state = 'legal_department' elif rec.service_cat.needs_project_management_approval: rec.state = 'projects_department' elif rec.service_cat.needs_beneficiary_manager_approval or rec.exception: rec.state = 'gm_assistant' else: rec.state = 'accounting_approve' def action_legal_department_approve(self): for rec in self: if rec.service_cat.needs_project_management_approval: rec.state = 'projects_department' elif rec.service_cat.needs_beneficiary_manager_approval or rec.exception: rec.state = 'gm_assistant' def action_projects_department_approve(self): for rec in self: if rec.service_cat.needs_beneficiary_manager_approval or rec.exception: rec.state = 'gm_assistant' else: rec.state = 'accounting_approve' def action_beneficiary_manager_approve(self): for rec in self: rec.state = 'accounting_approve' def action_accounting_approve(self): for rec in self: if rec.service_type == 'electrical_devices': rec.state = 'approval_of_beneficiary_services' else: rec.service_approval_date = fields.Datetime.now() rec.state = 'send_request_to_supplier' def action_supplier_approve(self): for rec in self: rec.service_approval_date = fields.Datetime.now() rec.state = 'send_request_to_supplier' def action_request_done(self): for rec in self: if rec.service_type == 'buy_car': car_vals = { 'benefit_id': rec.family_id.id, 'name': rec.car_name, 'member_id': rec.car_owner_id.id, 'car_model': rec.car_model_id.id, } car = self.env['cars.line'].create(car_vals) if rec.application_form: car.application_form = [(6, 0, rec.application_form.ids)] if rec.driving_license: car.driving_license = [(6, 0, rec.driving_license.ids)] if rec.owner_identity: car.owner_identity = [(6, 0, rec.owner_identity.ids)] rec.family_id.has_car = True rec.state = 'family_received_device' def action_send_request_to_supplier(self): for rec in self: rec.state = 'family_received_device' def action_first_refuse(self): return { 'name': _('Reason for Returning the Request'), 'type': 'ir.actions.act_window', 'res_model': 'reason.for.return.wizard', 'view_mode': 'form', 'target': 'new', } def action_refuse(self): return { 'name': _('Refuse Reason'), 'type': 'ir.actions.act_window', 'res_model': 'service.refuse.reason.wizard', 'view_mode': 'form', 'target': 'new', } @api.onchange('rent_payment_date', 'new_rent_payment_date') def onchange_rent_payment_date(self): today_date = fields.Date.today() for rec in self: if rec.rent_payment_date and not rec.rent_payment_date_exception and not rec.new_rent_payment_date: month_before_rent_payment_date = rec.rent_payment_date - timedelta(days=30) if today_date > month_before_rent_payment_date: raise UserError(_("You Should request At least a month ago rent payment date")) if rec.new_rent_payment_date and not rec.new_rent_payment_date_exception: new_month_before_rent_payment_date = rec.new_rent_payment_date - timedelta(days=30) if today_date > new_month_before_rent_payment_date: raise UserError(_("You Should request At least a month ago rent payment date")) @api.onchange('furnishing_items_ids') def _onchange_home_furnishing_cost(self): furnishing_cost_sum = 0 for rec in self.furnishing_items_ids: furnishing_cost_sum += rec.furnishing_cost self.requested_service_amount = furnishing_cost_sum @api.onchange('family_id', 'service_cat') def _onchange_member(self): for rec in self: rec.benefit_type = rec.service_cat.benefit_type if not rec.family_id: rec.member_id = False rec.service_cat = False rec.available_service_cats = False @api.onchange('service_cat', 'family_id') def _onchange_service_cat(self): if self.service_cat.service_type == 'rent' and self.family_id.property_type != 'rent' and self.family_id.property_type != 'rent_shared' and self.benefit_type == 'family': raise UserError(_("You cannot benefit from this service (property type not rent)")) @api.onchange( 'requested_service_amount', 'benefit_type', 'date', 'service_cat', 'family_id', 'member_id', 'exception_or_steal', 'home_furnishing_exception', 'has_marriage_course', 'home_age', 'service_reason_id', 'device_id', 'requested_quantity', 'amount_for_buy_home_for_member_count', 'marriage_contract_date', 'start', 'end' ) def onchange_requested_service_amount(self): res = {} Service = self.env['service.request'] today = fields.Date.today() date_before_year = today - timedelta(days=365) for rec in self: if not rec.exception and not rec.exception_attach: family_id = rec.family_id.id service_type = rec.service_cat.service_type allowed = rec.service_cat.allowed_recurrence interval = rec.service_cat.recurrence_interval or 1 period = rec.service_cat.recurrence_period or 'months' max_limit_type = rec.service_cat.max_limit_type special_services = ['home_furnishing', 'electrical_devices', 'rent', 'alternative_housing'] base_domain = [('family_id', '=', family_id), ('service_cat', '=', rec.service_cat.id), ('id', '!=', rec._origin.id), ('state', '!=', 'refused')] if rec.benefit_type == "member": base_domain.append(('member_id', '=', rec.member_id.id)) if rec.service_cat.service_type == 'buy_car': if rec.family_id.has_car: raise ValidationError(_("You cannot request this service because you have a car.")) if rec.benefit_member_count < rec.service_cat.min_count_member: raise ValidationError( _("You cannot request this service because you are less than %s") % rec.service_cat.min_count_member) if rec.service_cat.service_type == 'recruiting_driver': son_members_above_age = rec.family_id.mapped('member_ids').filtered( lambda x: x.relationn.relation_type == 'son' and x.age > 18) daughter_members_above_age = rec.family_id.mapped('member_ids').filtered( lambda x: x.relationn.relation_type == 'daughter' and x.age > 18) disable_mother = rec.family_id.mapped('member_ids').filtered( lambda x: x.relationn.relation_type == 'mother') work_mother = rec.family_id.mapped('member_ids').filtered( lambda x: x.relationn.relation_type == 'mother' and x.benefit_id.is_mother_work) disable_replacement_mother = rec.family_id.mapped('member_ids').filtered( lambda x: x.relationn.relation_type == 'replacement_mother') work_replacement_mother = rec.family_id.mapped('member_ids').filtered( lambda x: x.relationn.relation_type == 'replacement_mother' and x.replacement_is_mother_work) if not rec.family_id.has_car: raise ValidationError(_("You cannot request this service because you do not have a car")) if son_members_above_age or daughter_members_above_age: raise ValidationError( _("You cannot request this service because children above 18 years")) if rec.family_id.add_replacement_mother and not disable_replacement_mother and not work_replacement_mother: raise ValidationError( _("You cannot request this service because mother should be worked or has disability")) if not rec.family_id.add_replacement_mother and not disable_mother and not work_mother: raise ValidationError( _("You cannot request this service because mother should be worked or has disability")) if service_type in ['home_maintenance', 'complete_building_house', 'buy_home']: existing_request_restoration = Service.search([ ('family_id', '=', family_id), ('service_cat.service_type', '=', 'home_restoration'), ('id', '!=', rec._origin.id), ('state', '!=', 'refused') ], order='date desc', limit=1) if existing_request_restoration and existing_request_restoration.date: if service_type == 'buy_home': raise ValidationError(_( "You cannot request this service together with 'home_restoration' within the same recurrence period." )) else: restoration_date = existing_request_restoration.date.date() next_allowed_restoration_date = ( restoration_date + relativedelta(months=interval) if period == 'months' else restoration_date + relativedelta(years=interval) ) if rec.date.date() < next_allowed_restoration_date: raise ValidationError(_( "You cannot request this service together with 'home_restoration' within the same recurrence period." )) if service_type == 'transportation_insurance': if rec.family_id.has_car: raise ValidationError(_("You cannot request this service because you have a car.")) if service_type == 'buy_home': if rec.service_cat.buy_home_max_total_amount < rec.amount_for_buy_home_for_member_count: raise ValidationError(_( "You can request this service because the total housing amount (%.2f) " "is still under the maximum limit of %.2f." ) % (rec.amount_for_buy_home_for_member_count, rec.service_cat.buy_home_max_total_amount)) if rec.home_age > rec.service_cat.home_age: raise ValidationError( _("You cannot request this service Again Because the home Age More than %s") % rec.service_cat.home_age) if rec.start and rec.end: if rec.start > rec.end: raise ValidationError(_("Start date must be before end date.")) overlap_domain = base_domain + [ ('start', '!=', False), ('end', '!=', False), ('start', '<=', rec.end), ('end', '>=', rec.start) ] overlap_requests = Service.search(overlap_domain) if overlap_requests: raise ValidationError( _("This service request overlaps with an existing requests [%s] for the same service " "between %s and %s.") % (", ".join(overlap_requests.mapped('name')), rec.start, rec.end) ) if allowed: if allowed == 'unlimited': pass elif allowed == 'once': if Service.search_count(base_domain): raise ValidationError(_("You cannot request this service more than once.")) else: if service_type in special_services: if service_type == 'home_furnishing': delta_kwargs = {period: interval} date_before = rec.date - relativedelta(**delta_kwargs) domain = base_domain + [('date', '>', date_before)] existing_requests = Service.search(domain) total_amount = sum(existing_requests.mapped('requested_service_amount')) + sum( rec.furnishing_items_ids.mapped('furnishing_cost')) if not rec.home_furnishing_exception: rec.service_max_amount = rec.service_cat.max_amount if total_amount > rec.service_cat.max_amount: raise ValidationError( _("You cannot request more than %s") % rec.service_max_amount) if rec.home_furnishing_exception: rec.service_max_amount = rec.service_cat.max_furnishing_amount_if_exception if total_amount > rec.service_cat.max_furnishing_amount_if_exception: raise ValidationError( _("You cannot request more than %s") % rec.service_max_amount) if service_type == 'electrical_devices': rec.service_max_amount = rec.device_id.price_unit if rec.device_id else 0.0 if rec.device_id: delta_kwargs = {period: interval} date_before = rec.date - relativedelta(**delta_kwargs) domain = base_domain + [ ('device_id', '=', rec.device_id.id), ('date', '>', date_before) ] existing_requests = Service.search(domain) total_previous_qty = sum(existing_requests.mapped('requested_quantity')) total_qty = total_previous_qty + rec.requested_quantity allowed_line = rec.service_cat.electrical_devices_lines.filtered( lambda l: l.id == rec.device_id.id ) allowed_qty = allowed_line.allowed_quantity if allowed_line else 0 if total_qty > allowed_qty: raise ValidationError(_( "You cannot request this device more than %s times within %s %s." ) % (allowed_qty, interval, period)) else: last_request = Service.search(base_domain, order='date desc', limit=1) if last_request and last_request.date: last_date = ( last_request.date.date() if isinstance(last_request.date, datetime) else last_request.date ) next_allowed_date = ( last_date + relativedelta(months=interval) if period == 'months' else last_date + relativedelta(years=interval) ) if isinstance(next_allowed_date, datetime): next_allowed_date = next_allowed_date.date() if rec.date.date() < next_allowed_date: raise ValidationError(_( "You can only request this service again after %s." ) % next_allowed_date.strftime('%Y-%m-%d')) if max_limit_type and service_type not in special_services: if max_limit_type == 'fixed': rec.service_max_amount = rec.service_cat.max_amount elif max_limit_type == 'category': rec.service_max_amount = rec.service_cat.category_amount_lines and max( rec.service_cat.category_amount_lines.filtered( lambda r: r.benefit_category_id.id == rec.family_category.id).mapped('max_amount'), default=0.0) or 0 elif max_limit_type == 'category_person': rec.service_max_amount = rec.service_cat.bill_lines and max(rec.service_cat.bill_lines.filtered( lambda x: x.benefit_category_id.id == rec.family_category.id and x.min_count_member <= rec.benefit_member_count <= x.max_count_member).mapped( 'max_amount_for_bill'), default=0.0) or 0 elif max_limit_type == 'service': pass elif max_limit_type == 'none': pass elif max_limit_type == 'amount_person': rec.service_max_amount = rec.service_cat.limit_person_line_ids and max( rec.service_cat.limit_person_line_ids.filtered( lambda x: x.min_count_member <= rec.benefit_member_count <= x.max_count_member)).amount or 0 if rec.max_limit_period: if rec.max_limit_period == "month": if rec.start and rec.end: start_date = rec.start.date() if isinstance(rec.start, datetime) else rec.start end_date = rec.end.date() if isinstance(rec.end, datetime) else rec.end num_months = (end_date.year - start_date.year) * 12 + ( end_date.month - start_date.month) + 1 if num_months > rec.service_cat.max_months_limit: raise ValidationError( _("You cannot request this service for more than %s months.") % rec.service_cat.max_months_limit ) rec.service_max_amount *= num_months elif rec.max_limit_period == "year": before_year_domain = base_domain + [('date', '>', date_before_year)] existing_requests_within_year = Service.search(before_year_domain) total_spent = sum(existing_requests_within_year.mapped('requested_service_amount')) rec.service_max_amount = rec.service_cat.max_amount - total_spent elif rec.max_limit_period == "individual": rec.service_max_amount *= rec.service_benefit_count elif rec.max_limit_period == "recurrence_period": pass if service_type == 'transportation_insurance': if rec.service_reason_id and rec.requested_service_amount > rec.max_amount: raise ValidationError(_("You cannot request more than %s")) continue if rec.service_cat.service_type == 'marriage': if rec.member_id.relationn.relation_type == 'son' and not rec.member_id.is_work: raise ValidationError(_("This service is not eligible because the son is not working.")) if rec.marriage_contract_date and rec.date: request_date = rec.date.date() if isinstance(rec.date, datetime) else rec.date contract_date = rec.marriage_contract_date diff_days = (request_date - contract_date).days if diff_days > 365: raise ValidationError( _("You cannot request this service because the marriage contract date exceeds one year.")) rec.service_max_amount = rec.service_cat.fatherless_member_amount if rec.is_orphan: rec.service_max_amount = rec.service_cat.orphan_member_amount rec.requested_service_amount = rec.service_max_amount if rec.member_age > rec.service_cat.max_age: raise ValidationError(_("Member Age should be less than %s ") % rec.service_cat.max_age) if rec.member_payroll > rec.service_cat.member_max_payroll: raise ValidationError( _("Member Payroll should be less than %s ") % rec.service_cat.member_max_payroll) if not rec.is_orphan and rec.requested_service_amount > rec.service_max_amount: raise ValidationError(_("You cannot request more than %s ") % rec.service_max_amount) if rec.is_orphan and rec.requested_service_amount > rec.service_max_amount: raise ValidationError(_("You cannot request more than %s ") % rec.service_max_amount) if rec.has_marriage_course == 'no': raise UserError(_("You Should take a course")) continue if rec.requested_service_amount > rec.service_max_amount and service_type not in special_services and not max_limit_type == 'none': raise ValidationError( _("You cannot request more than %s") % rec.service_max_amount ) # Validation for 'member' benefit type if rec.benefit_type == 'member' and rec.service_cat.service_type == 'rent': max_requested_amount = rec.service_cat.max_amount_for_student if rec.requested_service_amount > max_requested_amount: self.benefit_type = False res['warning'] = {'title': _('ValidationError'), 'message': _("You cannot request more than %s") % max_requested_amount} return res # Validation for 'family' benefit type if rec.benefit_type == 'family' and rec.service_cat.service_type == 'rent': rent_line_id = rec.service_cat.rent_lines.filtered( lambda r: r.benefit_category_id.id == rec.family_category.id \ and r.benefit_count == rec.benefit_member_count ) max_requested_amount = rent_line_id.estimated_rent_branches if rec.branch_custom_id.branch_type == 'branches' else rent_line_id.estimated_rent_governorate if rec.requested_service_amount > max_requested_amount: self.benefit_type = False res['warning'] = {'title': _('ValidationError'), 'message': _("You cannot request more than %s") % max_requested_amount} return res if rec.benefit_type == 'family' and rec.service_cat.service_type == 'alternative_housing' and not rec.providing_alternative_housing_based_rent: if rec.requested_service_amount > rec.service_cat.rent_amount_for_alternative_housing: raise UserError( _("You Cannot request amount more than %s") % rec.service_cat.rent_amount_for_alternative_housing) elif rec.rent_period > rec.service_cat.rent_period: raise UserError( _("You Cannot request this service for period more than %s") % rec.service_cat.rent_period) # Validation for 'family' benefit type with 'eid_gift' service type # if rec.benefit_type == 'family' and rec.service_cat.service_type == 'eid_gift': # if rec.eid_gift_benefit_count == 0: # raise UserError( # _("You cannot request this service because family should have members his age less than %s") % rec.service_cat.max_age) # Validation for 'member' benefit type with 'eid_gift' service type # if rec.benefit_type == 'member' and rec.service_cat.service_type == 'eid_gift': # if rec.member_id.age > rec.service_cat.max_age: # raise UserError( # _("You cannot request this service because your age should be less than %s") % rec.service_cat.max_age) @api.onchange('member_id') def onchange_member_id(self): for rec in self: if rec.member_id and rec.service_type == 'rent' and not rec.member_id.member_location_conf.is_far_from_family: raise UserError(_("You Cannot request Service if you not study inside Saudi Arabia")) @api.onchange('start', 'end', 'rent_start_date', 'rent_end_date', 'new_start', 'new_end', 'new_rent_start_date', 'new_rent_end_date', 'new_rent_contract') def _check_date_range(self): for rec in self: # Ensure both start and end dates are set if rec.start and rec.end and rec.rent_start_date and rec.rent_end_date and not rec.new_rent_contract: # Check if `start` and `end` are within `rent_start_date` and `rent_end_date` if not (rec.rent_start_date <= rec.start <= rec.rent_end_date and rec.rent_start_date <= rec.end <= rec.rent_end_date): raise UserError( "The Start Date and End Date must be within the Rent Start Date and Rent End Date range.") if rec.new_start and rec.new_end and rec.new_rent_start_date and rec.new_rent_end_date and rec.new_rent_contract: # Check if `start` and `end` are within `rent_start_date` and `rent_end_date` if not (rec.new_rent_start_date <= rec.new_start <= rec.new_rent_end_date and rec.new_rent_start_date <= rec.new_end <= rec.new_rent_end_date): raise UserError( "The Start Date and End Date must be within the Rent Start Date and Rent End Date range.") @api.depends('family_category') def _compute_available_service_cats(self): for rec in self: domain = [('is_seasonal_service', '=', False), ('service_type', '!=', 'main_service'), ('benefit_category_ids', 'in', [rec.family_category.id])] if rec.family_id.property_type not in ['ownership', 'ownership_shared', 'charitable']: domain.append(('service_type', '!=', 'home_restoration')) else: domain.append(('service_type', '!=', 'buy_home')) rec.available_service_cats = rec.available_service_cats.sudo().search(domain) # if rec.member_id.member_status != 'benefit': # domain.append(('allow_non_beneficiary','=',True)) def action_set_to_draft(self): for rec in self: rec.state = 'draft' def action_accounting_transfer(self): validation_setting = self.env["family.validation.setting"].search([], limit=1) line_ids = [] service_cats = self.mapped('service_cat') if len(service_cats) > 1: cat_names = ", ".join(service_cats.mapped('service_name')) raise UserError(_( "All selected service requests must belong to the same Service Cat.\n\n" "Selected Services Cat:\n%s" ) % cat_names) if service_cats.payment_method == "payment_order": invalid_records = self.filtered( lambda r: r.state != 'accounting_approve' or r.payment_order_state != 'none' or r.payment_order_id ) if invalid_records: names = ", ".join(invalid_records.mapped('name')) raise UserError(_( "The following service requests do not meet the conditions:\n%s\n" "Each request must:\n" "• Be in 'Accounting Approve' state\n" "• Have payment order state = 'None'\n" "• Not be linked to any payment order" ) % names) payment_order = self.env['payment.orders'].create({ 'state': 'draft', 'accountant_id': service_cats.accountant_id.id, 'service_requests_ids': [(6, 0, self.ids)], 'type': 'services', }) self.write({ 'payment_order_ids': [(4, payment_order.id)], 'payment_order_id': payment_order.id, }) elif service_cats.payment_method == "invoice": invalid_records = self.filtered( lambda r: r.state != 'accounting_approve' or r.payment_order_state != 'none' or r.vendor_bill ) if invalid_records: names = ", ".join(invalid_records.mapped('name')) raise UserError(_( "The following service requests do not meet the conditions:\n%s\n" "Each request must:\n" "• Be in 'Accounting Approve' state\n" "• Have payment order state = 'None'\n" "• Not be linked to any invoice" ) % names) for rec in self: invoice_line = (0, 0, { 'name': f'{rec.family_id.name}/{rec.device_id.device_name}/{rec.description}/{rec.name}', 'account_id': rec.device_account_id.id, 'analytic_account_id': rec.family_id.branch_family_id.branch.analytic_account_id.id, 'quantity': rec.requested_quantity, 'price_unit': rec.requested_service_amount, 'benefit_family_id': rec.family_id.id, }) line_ids.append(invoice_line) vendor_bill = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self[0].service_producer_id.id, 'journal_id': validation_setting.journal_id.id, # 'accountant_id': self.accountant_id.id, 'invoice_line_ids': line_ids, }) self.vendor_bill = vendor_bill def _get_total_move_lines(self): for rec in self: if self.service_cat.payment_method == "payment_order": moves = rec.payment_order_ids.mapped('move_id') elif self.service_cat.payment_method == "invoice": moves = self.vendor_bill rec.total_moves = len(moves) def action_open_related_move_records(self): if self.service_cat.payment_method == "payment_order": moves = self.payment_order_ids.mapped('move_id') elif self.service_cat.payment_method == "invoice": moves = self.vendor_bill.ids return { 'name': _('Vendor Bills'), 'type': 'ir.actions.act_window', 'res_model': 'account.move', 'view_mode': 'tree,form', 'domain': [('id', 'in', moves.ids)], } def action_open_payment_orders(self): self.ensure_one() if not self.payment_order_ids: raise UserError(_("No payment orders are linked to this request.")) return { 'name': _('Payment Orders'), 'type': 'ir.actions.act_window', 'res_model': 'payment.orders', 'view_mode': 'tree,form', 'domain': [('id', 'in', self.payment_order_ids.ids)], 'context': {'create': False}, }