GoodERP
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

801 lines
35KB

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