GoodERP
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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