Odoo17操作下面代码的模块时出现问题,请教如何解决此错误
访问错误
啊哦看来你无意中发现了一些绝密记录。
对不起,Mitchell Admin (id=2)没有'读取'来访问:
- 工作中心, Assembly Line 1 (mrp.workcenter: 1, company=My Company (San Francisco))
归咎于以下规则:
- mrp_workcenter multi-company
注意:这可能是一个多公司问题。切换公司可能会有帮助 - 在 Odoo 中,而不是在现实生活中!
如果你真的非常需要访问,也许你可以用一批新鲜出炉的饼干来征服友好的管理员。
from odoo import models, fields, api, _, _lt
import json
from itertools import groupby # -*- coding: utf-8 -*-
import io
from odoo import models, api, _
from odoo.tools.misc import xlsxwriter
import datetime
from datetime import date
from odoo.exceptions import ValidationError
class YzAccountCostReport(models.Model):
_name = 'yz.account.cost.report'
_inherit = 'ks.dynamic.financial.reports'
_description = '成本费用报表'
ks_dfr_account_type_ids = fields.Many2many('ks.dynamic.financial.reports.account',
'ks_dfr_cost_account_type_reports',
'report_id', 'account_type_id', 'Account Types')
ks_df_report_account_ids = fields.Many2many('account.account', 'ks_df_report_cost_account_ids', 'report_line_id',
'account_id', 'Accounts')
def ks_df_account_report_data(self, ks_df_informations):
def custom_key(item):
return item[0], item[3]
result = {
'lines': [],
'heads': []
}
origin_heads = []
origin_lines = []
analytic_line = self.env['account.analytic.line']
domain = []
if ks_df_informations.get('accounts', False):
account_ids = [rec['id'] for rec in list(filter(lambda x: x['selected'], ks_df_informations['accounts']))]
if account_ids:
domain += [('general_account_id', 'in', account_ids)]
period_ids = analytic_line.search(domain).mapped('period_id')
if ks_df_informations.get('periods', False):
cur_period_id = [rec['id'] for rec in list(filter(lambda x: x['selected'], ks_df_informations['periods']))][0]
if period_ids:
domain += [('period_id', '=', cur_period_id)]
else:
cur_period_id = self.env['yz.finance.period'].search([('date_from', '<=', date.today()),
('date_to', '>=', date.today()),
('period_type', '=', 'month_period'),
('company_id','=',self.env.company.id)]).id
domain += [('period_id', '=', cur_period_id)]
if self.env['yz.finance.period'].browse(cur_period_id).account_ids.ids:
domain += [('general_account_id','in', self.env['yz.finance.period'].browse(cur_period_id).account_ids.ids)]
if ks_df_informations.get('type', False):
select_type = [rec['name'] for rec in list(filter(lambda x: x['selected'], ks_df_informations['type']))]
datas = []
result_data = {}
lines = analytic_line.search(domain)
ks_df_informations['accounts'] = ks_df_informations['accounts'] if ks_df_informations.get('accounts', []) else [
{'id': rec.id, 'name': rec.code + ' ' + rec.name, 'selected': False} for rec in
lines.mapped('general_account_id')]
ks_df_informations['periods'] = ks_df_informations['periods'] if ks_df_informations.get('periods', []) else [
{'id': rec.id, 'name': rec.code, 'selected': True if cur_period_id == rec.id else False} for rec in
period_ids]
for line in lines:
# [项目,部门,工作中心,内部, 金额]
datas.append([line.account_id and line.account_id.name or '',
line.x_plan2_id and line.x_plan2_id.name or '',
line.x_plan5_id and line.x_plan5_id.name or '',
line.x_plan3_id and line.x_plan3_id.name or '',
line.amount])
result['heads'] = ['']
for key, group in groupby(sorted(datas, key=custom_key), key=custom_key):
origin_heads.append('-'.join(key))
result['heads'].append('-'.join(key))
cols = len(result['heads']) - 1
if not select_type and self.env[self.env.context.get('model')].browse(self.env.context.get('id', 0)).ks_name in ['费用表需分配']:
select_type = ['部门']
if not select_type:
for data in datas:
# 部门维度
if not data[1]:
continue
if not result_data.get(data[1], False):
result_data[data[1]] = [0] * cols
index = result['heads'].index(data[0] + '-' + data[3]) - 1
result_data[data[1]][index] += data[4]
for data in datas:
# 工作中心维度
if not data[2]:
continue
if not result_data.get(data[2], False):
result_data[data[2]] = [0] * cols
index = result['heads'].index(data[0] + '-' + data[3]) - 1
result_data[data[2]][index] += data[4]
for type in select_type:
if type == '部门':
for data in datas:
# 部门维度
if not data[1]:
continue
if not result_data.get(data[1], False):
result_data[data[1]] = [0] * cols
index = result['heads'].index(data[0] + '-' + data[3]) - 1
result_data[data[1]][index] += data[4]
if type == '工作中心':
for data in datas:
if not data[2]:
continue
# 工作中心维度
if not result_data.get(data[2], False):
result_data[data[2]] = [0] * cols
index = result['heads'].index(data[0] + '-' + data[3]) - 1
result_data[data[2]][index] += data[4]
for key, values in result_data.items():
origin_lines.append([key] + values)
result['lines'].append([key] + values)
if self.env[self.env.context.get('model')].browse(self.env.context.get('id', 0)).ks_name == '分析分配':
return result
domain = []
if ks_df_informations.get('periods', False):
period_ids = [rec['id'] for rec in list(filter(lambda x: x['selected'], ks_df_informations['periods']))]
if period_ids:
domain += [('period_id', 'in', period_ids)]
else:
domain += [('period_id', '!=', False)]
# 获取工作中心列表
mw_datas = self.env['yz.mrp.workorder.cost.fee'].search(domain)
work_center = {}
wc_name = []
for wc in mw_datas:
if work_center.get(wc.workcenter_id.name, ''):
work_center[wc.workcenter_id.name] = round(work_center[wc.workcenter_id.name] + wc.period_gs,2)
else:
work_center[wc.workcenter_id.name] = wc.period_gs
wc_name.append(wc.workcenter_id.name)
result['heads'] = ['部门', '', '金额'] + wc_name + ['合计']
total = round(sum(list(work_center.values())),2)
gs_list = list(work_center.values())
result['lines'] = [['本期工时','',''] + gs_list + [total]]
ratios = [(item / total) if total else 0 for item in gs_list]
new_ratios = [(round(ratio / sum(ratios),2)) if sum(ratios) else 0 for ratio in ratios]
result['lines'] += [['系数','',''] + [str(round(ratio / sum(ratios),2)*100) if sum(ratios) else '0' + '%' for ratio in ratios] + [1]]
temp_lines = []
for k,line in enumerate(origin_lines):
for j,head in enumerate(origin_heads):
if line[j+1] == 0:
continue
temp = [line[0], head, line[j+1]]
temp += [round(line[j+1]*ratio,2) for ratio in new_ratios]
temp += [line[j+1]]
result['lines'].append(temp)
temp_lines.append(temp)
ks_df_informations['periods'] = ks_df_informations['periods'] if ks_df_informations.get('periods', []) else [
{'id': rec.id, 'name': rec.code, 'selected': False} for rec in
lines.mapped('period_id')]
if self.env[self.env.context.get('model')].browse(self.env.context.get('id', 0)).ks_name == '费用表需分配':
return result
if self.env[self.env.context.get('model')].browse(self.env.context.get('id', 0)).ks_name == '费用表分配合计':
result['lines'] = []
wc_lines = []
bm_lines = []
for type in select_type:
if type == '工作中心':
#工作中心
wc_data = {}
for data in datas:
if not data[2]:
continue
# 工作中心维度
if not wc_data.get(data[2], False):
wc_data[data[2]] = [0] * cols
index = origin_heads.index(data[0] + '-' + data[3])
wc_data[data[2]][index] += data[4]
for key, values in wc_data.items():
wc_lines.append([key] + values + [round(sum(values),2)])
if type == '部门':
for j, wc in enumerate(wc_name):
line_sum = 0
line = [0] * len(origin_heads)
for data in temp_lines:
if data[0] in wc_name:
# 部门数据里排除工作中心
continue
index = origin_heads.index(data[1])
line[index] = round(line[index] + data[3+j],2)
line_sum = round(line_sum + data[3+j],2)
line.insert(0, wc)
line.append(line_sum)
bm_lines.append(line)
if not select_type:
# 工作中心
wc_lines = []
wc_data = {}
for data in datas:
if not data[2]:
continue
# 工作中心维度
if not wc_data.get(data[2], False):
wc_data[data[2]] = [0] * cols
index = origin_heads.index(data[0] + '-' + data[3])
wc_data[data[2]][index] += data[4]
for key, values in wc_data.items():
wc_lines.append([key] + values + [round(sum(values),2)])
bm_lines = []
for j, wc in enumerate(wc_name):
line_sum = 0
line = [0] * len(origin_heads)
for data in temp_lines:
if data[0] in wc_name:
# 部门数据里排除工作中心
continue
index = origin_heads.index(data[1])
line[index] = round(line[index] + data[3+j],2)
line_sum = round(line_sum + data[3+j],2)
line.insert(0, wc)
line.append(line_sum)
bm_lines.append(line)
sums = []
for key,group in groupby(wc_lines+bm_lines, lambda x: x[0]):
lists = list(group)
temp = [rec[1:] for rec in lists]
datas = [round(sum(x),2) for x in zip(*temp)]
sums.append(datas)
result['lines'].append([key] + datas)
summed_values = [round(sum([inner[i] for inner in sums]),2) for i in range(len(sums[0]))] if sums else []
result['lines'].append(['合计'] + summed_values)
result['heads'] = [''] + origin_heads + ['小计']
#更新费用分配结果表
fields_data_mapp = {
'机物料消耗-机物料消耗': 'float_jwl',
'房租-房租': 'float_fz',
'运输费-运输费': 'float_ys',
'汽车费-汽车费': 'float_qc',
'能源费-水费': 'float_sf',
'能源费-电费': 'float_df',
'能源费-气费': 'float_qf',
'伙食费-伙食费': 'float_hs',
'修理费-修理费': 'float_xl',
'折旧-折旧': 'float_zj',
'工资-车间管理工资': 'float_glgz',
'工资-QC工资': 'float_qcgz',
'年终奖-年终奖': 'float_nzj'
}
line_data = { line[0]: line[1:-1] for line in result['lines']}
heads = [ fields_data_mapp[hd] for hd in result['heads'][1:-1]]
period_id = period_ids and period_ids[0] or cur_period_id
sql = """
SELECT id, head_id, name,
case when total_value = 0 then 0
else period_gs / total_value end AS ratio
FROM (SELECT ymwcf.id, ymwcf.head_id, m.name, ymwcf.period_gs, SUM(ymwcf.period_gs) OVER (PARTITION BY m.name) AS total_value
FROM yz_mrp_workorder_cost_fee ymwcf
JOIN mrp_workcenter m ON ymwcf.workcenter_id = m.id
WHERE ymwcf.period_id = {period_id}
) t
""".format(period_id=period_id)
self.env.cr.execute(sql)
res = self.env.cr.fetchall() or []
cost_obj = self.env['yz.mrp.workorder.cost.fee']
for rec in res:
if line_data.get(rec[2], False):
cost_data = cost_obj.browse(rec[0])
data = {'company_id': self.env.company.id}
values = [round(rec[3] * val, 8) for val in line_data[rec[2]]]
data.update(dict(zip(heads,values)))
cost_data.write(data)
return result
def _ks_get_df_informations(self, ks_earlier_informations=None):
ks_df_informations = {
'company_id': self.env.company.id,
'company_ids': self.env.context.get('allowed_company_ids', False) if self.env.context.get(
'allowed_company_ids', False) else [self.env.company.id],
'accounts': ks_earlier_informations and ks_earlier_informations.get('accounts', []) or [],
'periods': ks_earlier_informations and ks_earlier_informations.get('periods', []) or [],
'type': ks_earlier_informations and ks_earlier_informations.get('type', []) or [
{'id': 1, 'name': '部门', 'selected': False}, {'id': 2, 'name': '工作中心', 'selected': False}]
}
self.ks_construct_date_filter(ks_df_informations, ks_earlier_informations)
return ks_df_informations
def ks_get_dynamic_fin_info(self, ks_df_informations):
ks_df_informations = self._ks_get_df_informations(ks_df_informations)
report_data = self.ks_df_account_report_data(ks_df_informations)
info = {
'ks_df_informations': ks_df_informations,
'context': self.env.context,
'report_data': report_data
}
return info
def analytic_print_xlsx(self, ks_df_informations):
# if self.id == self.env.ref('ks_dynamic_financial_report.ks_df_tb0').id:
# return {
# 'type': 'ir_actions_account_report_download',
# 'data': {'model': self.env.context.get('model'),
# 'ks_df_informations': json.dumps(ks_df_informations),
# 'output_format': 'xlsx',
# 'financial_id': self.env.context.get('id'),
# }
# }
return {
'type': 'ir.actions.client',
'tag': 'ks_executexlsxReportDownloadAction',
'data': {'model': self.env.context.get('model'),
'ks_df_informations': json.dumps(ks_df_informations),
'output_format': 'xlsx',
'id': int(self.id),
'financial_id': self.env.context.get('id')
}
}
def get_xlsx(self, ks_df_informations, response=None):
if self.ks_name == '分析分配':
report_data = self.ks_df_account_report_data(ks_df_informations)
if ks_df_informations['date']['ks_start_date'] == False and ks_df_informations['date'][
'ks_end_date'] == False:
raise ValidationError(_('Sorry,Export file will not get download without date.'))
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
sheet = workbook.add_worksheet(self.display_name[:31])
workbook.close()
output.seek(0)
generated_file = output.read()
output.close()
return generated_file
else:
return super().get_xlsx(ks_df_informations=ks_df_informations, response=None)