Files
gzth/yuthon_report/models/pre_arrears_report.py
T
2026-06-18 19:34:22 +08:00

243 lines
11 KiB
Python

import datetime
import logging
from odoo import api, models
from .report_utils import _id_list
_logger = logging.getLogger(__name__)
class PreArrearsReport(models.Model):
_inherit = 'receivable.modify.line'
@api.model
def get_pre_arrears_report(self, params):
"""
前期欠收报表:
- Domain: due_date(应收开始)所在月 < 查询月(不含查询月)
- 数据源分两部分:
1. receivable.modify.line: 有 reconciliation_date 且 reconciliation_date月 > due_date月
且 reconciliation_date月 >= 查询月 → 欠收金额取 amount
2. property.accounts.receivable: is_reconciliation=False 且 due_date月 < 查询月
且 payout_date 为空 → 从未对过账且未收款,欠收金额取 submitted
- 按应收账单聚合,每张账单只出一行
"""
today = datetime.date.today()
this_month_first = today.replace(day=1)
date_start = params.get("date_start")
date_end = params.get("date_end")
summary_only = params.get("summary_only", False)
# 应收日期在查询月及之前(包含查询月)
cutoff_date = datetime.datetime.fromisoformat(date_end).date() if date_end else this_month_first
# 查询月范围(用于判断收款是否在查询月内)
query_month_start = datetime.datetime.fromisoformat(date_start).date() if date_start else this_month_first
query_month_end = datetime.datetime.fromisoformat(date_end).date() if date_end else this_month_first
# 提取筛选参数
keyword = params.get("keyword")
condition = params.get('condition')
# 多选标准化:partner_id 统一为列表
partner_id = _id_list(params.get('partner_id'))
company_id = _id_list(params.get('company_id'))
management_type_id = params.get('management_type_id')
property_id = params.get('property_id')
lessee_id = params.get('lessee_id')
contract_id = params.get('contract_id')
# ============================================================
# 第一部分:从 receivable.modify.line (对账明细) 取已对过账但欠收的数据
# ============================================================
# 核心逻辑:due_date < query_month_start(应收日期在查询月之前,不包含查询月)
domain = [
('receivable_id.due_date', '<', query_month_start),
('receivable_id.is_invalid', '!=', True),
]
if keyword:
domain += [
'|', '|',
('receivable_id.contract_id.contract_code', 'ilike', keyword),
('receivable_id.property_name', 'ilike', keyword),
('receivable_id.lessee_id.name', 'ilike', keyword),
]
if condition:
domain.append(('receivable_id.tenure_type', '=', condition))
if partner_id:
# 多选:片区管理员用 'in' 操作符
domain.append(('receivable_id.precinct_id', 'in', partner_id))
if company_id:
domain.append(('receivable_id.company_id', 'in', company_id))
if property_id:
domain.append(('receivable_id.property_ids', 'in', [property_id]))
if lessee_id:
domain.append(('receivable_id.lessee_id', '=', lessee_id))
if contract_id:
domain.append(('receivable_id.contract_id', '=', contract_id))
if management_type_id:
domain.append(('receivable_id.management_type_id', '=', management_type_id))
else:
domain.append(('receivable_id.management_type_id.name', 'not in', ['押金', '违约金']))
_logger.info("=== PRE_ARREARS Part1: modify.line search ===")
_logger.info("query_month_start=%s, query_month_end=%s", query_month_start, query_month_end)
_logger.info("Part1 domain: %s", domain)
lines = self.sudo().search(domain, order="receivable_id asc, reconciliation_date asc")
_logger.info("Part1 search found %s modify.line records", len(lines))
# 欠收条件:reconciliation_date 有值 且 所在月 > due_date月 且 >= 查询月
# (交晚了且查询月才收到,取amount)
due_month_start = query_month_start.replace(day=1)
lines = lines.filtered(
lambda l: l.reconciliation_date and
l.reconciliation_date.replace(day=1) > l.receivable_id.due_date.replace(day=1) and
l.reconciliation_date.replace(day=1) >= due_month_start
)
_logger.info("Part1 after欠收filter: %s records remain", len(lines))
# 按应收账单聚合
rec_map = {}
for line in lines:
rid = line.receivable_id.id
if rid not in rec_map:
rec_map[rid] = {'rec': line.receivable_id, 'amount': 0.0, 'payout_dates': [], 'discount_amount': 0.0}
# 有 reconciliation_date(交晚了),欠收金额取 amount
rec_map[rid]['amount'] += line.amount or 0.0
rec_map[rid]['payout_dates'].append(line.reconciliation_date)
# 应收金额 = original_amount - discount_amount(取 receivable_id 的值)
rec_map[rid]['discount_amount'] = line.receivable_id.discount_amount or 0.0
# ============================================================
# 第二部分:从 property.accounts.receivable 取 is_reconciliation=False 的记录
# 即:未对过账且未收款(payout_date为空)的应收账单,due_date月 < 查询月,欠收金额取 submitted
# ============================================================
covered_ids = list(rec_map.keys())
receivable_domain = [
('is_reconciliation', '=', False),
('due_date', '<', query_month_start),
('payout_date', '=', False),
('is_invalid', '!=', True),
]
if covered_ids:
receivable_domain.append(('id', 'not in', list(covered_ids)))
# 同样的筛选条件(去掉 receivable_id. 前缀,直接查 accounts.receivable 自身字段)
if keyword:
receivable_domain += [
'|', '|',
('contract_id.contract_code', 'ilike', keyword),
('property_name', 'ilike', keyword),
('lessee_id.name', 'ilike', keyword),
]
if condition:
receivable_domain.append(('tenure_type', '=', condition))
if partner_id:
# 多选:片区管理员用 'in' 操作符
receivable_domain.append(('precinct_id', 'in', partner_id))
if company_id:
receivable_domain.append(('company_id', 'in', company_id))
if property_id:
receivable_domain.append(('property_ids', 'in', [property_id]))
if lessee_id:
receivable_domain.append(('lessee_id', '=', lessee_id))
if contract_id:
receivable_domain.append(('contract_id', '=', contract_id))
if management_type_id:
receivable_domain.append(('management_type_id', '=', management_type_id))
else:
receivable_domain.append(('management_type_id.name', 'not in', ['押金', '违约金']))
unreconciled_receivables = self.env['property.accounts.receivable'].sudo().search(
receivable_domain, order="due_date asc")
_logger.info("Part2 从 accounts.receivable(is_reconciliation=False) 补充 %d 条", len(unreconciled_receivables))
for rec in unreconciled_receivables:
rid = rec.id
# 未对过账的应收账单,欠收金额 = submitted
rec_map[rid] = {
'rec': rec,
'amount': rec.submitted or 0.0,
'payout_dates': [],
'discount_amount': rec.discount_amount or 0.0,
}
# ============================================================
# 构建返回数据
# ============================================================
rows = []
total_amount = 0.0
if summary_only:
total_amount = sum(round(data['amount'], 2) for data in rec_map.values())
stats = [
{'name': '记录总数', 'amount': len(rec_map)},
{'name': '欠收总额', 'amount': round(total_amount, 2)},
]
return {"rows": [], "stats": stats}
for idx, (rid, data) in enumerate(rec_map.items(), start=1):
rec = data['rec']
contract = rec.contract_id
amount = round(data['amount'], 2)
total_amount += amount
# 物业穿透
property_val = ''
if contract and contract.lease_ids and contract.lease_ids[0].address_id:
prop = contract.lease_ids[0].address_id
property_val = {
'model': 'yuthon.property',
'id': prop.id,
'display_name': rec.property_name or prop.name,
}
elif rec:
property_val = rec.property_name or ''
# 应收开始日期
due_date_str = rec.due_date.strftime('%Y-%m-%d') if rec.due_date else ''
# 应收结束日期
due_date_end_str = rec.due_date_end.strftime('%Y-%m-%d') if rec.due_date_end else ''
# 收款日期(取所有收款日期,用逗号分隔)
payout_dates = data.get('payout_dates', [])
payout_date_str = ', '.join([d.strftime('%Y-%m-%d') for d in sorted(set(payout_dates))]) if payout_dates else ''
# 应收金额 = original_amount - discount_amount
receivable_amount = round((rec.original_amount or 0.0) - (data.get('discount_amount', 0.0) or 0.0), 2)
rows.append({
"序号": idx,
"合同编号": {
'model': 'property.lease.contract',
'id': contract.id,
'display_name': contract.contract_code,
'view_id': self.env.ref('yuthon_property_approval.view_property_lease_contract_form1').id,
} if contract else "",
"物业名称": property_val,
"承租方名称": {
'model': 'property.tenant.information',
'id': rec.lessee_id.id,
'display_name': rec.lessee_id.name,
} if rec.lessee_id else "",
"收款类型": rec.management_type_id.name if rec.management_type_id else "",
"应收开始日期": due_date_str,
"应收结束日期": due_date_end_str,
"收款日期": payout_date_str,
"金额": amount,
"应收金额": receivable_amount,
"所属公司": contract.lessor_id.name if contract and contract.lessor_id else "",
"管理员": {
'model': 'res.users',
'id': rec.admin_id.id,
'display_name': rec.admin_id.name,
} if rec.admin_id else "",
})
stats = [
{'name': '记录总数', 'amount': len(rows)},
{'name': '欠收总额', 'amount': round(total_amount, 2)},
]
return {"rows": rows, "stats": stats}