GoodERP
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

596 行
20KB

  1. # Copyright 2016 上海开阖软件有限公司 (http://www.osbzr.com)
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. from odoo import api, fields, models
  4. from odoo.exceptions import UserError
  5. BALANCE_DIRECTIONS_TYPE = [
  6. ('in', '借'),
  7. ('out', '贷')]
  8. class FinanceAccountType(models.Model):
  9. """ 会计要素
  10. """
  11. _name = 'finance.account.type'
  12. _description = '会计要素'
  13. _rec_name = 'name'
  14. _order = 'name ASC'
  15. name = fields.Char('名称', required=True, translate=True)
  16. active = fields.Boolean(string='启用', default="True")
  17. costs_types = fields.Selection([
  18. ('assets', '资产'),
  19. ('debt', '负债'),
  20. ('equity', '所有者权益'),
  21. ('in', '收入类'),
  22. ('out', '费用类'),
  23. ('cost', '成本类'),
  24. ],'类型', required=True,help='用于会计报表的生成。')
  25. class FinanceAccount(models.Model):
  26. '''科目'''
  27. _name = 'finance.account'
  28. _order = "code"
  29. _description = '会计科目'
  30. _parent_store = True
  31. @api.depends('parent_id')
  32. def _compute_level(self):
  33. for record in self:
  34. level = 1
  35. parent = record.parent_id
  36. while parent:
  37. level = level + 1
  38. parent = parent.parent_id
  39. record.level = level
  40. @api.depends('child_ids', 'voucher_line_ids', 'account_type')
  41. def compute_balance(self):
  42. """
  43. 计算会计科目的当前余额
  44. :return:
  45. """
  46. for record in self:
  47. # 上级科目按下级科目汇总
  48. if record.account_type == 'view':
  49. lines = self.env['voucher.line'].search(
  50. [('account_id', 'child_of', record.id),
  51. ('voucher_id.state', '=', 'done')])
  52. record.debit = sum((line.debit) for line in lines)
  53. record.credit = sum((line.credit) for line in lines)
  54. record.balance = record.debit - record.credit
  55. # 下级科目按记账凭证计算
  56. else:
  57. record.debit = sum(record.voucher_line_ids.filtered(
  58. lambda self: self.state == 'done').mapped('debit'))
  59. record.credit = sum(record.voucher_line_ids.filtered(
  60. lambda self: self.state == 'done').mapped('credit'))
  61. record.balance = record.debit - record.credit
  62. def get_balance(self, period_id=False):
  63. ''' 科目当前或某期间的借方、贷方、差额 '''
  64. self.ensure_one()
  65. domain = []
  66. data = {}
  67. period = self.env['finance.period']
  68. if period_id:
  69. domain.append(('period_id', '=', period_id))
  70. if self.account_type == 'view':
  71. domain.extend([
  72. ('account_id', 'child_of', self.id),
  73. ('voucher_id.state', '=', 'done')])
  74. lines = self.env['voucher.line'].search(domain)
  75. debit = sum((line.debit) for line in lines)
  76. credit = sum((line.credit) for line in lines)
  77. balance = self.debit - self.credit
  78. data.update({'debit': debit, 'credit': credit, 'balance': balance})
  79. # 下级科目按记账凭证计算
  80. else:
  81. if period_id:
  82. period = self.env['finance.period'].browse(period_id)
  83. if period:
  84. debit = sum(self.voucher_line_ids.filtered(
  85. lambda self: self.period_id == period
  86. and self.state == 'done'
  87. ).mapped('debit'))
  88. credit = sum(self.voucher_line_ids.filtered(
  89. lambda self: self.period_id == period
  90. and self.state == 'done'
  91. ).mapped('credit'))
  92. balance = self.debit - self.credit
  93. else:
  94. debit = sum(self.voucher_line_ids.filtered(
  95. lambda self: self.state == 'done').mapped('debit'))
  96. credit = sum(self.voucher_line_ids.filtered(
  97. lambda self: self.state == 'done').mapped('credit'))
  98. balance = self.debit - self.credit
  99. data.update({'debit': debit, 'credit': credit, 'balance': balance})
  100. return data
  101. display_name = fields.Char(compute='_compute_display_name',store=False)
  102. name = fields.Char('名称', required=True, translate=True)
  103. code = fields.Char('编码', required=True)
  104. balance_directions = fields.Selection(
  105. [('in', '借'),('out', '贷')],'余额方向',
  106. required=True,
  107. help='根据科目的类型,判断余额方向是借方或者贷方!')
  108. auxiliary_financing = fields.Selection(
  109. [('customer', '客户'),
  110. ('supplier', '供应商'),
  111. ('member', '个人'),
  112. ('project', '项目'),
  113. ('department', '部门'),
  114. ('goods', '存货'),
  115. ],
  116. '辅助核算',
  117. help='辅助核算是对账务处理的一种补充,即实现更广泛的账务处理,\n\
  118. 以适应企业管理和决策的需要.辅助核算一般通过核算项目来实现')
  119. costs_types = fields.Selection(related='user_type.costs_types')
  120. account_type = fields.Selection(
  121. string='科目类型',
  122. selection=[('view', 'View'), ('normal', 'Normal')],
  123. default='normal')
  124. user_type = fields.Many2one(
  125. string='会计要素',
  126. comodel_name='finance.account.type',
  127. ondelete='restrict',
  128. required=True,
  129. default=lambda s: s.env.get(
  130. 'finance.account.type').search([], limit=1).id)
  131. parent_left = fields.Integer('Left Parent', index=1)
  132. parent_right = fields.Integer('Right Parent', index=1)
  133. parent_id = fields.Many2one(
  134. string='上级科目',
  135. comodel_name='finance.account',
  136. ondelete='restrict',
  137. domain="[('account_type','=','view')]")
  138. parent_path = fields.Char(index=True)
  139. child_ids = fields.One2many(
  140. string='下级科目',
  141. comodel_name='finance.account',
  142. inverse_name='parent_id', )
  143. level = fields.Integer(string='科目级次', compute='_compute_level')
  144. currency_id = fields.Many2one('res.currency', '外币币别')
  145. exchange = fields.Boolean('是否期末调汇')
  146. active = fields.Boolean('启用', default=True)
  147. company_id = fields.Many2one(
  148. 'res.company',
  149. string='公司',
  150. change_default=True,
  151. default=lambda self: self.env.company)
  152. voucher_line_ids = fields.One2many(
  153. string='Voucher Lines',
  154. comodel_name='voucher.line',
  155. inverse_name='account_id', )
  156. debit = fields.Float(
  157. string='借方',
  158. compute='compute_balance',
  159. store=False,
  160. digits='Amount')
  161. credit = fields.Float(
  162. string='贷方',
  163. compute='compute_balance',
  164. store=False,
  165. digits='Amount')
  166. balance = fields.Float('当前余额',
  167. compute='compute_balance',
  168. store=False,
  169. digits='Amount',
  170. help='科目的当前余额',
  171. )
  172. restricted_debit = fields.Boolean(
  173. string='借方限制使用',
  174. help='手工凭证时, 借方限制使用'
  175. )
  176. restricted_debit_msg = fields.Char(
  177. string='借方限制提示消息',
  178. )
  179. restricted_credit = fields.Boolean(
  180. string='贷方限制使用',
  181. help='手工凭证时, 贷方限制使用'
  182. )
  183. restrict_credit_msg = fields.Char(
  184. string='贷方限制提示消息',
  185. )
  186. source = fields.Selection(
  187. string='创建来源',
  188. selection=[('init', '初始化'), ('manual', '手工创建')], default='manual'
  189. )
  190. _sql_constraints = [
  191. ('name_uniq', 'unique(name)', '科目名称必须唯一。'),
  192. ('code', 'unique(code)', '科目编码必须唯一。'),
  193. ]
  194. @api.depends('name', 'code')
  195. def name_get(self):
  196. """
  197. 在其他model中用到account时在页面显示 code name balance如:2202 应付账款 当前余额(更有利于会计记账)
  198. :return:
  199. """
  200. result = []
  201. for line in self:
  202. account_name = line.code + ' ' + line.name
  203. if line.env.context.get('show_balance'):
  204. account_name += ' ' + str(line.balance)
  205. result.append((line.id, account_name))
  206. return result
  207. @api.depends('code', 'name')
  208. def _compute_display_name(self):
  209. """
  210. 在其他model中用到account时在页面显示 code name balance如:2202 应付账款 当前余额(更有利于会计记账)
  211. :return:
  212. 替代 name_get, 注意原来的 name_get 被name_search使用, 不能删除
  213. """
  214. for record in self:
  215. record.display_name = record.code + ' ' + record.name
  216. if record.env.context.get('show_balance'):
  217. record.display_name += ' ' + str(record.balance)
  218. @api.model
  219. def name_search(self, name, args=None, operator='ilike', limit=100):
  220. '''会计科目按名字和编号搜索'''
  221. args = args or []
  222. domain = []
  223. if name:
  224. res_id = self.search([('code', '=', name)]+args)
  225. if res_id:
  226. return res_id.name_get()
  227. domain = ['|', ('code', '=ilike', name + '%'),
  228. ('name', operator, name)]
  229. accounts = self.search(domain + args, limit=limit)
  230. return accounts.name_get()
  231. def get_smallest_code_account(self):
  232. """
  233. 取得最小的code对应的account对象
  234. :return: 最小的code 对应的对象
  235. """
  236. finance_account_row = self.search([], order='code')
  237. return finance_account_row and finance_account_row[0]
  238. def get_max_code_account(self):
  239. """
  240. 取得最大的code对应的account对象
  241. :return: 最大的code 对应的对象
  242. """
  243. finance_account_row = self.search([], order='code desc')
  244. return finance_account_row and finance_account_row[0]
  245. def write(self, values):
  246. """
  247. 限制科目修改条件
  248. """
  249. for record in self:
  250. if record.source == 'init' and record.env.context.get(
  251. 'modify_from_webclient', False):
  252. raise UserError('不能修改预设会计科目!')
  253. if record.voucher_line_ids and record.env.context.get(
  254. 'modify_from_webclient', False):
  255. raise UserError('不能修改有记账凭证的会计科目!')
  256. return super(FinanceAccount, self).write(values)
  257. def unlink(self):
  258. """
  259. 限制科目删除条件
  260. """
  261. parent_ids = []
  262. for record in self:
  263. if record.parent_id not in parent_ids:
  264. parent_ids.append(record.parent_id)
  265. if record.source == 'init' and record.env.context.get(
  266. 'modify_from_webclient', False):
  267. raise UserError('不能删除预设会计科目!')
  268. if record.voucher_line_ids:
  269. raise UserError('不能删除有记账凭证的会计科目!')
  270. if len(record.child_ids) != 0:
  271. raise UserError('不能删除有下级科目的会计科目!')
  272. '''
  273. 此处 https://github.com/osbzr/gooderp_addons/
  274. commit/a4c3f2725ba602854149001563002dcedaa89e3d
  275. 导致代码xml中删除数据时发生混乱,暂时拿掉
  276. ir_record = self.env['ir.model.data'].search(
  277. [('model','=','finance.account'),('res_id','=', record.id)])
  278. if ir_record:
  279. ir_record.res_id = record.parent_id.id
  280. '''
  281. result = super(FinanceAccount, self).unlink()
  282. # 如果 下级科目全删除了,则将 上级科目设置为 普通科目
  283. for parent_id in parent_ids:
  284. if len(parent_id.child_ids.ids) == 0:
  285. parent_id.with_context(
  286. modify_from_webclient=False).account_type = 'normal'
  287. return result
  288. def button_add_child(self):
  289. self.ensure_one()
  290. view = self.env.ref('finance.view_wizard_account_add_child_form')
  291. return {
  292. 'name': '增加下级科目',
  293. 'type': 'ir.actions.act_window',
  294. 'view_mode': 'form',
  295. 'res_model': 'wizard.account.add.child',
  296. 'views': [(view.id, 'form')],
  297. 'view_id': view.id,
  298. 'target': 'new',
  299. 'context': dict(
  300. self.env.context, active_id=self.id,
  301. active_ids=[self.id],
  302. modify_from_webclient=False),
  303. }
  304. class WizardAccountAddChild(models.TransientModel):
  305. """ 向导,用于新增下级科目.
  306. """
  307. _name = 'wizard.account.add.child'
  308. _description = 'Wizard Account Add Child'
  309. parent_id = fields.Many2one(
  310. string='上级科目',
  311. comodel_name='finance.account',
  312. ondelete='set null',
  313. )
  314. parent_path = fields.Char(index=True)
  315. parent_name = fields.Char(
  316. string='上级科目名称',
  317. related='parent_id.name',
  318. readonly=True,
  319. )
  320. parent_code = fields.Char(
  321. string='上级科目编码',
  322. related='parent_id.code',
  323. readonly=True,
  324. )
  325. account_code = fields.Char(
  326. string='新增编码', required=True
  327. )
  328. currency_id = fields.Many2one(
  329. 'res.currency', '外币币别')
  330. full_account_code = fields.Char(
  331. string='完整科目编码',
  332. )
  333. account_name = fields.Char(
  334. string='科目名称', required=True
  335. )
  336. account_type = fields.Selection(
  337. string='Account Type',
  338. related='parent_id.account_type'
  339. )
  340. has_journal_items = fields.Boolean(
  341. string='Has Journal Items',
  342. )
  343. @api.model
  344. def default_get(self, fields):
  345. if len(self.env.context.get('active_ids', list())) > 1:
  346. raise UserError("一次只能为一个科目增加下级科目!")
  347. account_id = self.env.context.get('active_id')
  348. account = self.env['finance.account'].browse(account_id)
  349. has_journal_items = False
  350. if account.voucher_line_ids:
  351. has_journal_items = True
  352. if account.level >= int(self.env['ir.default']._get(
  353. 'finance.config.settings', 'defaul_account_hierarchy_level')):
  354. raise UserError(
  355. '选择的科目层级是%s级,已经是最低层级科目了,不能建立在它下面建立下级科目!'
  356. % account.level)
  357. res = super(WizardAccountAddChild, self).default_get(fields)
  358. res.update({
  359. 'parent_id': account_id,
  360. 'has_journal_items': has_journal_items
  361. })
  362. return res
  363. def create_account(self):
  364. self.ensure_one()
  365. account_type = self.parent_id.account_type
  366. new_account = False
  367. full_account_code = '%s%s' % (self.parent_code, self.account_code)
  368. if account_type == 'normal':
  369. # 挂账科目,需要对现有凭证进行科目转换
  370. # step1, 建新科目
  371. new_account = self.parent_id.copy(
  372. {
  373. 'code': full_account_code,
  374. 'name': self.account_name,
  375. 'account_type': 'normal',
  376. 'source': 'manual',
  377. 'currency_id': self.currency_id.id,
  378. 'parent_id': self.parent_id.id
  379. }
  380. )
  381. # step2, 将关联凭证改到新科目
  382. self.env['voucher.line'].search(
  383. [('account_id', '=', self.parent_id.id)]).write(
  384. {'account_id': new_account.id})
  385. # step3, 老科目改为 视图
  386. self.parent_id.write({
  387. 'account_type': 'view',
  388. })
  389. elif account_type == 'view':
  390. # 直接新增下级科目,无需转换科目
  391. new_account = self.parent_id.copy(
  392. {
  393. 'code': full_account_code,
  394. 'name': self.account_name,
  395. 'account_type': 'normal',
  396. 'source': 'manual',
  397. 'currency_id': self.currency_id.id,
  398. 'parent_id': self.parent_id.id
  399. }
  400. )
  401. if not new_account: # pragma: no cover
  402. raise UserError('新科目创建失败!')
  403. view = self.env.ref('finance.finance_account_list')
  404. return {
  405. 'name': '科目',
  406. 'type': 'ir.actions.act_window',
  407. 'view_mode': 'list',
  408. 'res_model': 'finance.account',
  409. 'views': [(view.id, 'list')],
  410. 'view_id': view.id,
  411. 'target': 'current',
  412. 'context': dict(
  413. self.env.context,
  414. hide_button=False,
  415. modify_from_webclient=True)
  416. }
  417. @api.onchange('account_code')
  418. def _onchange_account_code(self):
  419. def is_number(chars):
  420. try:
  421. int(chars)
  422. return True
  423. except ValueError:
  424. return False
  425. if self.account_code and not is_number(self.account_code):
  426. self.account_code = '01'
  427. return {
  428. 'warning': {
  429. 'title': '错误',
  430. 'message': '科目代码必须是数字'
  431. }
  432. }
  433. default_child_step = self.env['ir.default']._get(
  434. 'finance.config.settings', 'defaul_child_step')
  435. if self.account_code:
  436. self.full_account_code = "%s%s" % (
  437. self.parent_code, self.account_code)
  438. if self.account_code and len(
  439. self.account_code) != int(default_child_step):
  440. self.account_code = '01'
  441. self.full_account_code = self.parent_code
  442. return {
  443. 'warning': {
  444. 'title': '错误',
  445. 'message': '下级科目编码长度与"下级科目编码递增长度"规则不符合!'
  446. }
  447. }
  448. class AuxiliaryFinancing(models.Model):
  449. '''辅助核算'''
  450. _name = 'auxiliary.financing'
  451. _description = '辅助核算'
  452. code = fields.Char('编码')
  453. name = fields.Char('名称')
  454. type = fields.Selection([
  455. ('member', '个人'),
  456. ('project', '项目'),
  457. ('department', '部门'),
  458. ], '分类', default=lambda self: self.env.context.get('type'))
  459. active = fields.Boolean('启用', default=True)
  460. company_id = fields.Many2one(
  461. 'res.company',
  462. string='公司',
  463. change_default=True,
  464. default=lambda self: self.env.company)
  465. _sql_constraints = [
  466. ('name_uniq', 'unique(name)', '辅助核算不能重名')
  467. ]
  468. class ResCompany(models.Model):
  469. '''继承公司对象,添加字段'''
  470. _inherit = 'res.company'
  471. cogs_account = fields.Many2one(
  472. 'finance.account',
  473. '主营业务成本科目',
  474. ondelete='restrict',
  475. help='主营业务成本科目,销项发票开具时会用到。')
  476. profit_account = fields.Many2one(
  477. 'finance.account',
  478. '本年利润科目',
  479. ondelete='restrict',
  480. help='本年利润科目,本年中盈利的科目,在结转时会用到。')
  481. remain_account = fields.Many2one(
  482. 'finance.account', '未分配利润科目', ondelete='restrict', help='未分配利润科目。')
  483. import_tax_account = fields.Many2one(
  484. 'finance.account',
  485. "进项税科目",
  486. ondelete='restrict',
  487. help='进项税额,是指纳税人购进货物、加工修理修配劳务、服务、无形资产或者不动产,支付或者负担的增值税额。')
  488. output_tax_account = fields.Many2one(
  489. 'finance.account', "销项税科目", ondelete='restrict')
  490. operating_cost_account_id = fields.Many2one(
  491. 'finance.account',
  492. ondelete='restrict',
  493. string='生产费用科目',
  494. help='用在组装拆卸的费用上')
  495. class BankAccount(models.Model):
  496. _inherit = 'bank.account'
  497. account_id = fields.Many2one(
  498. 'finance.account',
  499. '科目',
  500. domain="[('account_type','=','normal')]")
  501. currency_id = fields.Many2one(
  502. 'res.currency', '外币币别', related='account_id.currency_id', store=True)
  503. currency_amount = fields.Float('外币金额', digits='Amount')
  504. class CoreCategory(models.Model):
  505. """继承core category,添加科目类型"""
  506. _inherit = 'core.category'
  507. account_id = fields.Many2one(
  508. 'finance.account',
  509. '科目',
  510. help='科目',
  511. domain="[('account_type','=','normal')]")
上海开阖软件有限公司 沪ICP备12045867号-1