GoodERP
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

816 行
36KB

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