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.

875 line
38KB

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