GoodERP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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