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.

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