GoodERP
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

817 lignes
36KB

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