diff --git a/yuthon_catering/models/yuthon_catering.py b/yuthon_catering/models/yuthon_catering.py index 342b623f4..b2471791d 100644 --- a/yuthon_catering/models/yuthon_catering.py +++ b/yuthon_catering/models/yuthon_catering.py @@ -36,6 +36,64 @@ class YuthonCatering(models.Model): ('confirmed', '已确认'), ], default='unconfirmed', string='状态') + def _recompute_related_meal_expenses(self): + """当 yuthon.catering 数据变化时,主动触发关联 yuthon.meal.expenses 重算""" + for record in self: + if not record.employee_id or not record.date: + continue + year = str(record.date.year) + month = str(record.date.month) + meal_records = self.env['yuthon.meal.expenses'].search([ + ('employee_id', '=', record.employee_id.id), + ('select_year', '=', year), + ('select_time', '=', month), + ]) + if meal_records: + meal_records._compute_catering_counts() + + def write(self, vals): + # 记录写入前的员工和日期(防止改了 employee_id 或 date 后找不到旧记录) + old_data = [(r.employee_id, r.date) for r in self] + result = super().write(vals) + # 触发旧记录关联的 meal.expenses 重算 + for emp, date in old_data: + if emp and date: + year = str(date.year) + month = str(date.month) + meal_records = self.env['yuthon.meal.expenses'].search([ + ('employee_id', '=', emp.id), + ('select_year', '=', year), + ('select_time', '=', month), + ]) + if meal_records: + meal_records._compute_catering_counts() + # 如果改了 employee_id 或 date,也触发新记录 + if 'employee_id' in vals or 'date' in vals: + self._recompute_related_meal_expenses() + return result + + @api.model_create_multi + def create(self, vals_list): + records = super().create(vals_list) + records._recompute_related_meal_expenses() + return records + + def unlink(self): + # 删除前先收集关联信息 + related_info = [(r.employee_id, r.date) for r in self if r.employee_id and r.date] + result = super().unlink() + for emp, date in related_info: + year = str(date.year) + month = str(date.month) + meal_records = self.env['yuthon.meal.expenses'].search([ + ('employee_id', '=', emp.id), + ('select_year', '=', year), + ('select_time', '=', month), + ]) + if meal_records: + meal_records._compute_catering_counts() + return result + def task_catering22(self): cat_ids = self.env["yuthon.catering"].browse(self._context.get('active_ids', self._context.get('active_id'))) for cat in cat_ids: