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.

843 lines
37KB

  1. # Copyright 2016 上海开阖软件有限公司 (http://www.osbzr.com)
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. from odoo import fields, models, api, _
  4. from odoo.exceptions import UserError
  5. from datetime import datetime
  6. from odoo.tools import float_compare, float_is_zero
  7. from odoo.exceptions import ValidationError
  8. # 采购订单确认状态可选值
  9. BUY_ORDER_STATES = [
  10. ('draft', '草稿'),
  11. ('done', '已确认'),
  12. ('cancel', '已作废')]
  13. # 字段只读状态
  14. READONLY_STATES = {
  15. 'done': [('readonly', True)],
  16. 'cancel': [('readonly', True)],
  17. }
  18. class BuyOrder(models.Model):
  19. _name = "buy.order"
  20. _inherit = ['mail.thread', 'mail.activity.mixin']
  21. _description = "采购订单"
  22. _order = 'date desc, id desc'
  23. @api.depends('line_ids.subtotal', 'discount_amount')
  24. def _compute_amount(selfs):
  25. '''当订单行和优惠金额改变时,改变成交金额'''
  26. for self in selfs:
  27. total = sum(line.subtotal for line in self.line_ids)
  28. self.amount = total - self.discount_amount
  29. self.untax_amount = sum(line.amount for line in self.line_ids)
  30. self.tax_amount = sum(line.tax_amount for line in self.line_ids)
  31. @api.depends('line_ids.quantity')
  32. def _compute_qty(selfs):
  33. '''当订单行数量改变时,更新总数量'''
  34. for self in selfs:
  35. self.total_qty = sum(line.quantity for line in self.line_ids)
  36. @api.depends('receipt_ids.state')
  37. def _get_buy_goods_state(selfs):
  38. '''返回收货状态'''
  39. for self in selfs:
  40. if all(line.quantity_in == 0 for line in self.line_ids):
  41. if any(r.state == 'draft' for r in self.receipt_ids) or self.state=='draft':
  42. self.goods_state = '未入库'
  43. else:
  44. self.goods_state = '全部作废'
  45. elif any(line.quantity > line.quantity_in for line in self.line_ids):
  46. if any(r.state == 'draft' for r in self.receipt_ids):
  47. self.goods_state = '部分入库'
  48. else:
  49. self.goods_state = '部分入库剩余作废'
  50. else:
  51. self.goods_state = '全部入库'
  52. @api.model
  53. def _default_warehouse_dest_impl(self):
  54. if self.env.context.get('warehouse_dest_type'):
  55. return self.env['warehouse'].get_warehouse_by_type(
  56. self.env.context.get('warehouse_dest_type'), False)
  57. @api.model
  58. def _default_warehouse_dest(self):
  59. '''获取默认调入仓库'''
  60. return self._default_warehouse_dest_impl()
  61. def _get_paid_amount(selfs):
  62. '''计算采购订单付款/退款状态'''
  63. for self in selfs:
  64. if not self.invoice_by_receipt: # 分期付款时
  65. money_invoices = self.env['money.invoice'].search([
  66. ('name', '=', self.name),
  67. ('state', '=', 'done')])
  68. self.paid_amount = sum([invoice.reconciled for invoice in money_invoices])
  69. else:
  70. receipts = self.env['buy.receipt'].search([('order_id', '=', self.id)])
  71. # 采购订单上输入预付款时
  72. money_order_rows = self.env['money.order'].search([('buy_id', '=', self.id),
  73. ('partner_id', '=', self.partner_id.id),
  74. ('state', '=', 'done')])
  75. self.paid_amount = sum([receipt.invoice_id.reconciled for receipt in receipts]) +\
  76. sum([order_row.to_reconcile for order_row in money_order_rows])
  77. @api.depends('receipt_ids')
  78. def _compute_receipt(self):
  79. for order in self:
  80. order.receipt_count = len([receipt for receipt in order.receipt_ids if not receipt.is_return])
  81. order.return_count = len([receipt for receipt in order.receipt_ids if receipt.is_return])
  82. @api.depends('receipt_ids')
  83. def _compute_invoice(self):
  84. for order in self:
  85. money_invoices = self.env['money.invoice'].search([
  86. ('name', '=', order.name)])
  87. order.invoice_ids = not money_invoices and order.receipt_ids.mapped('invoice_id') or money_invoices + order.receipt_ids.mapped('invoice_id')
  88. order.invoice_count = len(order.invoice_ids.ids)
  89. partner_id = fields.Many2one('partner', '供应商',
  90. ondelete='restrict',
  91. help='供应商')
  92. contact = fields.Char('联系人')
  93. address_id = fields.Many2one('partner.address', '地址',
  94. domain="[('partner_id', '=', partner_id)]",
  95. help='联系地址')
  96. date = fields.Date('单据日期',
  97. default=lambda self: fields.Date.context_today(self),
  98. index=True,
  99. copy=False,
  100. help="默认是订单创建日期")
  101. planned_date = fields.Date(
  102. '要求交货日期',
  103. default=lambda self: fields.Date.context_today(
  104. self),
  105. index=True,
  106. copy=False,
  107. help="订单的要求交货日期")
  108. name = fields.Char('单据编号',
  109. index=True,
  110. copy=False,
  111. help="采购订单的唯一编号,当创建时它会自动生成下一个编号。")
  112. type = fields.Selection([('buy', '采购'),
  113. ('return', '退货')],
  114. '类型',
  115. default='buy',
  116. help='采购订单的类型,分为采购或退货')
  117. ref = fields.Char('供应商订单号')
  118. warehouse_dest_id = fields.Many2one('warehouse',
  119. '调入仓库',
  120. required=True,
  121. default=_default_warehouse_dest,
  122. ondelete='restrict',
  123. help='将商品调入到该仓库')
  124. invoice_by_receipt = fields.Boolean(string="按收货结算",
  125. default=True,
  126. help='如未勾选此项,可在资金行里输入付款金额,订单保存后,采购人员可以单击资金行上的【确认】按钮。')
  127. line_ids = fields.One2many('buy.order.line',
  128. 'order_id',
  129. '采购订单行',
  130. copy=True,
  131. help='采购订单的明细行,不能为空')
  132. pay_method = fields.Many2one('pay.method',
  133. string='付款方式',
  134. ondelete='restrict')
  135. note = fields.Text('备注',
  136. help='单据备注')
  137. discount_rate = fields.Float('优惠率(%)',
  138. digits='Amount',
  139. help='整单优惠率')
  140. discount_amount = fields.Float('抹零',
  141. digits='Amount',
  142. help='整单优惠金额,可由优惠率自动计算出来,也可手动输入')
  143. amount = fields.Float('成交金额',
  144. store=True,
  145. compute='_compute_amount',
  146. digits='Amount',
  147. help='总金额减去优惠金额')
  148. untax_amount = fields.Float('不含税合计',
  149. store=True,
  150. compute='_compute_amount',
  151. digits='Amount')
  152. tax_amount = fields.Float('税金合计',
  153. store=True,
  154. compute='_compute_amount',
  155. digits='Amount')
  156. total_qty = fields.Float(string='数量合计', store=True, readonly=True,
  157. compute='_compute_qty',
  158. digits='Quantity',
  159. help='数量总计')
  160. prepayment = fields.Float('预付款',
  161. digits='Amount',
  162. help='输入预付款确认采购订单,会产生一张付款单')
  163. bank_account_id = fields.Many2one('bank.account',
  164. '结算账户',
  165. ondelete='restrict',
  166. help='用来核算和监督企业与其他单位或个人之间的债权债务的结算情况')
  167. approve_uid = fields.Many2one('res.users',
  168. '确认人',
  169. copy=False,
  170. ondelete='restrict',
  171. help='确认单据的人')
  172. state = fields.Selection(BUY_ORDER_STATES,
  173. '确认状态',
  174. readonly=True,
  175. help="采购订单的确认状态",
  176. index=True,
  177. copy=False,
  178. default='draft')
  179. goods_state = fields.Char('收货状态',
  180. compute=_get_buy_goods_state,
  181. default='未入库',
  182. store=True,
  183. help="采购订单的收货状态",
  184. index=True,
  185. copy=False)
  186. cancelled = fields.Boolean('已终止',
  187. help='该单据是否已终止')
  188. pay_ids = fields.One2many("payment.plan",
  189. "buy_id",
  190. string="付款计划",
  191. help='分批付款时使用付款计划')
  192. goods_id = fields.Many2one(
  193. 'goods', related='line_ids.goods_id', string='商品')
  194. receipt_ids = fields.One2many(
  195. 'buy.receipt', 'order_id', string='入库单', copy=False)
  196. receipt_count = fields.Integer(
  197. compute='_compute_receipt', string='入库单数量', default=0)
  198. return_count = fields.Integer(
  199. compute='_compute_receipt', string='退货单数量', default=0)
  200. invoice_ids = fields.One2many(
  201. 'money.invoice', compute='_compute_invoice', string='Invoices')
  202. invoice_count = fields.Integer(
  203. compute='_compute_invoice', string='Invoices Count', default=0)
  204. currency_id = fields.Many2one('res.currency',
  205. '外币币别',
  206. store=True,
  207. related='partner_id.s_category_id.account_id.currency_id',
  208. help='外币币别')
  209. is_multi_currency = fields.Boolean('多币种', related='company_id.is_multi_currency')
  210. express_type = fields.Char(string='承运商',)
  211. term_id = fields.Many2one('core.value', "贸易条款",
  212. domain=[('type', '=', 'price_term')],
  213. context={'type': 'price_term'})
  214. user_id = fields.Many2one(
  215. 'res.users',
  216. '经办人',
  217. ondelete='restrict',
  218. default=lambda self: self.env.user,
  219. help='单据经办人',
  220. )
  221. company_id = fields.Many2one(
  222. 'res.company',
  223. string='公司',
  224. change_default=True,
  225. default=lambda self: self.env.company)
  226. paid_amount = fields.Float(
  227. '已付金额', compute=_get_paid_amount, readonly=True)
  228. paid_no_goods = fields.Boolean('已付款未到货',compute="_compute_paid_no_goods",store=True)
  229. money_order_id = fields.Many2one(
  230. 'money.order',
  231. '预付款单',
  232. readonly=True,
  233. copy=False,
  234. help='输入预付款确认时产生的预付款单')
  235. details = fields.Html('明细',compute='_compute_details')
  236. project_id = fields.Many2one('project', string='项目')
  237. @api.depends('money_order_id.state','goods_state')
  238. def _compute_paid_no_goods(self):
  239. for o in self:
  240. o.paid_no_goods = False
  241. if o.state == 'done' and o.goods_state == '未入库' and o.paid_amount:
  242. if not all(line.goods_id.no_stock for line in self.line_ids):
  243. o.paid_no_goods = True
  244. @api.depends('line_ids')
  245. def _compute_details(self):
  246. for v in self:
  247. vl = {'col':[],'val':[]}
  248. vl['col'] = ['商品','数量','单价','已收']
  249. for l in v.line_ids:
  250. vl['val'].append([l.goods_id.name,l.quantity,l.price,l.quantity_in])
  251. v.details = v.company_id._get_html_table(vl)
  252. @api.onchange('discount_rate', 'line_ids')
  253. def onchange_discount_rate(self):
  254. '''当优惠率或采购订单行发生变化时,单据优惠金额发生变化'''
  255. total = sum(line.subtotal for line in self.line_ids)
  256. self.discount_amount = total * self.discount_rate * 0.01
  257. @api.onchange('partner_id')
  258. def onchange_partner_id(self):
  259. if self.partner_id:
  260. for line in self.line_ids:
  261. line.tax_rate = line.goods_id.get_tax_rate(line.goods_id, self.partner_id, 'buy')
  262. self.contact = self.partner_id.main_contact
  263. self.pay_method = self.partner_id.pay_method
  264. @api.onchange('address_id')
  265. def onchange_address_id(self):
  266. if self.address_id:
  267. self.contact = self.address_id.contact
  268. def _get_vals(self):
  269. '''返回创建 money_order 时所需数据'''
  270. flag = (self.type == 'buy' and 1 or -1) # 用来标志入库或退货
  271. amount = flag * self.amount
  272. this_reconcile = flag * self.prepayment
  273. money_lines = [{
  274. 'bank_id': self.bank_account_id.id,
  275. 'amount': this_reconcile,
  276. }]
  277. return {
  278. 'partner_id': self.partner_id.id,
  279. 'bank_name': self.partner_id.bank_name,
  280. 'bank_num': self.partner_id.bank_num,
  281. 'date': fields.Date.context_today(self),
  282. 'line_ids':
  283. [(0, 0, line) for line in money_lines],
  284. 'amount': amount,
  285. 'reconciled': this_reconcile,
  286. 'to_reconcile': amount,
  287. 'state': 'draft',
  288. 'origin_name': self.name,
  289. 'buy_id': self.id,
  290. }
  291. def generate_payment_order(self):
  292. '''由采购订单生成付款单'''
  293. # 入库单/退货单
  294. if self.prepayment:
  295. money_order = self.with_context(type='pay').env['money.order'].create(
  296. self._get_vals()
  297. )
  298. return money_order
  299. def buy_order_done(self):
  300. '''确认采购订单'''
  301. self.ensure_one()
  302. if self.state == 'done':
  303. raise UserError('请不要重复确认')
  304. if not self.line_ids:
  305. raise UserError('请输入商品明细行')
  306. for line in self.line_ids:
  307. # 检查属性是否填充,防止无权限人员不填就可以保存
  308. if line.using_attribute and not line.attribute_id:
  309. raise UserError('请输入商品:%s 的属性' % line.goods_id.name)
  310. if line.quantity <= 0 or line.price_taxed < 0:
  311. raise UserError('商品 %s 的数量和含税单价不能小于0' % line.goods_id.name)
  312. if line.tax_amount > 0 and self.currency_id:
  313. raise UserError('外贸免税')
  314. if not self.bank_account_id and self.prepayment:
  315. raise UserError('预付款不为空时,请选择结算账户')
  316. if not self.amount and self.env.context.get('func', '') != 'amount_not_value':
  317. vals = {}
  318. return self.env[self.sudo()._name].with_context(
  319. {'active_model': self.sudo()._name}
  320. ).open_dialog('amount_not_value', {
  321. 'message': '当前采购单价格为0,是否继续进行?',
  322. 'args': [vals],
  323. })
  324. # 采购预付款生成付款单
  325. money_order = self.generate_payment_order()
  326. self.buy_generate_receipt()
  327. self.approve_uid = self._uid
  328. self.write({
  329. 'money_order_id': money_order and money_order.id,
  330. 'state': 'done', # 为保证审批流程顺畅,否则,未审批就可审核
  331. })
  332. def amount_not_value(self, vals):
  333. for line in self.line_ids:
  334. line.onchange_price()
  335. self.buy_order_done()
  336. def buy_order_draft(self):
  337. '''撤销确认采购订单'''
  338. self.ensure_one()
  339. if self.state == 'draft':
  340. raise UserError('请不要重复撤销%s' % self._description)
  341. if any(r.state == 'done' for r in self.receipt_ids):
  342. raise UserError('该采购订单已经收货,不能撤销确认!')
  343. # 查找产生的发票并删除
  344. for inv in self.invoice_ids:
  345. if inv.state == 'done':
  346. raise UserError('该采购订单已经收票,不能撤销确认!')
  347. else:
  348. inv.unlink()
  349. for plan in self.pay_ids:
  350. plan.date_application = ''
  351. # 查找产生的入库单并删除
  352. self.receipt_ids.unlink()
  353. # 查找产生的付款单并撤销确认,删除
  354. for money_order_id in self.env['money.order'].search([('buy_id','=',self.id)]):
  355. if money_order_id.state == 'done':
  356. raise UserError('该采购订单已经付款,不能撤销确认!')
  357. money_order_id.unlink()
  358. self.approve_uid = False
  359. self.state = 'draft'
  360. def get_receipt_line(self, line, single=False):
  361. '''返回采购入库/退货单行'''
  362. self.ensure_one()
  363. qty = 0
  364. discount_amount = 0
  365. if single:
  366. qty = 1
  367. discount_amount = (line.discount_amount /
  368. ((line.quantity - line.quantity_in) or 1))
  369. else:
  370. qty = line.quantity - line.quantity_in
  371. discount_amount = line.discount_amount
  372. return {
  373. 'type': self.type == 'buy' and 'in' or 'out',
  374. 'buy_line_id': line.id,
  375. 'goods_id': line.goods_id.id,
  376. 'attribute_id': line.attribute_id.id,
  377. 'uos_id': line.goods_id.uos_id.id,
  378. 'goods_qty': qty,
  379. 'uom_id': line.uom_id.id,
  380. 'cost_unit': line.price,
  381. 'price': line.price,
  382. 'price_taxed': line.price_taxed,
  383. 'discount_rate': line.discount_rate,
  384. 'discount_amount': discount_amount,
  385. 'tax_rate': line.tax_rate,
  386. 'plan_date':self.planned_date,
  387. }
  388. def _generate_receipt(self, receipt_line):
  389. '''根据明细行生成入库单或退货单'''
  390. # 如果退货,warehouse_dest_id,warehouse_id要调换
  391. warehouse = (self.type == 'buy'
  392. and self.env.ref("warehouse.warehouse_supplier")
  393. or self.warehouse_dest_id)
  394. warehouse_dest = (self.type == 'buy'
  395. and self.warehouse_dest_id
  396. or self.env.ref("warehouse.warehouse_supplier"))
  397. rec = (self.type == 'buy' and self.with_context(is_return=False)
  398. or self.with_context(is_return=True))
  399. receipt_id = rec.env['buy.receipt'].create({
  400. 'partner_id': self.partner_id.id,
  401. 'warehouse_id': warehouse.id,
  402. 'warehouse_dest_id': warehouse_dest.id,
  403. 'date': self.planned_date,
  404. 'date_due': self.planned_date,
  405. 'order_id': self.id,
  406. 'ref': self.ref,
  407. 'origin': 'buy.receipt',
  408. 'discount_rate': self.discount_rate,
  409. 'discount_amount': self.discount_amount,
  410. 'invoice_by_receipt': self.invoice_by_receipt,
  411. 'currency_id': self.currency_id.id,
  412. 'currency_rate': self.env['res.currency'].get_rate_silent(
  413. self.date, self.currency_id.id) or 0,
  414. 'project_id': self.project_id.id,
  415. })
  416. if self.type == 'buy':
  417. receipt_id.write({'line_in_ids': [
  418. (0, 0, line) for line in receipt_line]})
  419. else:
  420. receipt_id.write({'line_out_ids': [
  421. (0, 0, line) for line in receipt_line]})
  422. return receipt_id
  423. def buy_generate_receipt(self):
  424. '''由采购订单生成采购入库/退货单'''
  425. self.ensure_one()
  426. receipt_line = [] # 采购入库/退货单行
  427. for line in self.line_ids:
  428. # 如果订单部分入库,则点击此按钮时生成剩余数量的入库单
  429. to_in = line.quantity - line.quantity_in
  430. if to_in <= 0:
  431. continue
  432. if line.goods_id.force_batch_one:
  433. i = 0
  434. while i < to_in:
  435. i += 1
  436. receipt_line.append(
  437. self.get_receipt_line(line, single=True))
  438. else:
  439. receipt_line.append(self.get_receipt_line(line, single=False))
  440. if not receipt_line:
  441. return {}
  442. self._generate_receipt(receipt_line)
  443. return {}
  444. def action_view_receipt(self):
  445. '''
  446. This function returns an action that display existing picking orders of given purchase order ids.
  447. When only one found, show the picking immediately.
  448. '''
  449. self.ensure_one()
  450. action = {
  451. 'name': '采购入库单',
  452. 'type': 'ir.actions.act_window',
  453. 'view_mode': 'form',
  454. 'res_model': 'buy.receipt',
  455. 'view_id': False,
  456. 'target': 'current',
  457. }
  458. #receipt_ids = sum([order.receipt_ids.ids for order in self], [])
  459. receipt_ids = [receipt.id for receipt in self.receipt_ids if not receipt.is_return]
  460. # choose the view_mode accordingly
  461. if len(receipt_ids) > 1:
  462. action['domain'] = "[('id','in',[" + \
  463. ','.join(map(str, receipt_ids)) + "])]"
  464. action['view_mode'] = 'list,form'
  465. elif len(receipt_ids) == 1:
  466. view_id = self.env.ref('buy.buy_receipt_form').id
  467. action['views'] = [(view_id, 'form')]
  468. action['res_id'] = receipt_ids and receipt_ids[0] or False
  469. return action
  470. def action_view_return(self):
  471. '''
  472. 该采购订单对应的退货单
  473. '''
  474. self.ensure_one()
  475. action = {
  476. 'name': '采购退货单',
  477. 'type': 'ir.actions.act_window',
  478. 'view_mode': 'form',
  479. 'res_model': 'buy.receipt',
  480. 'view_id': False,
  481. 'target': 'current',
  482. }
  483. receipt_ids = [receipt.id for receipt in self.receipt_ids if receipt.is_return]
  484. if len(receipt_ids) > 1:
  485. action['domain'] = "[('id','in',[" + \
  486. ','.join(map(str, receipt_ids)) + "])]"
  487. action['view_mode'] = 'list,form'
  488. elif len(receipt_ids) == 1:
  489. view_id = self.env.ref('buy.buy_return_form').id
  490. action['views'] = [(view_id, 'form')]
  491. action['res_id'] = receipt_ids and receipt_ids[0] or False
  492. return action
  493. def action_view_invoice(self):
  494. '''
  495. This function returns an action that display existing invoices of given purchase order ids( linked/computed via buy.receipt).
  496. When only one found, show the invoice immediately.
  497. '''
  498. self.ensure_one()
  499. if self.invoice_count == 0:
  500. return False
  501. action = {
  502. 'name': '结算单(供应商发票)',
  503. 'type': 'ir.actions.act_window',
  504. 'view_mode': 'form',
  505. 'res_model': 'money.invoice',
  506. 'view_id': False,
  507. 'target': 'current',
  508. }
  509. invoice_ids = self.invoice_ids.ids
  510. action['domain'] = "[('id','in',[" + \
  511. ','.join(map(str, invoice_ids)) + "])]"
  512. action['view_mode'] = 'list'
  513. return action
  514. class BuyOrderLine(models.Model):
  515. _name = 'buy.order.line'
  516. _description = '采购订单明细'
  517. # 根据采购商品的主单位数量,计算该商品的辅助单位数量
  518. @api.depends('quantity', 'goods_id')
  519. def _get_goods_uos_qty(self):
  520. for line in self:
  521. if line.goods_id and line.quantity:
  522. line.goods_uos_qty = line.quantity / line.goods_id.conversion
  523. else:
  524. line.goods_uos_qty = 0
  525. # 根据商品的辅助单位数量,反算出商品的主单位数量
  526. @api.onchange('goods_uos_qty', 'goods_id')
  527. def _inverse_quantity(self):
  528. for line in self:
  529. line.quantity = line.goods_uos_qty * line.goods_id.conversion
  530. @api.depends('goods_id')
  531. def _compute_using_attribute(selfs):
  532. '''返回订单行中商品是否使用属性'''
  533. for self in selfs:
  534. self.using_attribute = self.goods_id.attribute_ids and True or False
  535. @api.depends('quantity', 'price_taxed', 'discount_amount', 'tax_rate')
  536. def _compute_all_amount(selfs):
  537. for self in selfs:
  538. '''当订单行的数量、含税单价、折扣额、税率改变时,改变采购金额、税额、价税合计'''
  539. self.subtotal = self.price_taxed * self.quantity - self.discount_amount # 价税合计
  540. self.tax_amount = self.subtotal / (100 + self.tax_rate) * self.tax_rate # 税额
  541. self.amount = self.subtotal - self.tax_amount # 金额
  542. @api.onchange('price', 'tax_rate')
  543. def onchange_price(self):
  544. '''当订单行的不含税单价改变时,改变含税单价'''
  545. price = self.price_taxed / (1 + self.tax_rate * 0.01) # 不含税单价
  546. decimal = self.env.ref('core.decimal_price')
  547. if float_compare(price, self.price, precision_digits=decimal.digits) != 0:
  548. self.price_taxed = self.price * (1 + self.tax_rate * 0.01)
  549. order_id = fields.Many2one('buy.order',
  550. '订单编号',
  551. index=True,
  552. required=True,
  553. ondelete='cascade',
  554. help='关联订单的编号')
  555. partner_id = fields.Many2one(
  556. 'partner',
  557. string="供应商",
  558. related='order_id.partner_id',
  559. store=True)
  560. goods_id = fields.Many2one('goods',
  561. '商品',
  562. ondelete='restrict',
  563. help='商品')
  564. using_attribute = fields.Boolean('使用属性',
  565. compute=_compute_using_attribute,
  566. help='商品是否使用属性')
  567. attribute_id = fields.Many2one('attribute',
  568. '属性',
  569. ondelete='restrict',
  570. domain="[('goods_id', '=', goods_id)]",
  571. help='商品的属性,当商品有属性时,该字段必输')
  572. goods_uos_qty = fields.Float('辅助数量', digits='Quantity', compute='_get_goods_uos_qty',
  573. inverse='_inverse_quantity', store=True,
  574. help='商品的辅助数量')
  575. uos_id = fields.Many2one('uom', string='辅助单位', ondelete='restrict', readonly=True, help='商品的辅助单位')
  576. uom_id = fields.Many2one('uom',
  577. '单位',
  578. ondelete='restrict',
  579. help='商品计量单位')
  580. quantity = fields.Float('数量',
  581. default=1,
  582. required=True,
  583. digits='Quantity',
  584. help='下单数量')
  585. quantity_in = fields.Float('已执行数量',
  586. copy=False,
  587. digits='Quantity',
  588. help='采购订单产生的入库单/退货单已执行数量')
  589. price = fields.Float('采购单价',
  590. store=True,
  591. digits='Price',
  592. help='不含税单价,由含税单价计算得出')
  593. price_taxed = fields.Float('含税单价',
  594. digits='Price',
  595. help='含税单价,取自商品成本或对应供应商的采购价')
  596. discount_rate = fields.Float('折扣率%',
  597. help='折扣率')
  598. discount_amount = fields.Float('折扣额',
  599. digits='Amount',
  600. help='输入折扣率后自动计算得出,也可手动输入折扣额')
  601. amount = fields.Float('金额',
  602. compute=_compute_all_amount,
  603. store=True,
  604. digits='Amount',
  605. help='金额 = 价税合计 - 税额')
  606. tax_rate = fields.Float('税率(%)',
  607. default=lambda self: self.env.user.company_id.import_tax_rate,
  608. help='默认值取公司进项税率')
  609. tax_amount = fields.Float('税额',
  610. compute=_compute_all_amount,
  611. store=True,
  612. digits='Amount',
  613. help='由税率计算得出')
  614. subtotal = fields.Float('价税合计',
  615. compute=_compute_all_amount,
  616. store=True,
  617. digits='Amount',
  618. help='含税单价 乘以 数量')
  619. procure_date = fields.Date('计划交期', help='供应商计划交货日期。采购订单(要求交货日期)+ 料品(供应商备货周期)。')
  620. note = fields.Char('备注',
  621. help='本行备注')
  622. company_id = fields.Many2one(
  623. 'res.company',
  624. string='公司',
  625. change_default=True,
  626. default=lambda self: self.env.company)
  627. quantity_todo = fields.Float(
  628. '未执行数量', compute="_compute_quantity_todo",
  629. store=True, digits='Quantity')
  630. @api.depends('quantity', 'quantity_in')
  631. def _compute_quantity_todo(self):
  632. for s in self:
  633. s.quantity_todo = s.quantity - s.quantity_in
  634. @api.onchange('goods_id', 'quantity','order_id')
  635. def onchange_goods_id(self):
  636. '''当订单行的商品变化时,带出商品上的单位、成本价。
  637. 在采购订单上选择供应商,自动带出供货价格,没有设置供货价的取成本价格。'''
  638. if not self.order_id.partner_id:
  639. raise UserError('请先选择一个供应商!')
  640. if self.goods_id:
  641. self.uom_id = self.goods_id.uom_id
  642. self.uos_id = self.goods_id.uos_id
  643. if self.price == 0:
  644. self.price = self.goods_id.cost
  645. # 使用搜索使模型排序生效
  646. vendor_ids = self.env['vendor.goods'].search([
  647. ('goods_id', '=', self.goods_id.id )])
  648. for line in vendor_ids:
  649. if line.date and line.date > self.order_id.date:
  650. continue
  651. if line.vendor_id == self.order_id.partner_id \
  652. and self.quantity >= line.min_qty:
  653. if self.env.company.vendor_price_taxed:
  654. self.price_taxed = line.price
  655. else:
  656. self.price = line.price
  657. break
  658. self.tax_rate = self.goods_id.get_tax_rate(self.goods_id, self.order_id.partner_id, 'buy')
  659. @api.onchange('quantity', 'price_taxed', 'discount_rate')
  660. def onchange_discount_rate(self):
  661. '''当数量、单价或优惠率发生变化时,优惠金额发生变化'''
  662. price = self.price_taxed / (1 + self.tax_rate * 0.01)
  663. decimal = self.env.ref('core.decimal_price')
  664. if float_compare(price, self.price, precision_digits=decimal.digits) != 0:
  665. self.price = price
  666. self.discount_amount = (self.quantity * price *
  667. self.discount_rate * 0.01)
  668. @api.constrains('tax_rate')
  669. def _check_tax_rate(self):
  670. for record in self:
  671. if record.tax_rate > 100:
  672. raise UserError('税率不能输入超过100的数')
  673. if record.tax_rate < 0:
  674. raise UserError('税率不能输入负数')
  675. class Payment(models.Model):
  676. _name = "payment.plan"
  677. _description = '付款计划'
  678. name = fields.Char(string="付款阶段名称", required=True,
  679. help='付款计划名称')
  680. amount_money = fields.Float(string="金额", required=True,
  681. help='付款金额')
  682. date_application = fields.Date(string="申请日期", readonly=True,
  683. help='付款申请日期')
  684. buy_id = fields.Many2one("buy.order",
  685. help='关联的采购订单',
  686. ondelete='cascade'
  687. )
  688. money_invoice_id = fields.Many2one('money.invoice', string='结算单', ondelete='restrict',)
  689. @api.constrains('amount_money', 'buy_id')
  690. def _check_payment_amount(self):
  691. for plan in self:
  692. if not plan.buy_id:
  693. continue
  694. # buy.order 模型中有一个名为 'amount' 的字段表示订单总金额。
  695. order_amount = plan.buy_id.amount
  696. # 计算同一个采购订单下,除了当前记录之外的其他付款计划总和
  697. domain = [('buy_id', '=', plan.buy_id.id)]
  698. # 如果当前记录已存在(是更新操作),需要排除它,以免把旧金额重复计算
  699. if plan.id:
  700. domain.append(('id', '!=', plan.id))
  701. other_plans = self.search(domain)
  702. other_amount_sum = sum(other_plans.mapped('amount_money'))
  703. # 当前总金额 = 其他计划金额 + 当前计划正在保存的金额
  704. current_total = other_amount_sum + plan.amount_money
  705. if current_total > order_amount:
  706. raise ValidationError(
  707. _(
  708. "付款计划金额总计 (%.2f) 超过了关联采购订单 '%s' 的总金额 (%.2f)。\n"
  709. "无法保存。"
  710. ) % (current_total, plan.buy_id.name, order_amount)
  711. )
  712. def unlink(self):
  713. # 1. 获取所有需要删除的记录所关联的结算单
  714. invoices = self.mapped('money_invoice_id')
  715. # 2. 解除关联
  716. # 因为设置了 ondelete='restrict',如果不先解除关系,直接删除 invoices 会报错。
  717. # write 操作可能会触发其他逻辑,但这是清除关联的标准方法。
  718. self.write({'money_invoice_id': False})
  719. # 3. 删除关联的结算单
  720. if invoices:
  721. invoices.unlink()
  722. # 4. 执行父类的删除方法,删除当前的付款计划记录
  723. return super().unlink()
  724. def request_payment(self):
  725. self.ensure_one()
  726. if not self.buy_id.company_id.bank_account_id.id:
  727. raise UserError('%s未设置开户行,不能申请付款,\n请联系系统管理员进行设置。' % self.buy_id.company_id.name)
  728. categ = self.env.ref('money.core_category_purchase')
  729. tax_rate = self.buy_id.line_ids[0].tax_rate
  730. tax_amount = self.amount_money * tax_rate / (100 + tax_rate)
  731. if not float_is_zero(self.amount_money, 2):
  732. source_id = self.env['money.invoice'].create({
  733. 'name': self.buy_id.name,
  734. 'partner_id': self.buy_id.partner_id.id,
  735. 'category_id': categ.id,
  736. 'date': fields.Date.context_today(self),
  737. 'amount': self.amount_money,
  738. 'tax_amount': tax_amount,
  739. 'reconciled': 0,
  740. 'to_reconcile': self.amount_money,
  741. 'date_due': fields.Date.context_today(self),
  742. 'state': 'draft',
  743. })
  744. # 避免付款单去核销一张未确认的结算单(公司按发票确认应收应付的场景下出现)
  745. if source_id.state == 'draft':
  746. source_id.money_invoice_done()
  747. self.with_context(type='pay').env["money.order"].create({
  748. 'partner_id': self.buy_id.partner_id.id,
  749. 'bank_name': self.buy_id.partner_id.bank_name,
  750. 'bank_num': self.buy_id.partner_id.bank_num,
  751. 'date': fields.Date.context_today(self),
  752. 'source_ids':
  753. [(0, 0, {'name': source_id.id,
  754. 'category_id': categ.id,
  755. 'date': source_id.date,
  756. 'amount': self.amount_money,
  757. 'reconciled': 0.0,
  758. 'to_reconcile': self.amount_money,
  759. 'this_reconcile': self.amount_money})],
  760. 'line_ids':
  761. [(0, 0, {'bank_id': self.buy_id.company_id.bank_account_id.id,
  762. 'amount': self.amount_money})],
  763. 'type': 'pay',
  764. 'amount': self.amount_money,
  765. 'reconciled': 0,
  766. 'to_reconcile': self.amount_money,
  767. 'state': 'draft',
  768. 'buy_id': self.buy_id.id,
  769. })
  770. self.money_invoice_id = source_id.id
  771. self.date_application = datetime.now()
上海开阖软件有限公司 沪ICP备12045867号-1