GoodERP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

807 line
34KB

  1. # -*- coding: utf-8 -*-
  2. from odoo import fields, models, api
  3. from odoo import _
  4. from odoo.exceptions import UserError
  5. from odoo.tools import float_compare
  6. import logging
  7. _logger = logging.getLogger(__name__)
  8. # 销售订单确认状态可选值
  9. SELL_ORDER_STATES = [
  10. ('draft', '草稿'),
  11. ('done', '已确认'),
  12. ('cancel', '已作废')]
  13. class SellOrder(models.Model):
  14. _name = 'sell.order'
  15. _description = '销售订单'
  16. _inherit = ['mail.thread']
  17. _order = 'date desc, id desc'
  18. @api.depends('line_ids.subtotal', 'discount_amount')
  19. def _compute_amount(self):
  20. '''当订单行和优惠金额改变时,改变成交金额'''
  21. for o in self:
  22. total = sum(line.subtotal for line in o.line_ids)
  23. o.amount = total - o.discount_amount
  24. o.untax_amount = sum(line.amount for line in o.line_ids)
  25. o.tax_amount = sum(line.tax_amount for line in o.line_ids)
  26. @api.depends('line_ids.quantity')
  27. def _compute_qty(self):
  28. '''当订单行数量改变时,更新总数量'''
  29. for o in self:
  30. o.total_qty = sum(line.quantity for line in o.line_ids)
  31. @api.depends('delivery_ids.state')
  32. def _get_sell_goods_state(selfs):
  33. '''返回发货状态'''
  34. for self in selfs:
  35. if all(line.quantity_out == 0 for line in self.line_ids):
  36. if any(r.state == 'draft' for r in self.delivery_ids) or self.state=='draft':
  37. self.goods_state = '未出库'
  38. else:
  39. self.goods_state = '全部作废'
  40. elif any(line.quantity > line.quantity_out for line in self.line_ids):
  41. if any(r.state == 'draft' for r in self.delivery_ids):
  42. self.goods_state = '部分出库'
  43. else:
  44. self.goods_state = '部分出库剩余作废'
  45. else:
  46. self.goods_state = '全部出库'
  47. @api.depends('partner_id')
  48. def _compute_currency_id(self):
  49. for o in self:
  50. self.currency_id = \
  51. self.partner_id.c_category_id.account_id.currency_id.id \
  52. or self.partner_id.s_category_id.account_id.currency_id.id
  53. @api.model
  54. def _default_warehouse(self):
  55. return self._default_warehouse_impl()
  56. @api.model
  57. def _default_warehouse_impl(self):
  58. if self.env.context.get('warehouse_type'):
  59. return self.env['warehouse'].get_warehouse_by_type(
  60. self.env.context.get('warehouse_type'), False)
  61. def _get_received_amount(selfs):
  62. '''计算销售订单收款/退款状态'''
  63. for self in selfs:
  64. deliverys = self.env['sell.delivery'].search(
  65. [('order_id', '=', self.id)])
  66. money_order_rows = self.env['money.order'].search([('sell_id', '=', self.id),
  67. ('reconciled', '=', 0),
  68. ('state', '=', 'done')])
  69. self.received_amount = sum([delivery.invoice_id.reconciled for delivery in deliverys]) +\
  70. sum([order_row.amount for order_row in money_order_rows])
  71. @api.depends('delivery_ids')
  72. def _compute_delivery(self):
  73. for order in self:
  74. order.delivery_count = len([deli for deli in order.delivery_ids if not deli.is_return])
  75. order.return_count = len([deli for deli in order.delivery_ids if deli.is_return])
  76. @api.depends('partner_id')
  77. def _get_sell_user(selfs):
  78. '''计算销售单据的业务员,不允许修改'''
  79. for self in selfs:
  80. if self.partner_id:
  81. if self.partner_id.responsible_id:
  82. self.user_id = self.partner_id.responsible_id
  83. else:
  84. self.user_id = self._uid
  85. @api.depends('line_ids.goods_id', 'line_ids.quantity')
  86. def _compute_net_weight(self):
  87. '''计算净重合计'''
  88. for o in self:
  89. o.net_weight = sum(
  90. line.goods_id.net_weight * line.quantity
  91. for line in o.line_ids
  92. )
  93. partner_id = fields.Many2one('partner', '客户',
  94. ondelete='restrict',
  95. help='签约合同的客户')
  96. contact = fields.Char('联系人',
  97. help='客户方的联系人')
  98. address_id = fields.Many2one('partner.address', '地址',
  99. domain="[('partner_id', '=', partner_id)]",
  100. help='联系地址')
  101. mobile = fields.Char('手机',
  102. help='联系手机')
  103. user_id = fields.Many2one(
  104. 'res.users',
  105. '销售员',
  106. ondelete='restrict',store=True,
  107. compute='_get_sell_user',
  108. help='单据经办人',
  109. )
  110. date = fields.Date('单据日期',
  111. required=True,
  112. default=lambda self: fields.Date.context_today(self),
  113. index=True,
  114. copy=False,
  115. help="默认是订单创建日期")
  116. delivery_date = fields.Date(
  117. '要求交货日期',
  118. required=True,
  119. default=lambda self: fields.Date.context_today(self),
  120. index=True,
  121. copy=False,
  122. help="订单的要求交货日期")
  123. type = fields.Selection([('sell', '销售'), ('return', '退货')], '类型',
  124. default='sell',
  125. help='销售订单的类型,分为销售或退货')
  126. ref = fields.Char('客户订单号')
  127. warehouse_id = fields.Many2one('warehouse',
  128. '调出仓库',
  129. required=True,
  130. ondelete='restrict',
  131. default=_default_warehouse,
  132. help='商品将从该仓库调出')
  133. name = fields.Char('单据编号', index=True, copy=False,
  134. default='/', help="创建时它会自动生成下一个编号")
  135. line_ids = fields.One2many('sell.order.line', 'order_id', '销售订单行',
  136. copy=True,
  137. help='销售订单的明细行,不能为空')
  138. note = fields.Text('备注', help='单据备注')
  139. discount_rate = fields.Float('优惠率(%)',
  140. help='整单优惠率')
  141. discount_amount = fields.Float('抹零',
  142. digits='Amount',
  143. help='整单优惠金额,可由优惠率自动计算出来,也可手动输入')
  144. amount = fields.Float(string='成交金额', store=True, readonly=True,
  145. compute='_compute_amount',
  146. digits='Amount',
  147. help='总金额减去优惠金额')
  148. tax_amount = fields.Float(string='税额', store=True, readonly=True,
  149. compute='_compute_amount',
  150. digits='Amount',
  151. help='税额')
  152. untax_amount = fields.Float(string='不含税金额', store=True, readonly=True,
  153. compute='_compute_amount',
  154. digits='Amount',
  155. help='不含税金额')
  156. total_qty = fields.Float(string='数量合计', store=True, readonly=True, copy=False,
  157. compute='_compute_qty',
  158. digits='Quantity',
  159. help='数量总计')
  160. pre_receipt = fields.Float('预收款',
  161. digits='Amount',
  162. help='输入预收款确认销售订单,会产生一张收款单')
  163. bank_account_id = fields.Many2one('bank.account', '结算账户',
  164. ondelete='restrict',
  165. help='用来核算和监督企业与其他单位或个人之间的债权债务的结算情况')
  166. approve_uid = fields.Many2one('res.users', '确认人', copy=False,
  167. ondelete='restrict',
  168. help='确认单据的人')
  169. state = fields.Selection(SELL_ORDER_STATES, '确认状态', readonly=True,
  170. help="销售订单的确认状态", index=True,
  171. tracking=True,
  172. copy=False, default='draft')
  173. goods_state = fields.Char('发货状态', compute=_get_sell_goods_state,
  174. default='未出库',
  175. store=True,
  176. help="销售订单的发货状态", index=True, copy=False)
  177. cancelled = fields.Boolean('已终止',
  178. help='该单据是否已终止')
  179. currency_id = fields.Many2one('res.currency',
  180. '外币币别',
  181. compute='_compute_currency_id',
  182. store=True,
  183. readonly=True,
  184. help='外币币别')
  185. pay_base_currency = fields.Boolean('以本币结算', help='客户以本币付款到我公司基本账户内')
  186. company_id = fields.Many2one(
  187. 'res.company',
  188. string='公司',
  189. change_default=True,
  190. default=lambda self: self.env.company)
  191. received_amount = fields.Float(
  192. '已收金额', compute=_get_received_amount, readonly=True)
  193. delivery_ids = fields.One2many(
  194. 'sell.delivery', 'order_id', string='发货单', copy=False)
  195. delivery_count = fields.Integer(
  196. compute='_compute_delivery', string='发货单数量', default=0)
  197. return_count = fields.Integer(
  198. compute='_compute_delivery', string='退货单数量', default=0)
  199. pay_method = fields.Many2one('pay.method',
  200. string='付款方式',
  201. ondelete='restrict')
  202. term_id = fields.Many2one('core.value', "贸易条款",
  203. domain=[('type', '=', 'price_term')],
  204. context={'type': 'price_term'}
  205. )
  206. pol = fields.Char('起运港')
  207. pod = fields.Char('目的港')
  208. express_type = fields.Char('承运商')
  209. money_order_id = fields.Many2one(
  210. 'money.order',
  211. '预收款单',
  212. readonly=True,
  213. copy=False,
  214. help='输入预收款确认时产生的预收款单')
  215. net_weight = fields.Float(
  216. string='净重合计', compute='_compute_net_weight', store=True)
  217. invoice_ids = fields.One2many(
  218. 'money.invoice', compute='_compute_invoice', string='Invoices')
  219. invoice_count = fields.Integer(
  220. compute='_compute_invoice', string='Invoices Count', default=0)
  221. details = fields.Html('明细',compute='_compute_details')
  222. paid_no_goods = fields.Boolean('已收款未发货',compute="_compute_paid_no_goods",store=True)
  223. goods_id = fields.Many2one(
  224. 'goods', related='line_ids.goods_id', string='商品') #用于在列表上根据商品搜索
  225. project_id = fields.Many2one('project', string='项目')
  226. @api.depends('money_order_id.state','goods_state')
  227. def _compute_paid_no_goods(self):
  228. for o in self:
  229. o.paid_no_goods = False
  230. if o.state == 'done' and o.goods_state == '未出库' and o.received_amount:
  231. if not all(line.goods_id.no_stock for line in self.line_ids):
  232. o.paid_no_goods = True
  233. @api.depends('line_ids')
  234. def _compute_details(self):
  235. for v in self:
  236. vl = {'col':[],'val':[]}
  237. vl['col'] = [_('商品'),_('数量'),_('单价'),_('已发')]
  238. for l in v.line_ids:
  239. vl['val'].append([l.goods_id.name,l.quantity,l.price,l.quantity_out])
  240. v.details = v.company_id._get_html_table(vl)
  241. @api.onchange('address_id')
  242. def onchange_partner_address(self):
  243. ''' 选择地址填充 联系人、电话 '''
  244. if self.address_id:
  245. self.contact = self.address_id.contact
  246. self.mobile = self.address_id.mobile
  247. @api.onchange('partner_id')
  248. def onchange_partner_id(self):
  249. ''' 选择客户带出其默认地址信息 '''
  250. if self.partner_id:
  251. self.contact = self.partner_id.contact
  252. self.mobile = self.partner_id.mobile
  253. self.pay_method = self.partner_id.pay_method
  254. for child in self.partner_id.child_ids:
  255. if child.is_default_add:
  256. self.address_id = child.id
  257. if self.partner_id.child_ids and not any([child.is_default_add for child in self.partner_id.child_ids]):
  258. partners_add = self.env['partner.address'].search(
  259. [('partner_id', '=', self.partner_id.id)], order='id')
  260. self.address_id = partners_add[0].id
  261. for line in self.line_ids:
  262. line.tax_rate = line.goods_id.get_tax_rate(line.goods_id, self.partner_id, 'sell')
  263. address_list = [
  264. child_list.id for child_list in self.partner_id.child_ids]
  265. if address_list:
  266. return {'domain': {'address_id': [('id', 'in', address_list)]}}
  267. else:
  268. self.address_id = False
  269. @api.onchange('discount_rate', 'line_ids')
  270. def onchange_discount_rate(self):
  271. '''当优惠率或销售订单行发生变化时,单据优惠金额发生变化'''
  272. total = sum(line.subtotal for line in self.line_ids)
  273. self.discount_amount = total * self.discount_rate * 0.01
  274. def _get_vals(self):
  275. '''返回创建 money_order 时所需数据'''
  276. flag = (self.type == 'sell' and 1 or -1) # 用来标志发库或退货
  277. amount = flag * self.amount
  278. this_reconcile = flag * self.pre_receipt
  279. money_lines = [{
  280. 'bank_id': self.bank_account_id.id,
  281. 'amount': this_reconcile,
  282. }]
  283. return {
  284. 'partner_id': self.partner_id.id,
  285. 'date': fields.Date.context_today(self),
  286. 'line_ids':
  287. [(0, 0, line) for line in money_lines],
  288. 'amount': amount,
  289. 'reconciled': this_reconcile,
  290. 'to_reconcile': amount,
  291. 'state': 'draft',
  292. 'origin_name': self.name,
  293. 'sell_id': self.id,
  294. }
  295. def generate_receipt_order(self):
  296. '''由销售订单生成收款单'''
  297. # 发库单/退货单
  298. if self.pre_receipt:
  299. money_order = self.with_context(type='get').env['money.order'].create(
  300. self._get_vals()
  301. )
  302. return money_order
  303. def _check_sell_order_manage_access(self):
  304. if self.env.context.get('skip_sell_order_manage_access'):
  305. return
  306. if not self.env.user.has_group('sell.group_sell'):
  307. raise UserError(_('只有销售组可以确认、撤销或作废销售订单'))
  308. def _check_sell_order_done(self):
  309. '''检查销售订单是否可以确认'''
  310. self.ensure_one()
  311. self._check_sell_order_manage_access()
  312. # 检查订单状态
  313. if self.state == 'done':
  314. raise UserError(_('请不要重复确认!'))
  315. # 检查是否有明细行
  316. if not self.line_ids:
  317. raise UserError(_('请输入商品明细行!'))
  318. # 检查明细行
  319. for line in self.line_ids:
  320. # 检查属性是否填充,防止无权限人员不填就可以保存
  321. if line.using_attribute and not line.attribute_id:
  322. raise UserError(_('请输入商品:%s 的属性') % line.goods_id.name)
  323. # 检查数量和价格
  324. if line.quantity <= 0 or line.price_taxed < 0:
  325. raise UserError(_('商品 %s 的数量和含税单价不能小于0!') % line.goods_id.name)
  326. # 检查外贸免税
  327. if line.tax_amount > 0 and self.currency_id:
  328. raise UserError(_('外贸免税!'))
  329. # 检查结算账户
  330. if not self.bank_account_id and self.pre_receipt:
  331. raise UserError(_('预付款不为空时,请选择结算账户!'))
  332. return True
  333. def sell_order_done(self):
  334. '''确认销售订单'''
  335. self.ensure_one()
  336. # 执行确认前检查
  337. self._check_sell_order_done()
  338. # 销售预收款生成收款单
  339. money_order = self.generate_receipt_order()
  340. # 生成发货单
  341. self.sell_generate_delivery()
  342. # 更新订单状态
  343. self.approve_uid = self._uid
  344. self.write({
  345. 'money_order_id': money_order and money_order.id,
  346. 'state': 'done', # 为保证审批流程顺畅,否则,未审批就可审核
  347. })
  348. return True
  349. def _check_sell_order_draft(self):
  350. '''检查销售订单是否可以撤销确认'''
  351. self.ensure_one()
  352. self._check_sell_order_manage_access()
  353. # 检查订单状态
  354. if self.state == 'draft':
  355. raise UserError(_('请不要重复撤销 %s') % self._description)
  356. # 检查是否已发货
  357. if any(r.state == 'done' for r in self.delivery_ids):
  358. raise UserError(_('该销售订单已经发货,不能撤销确认!'))
  359. return True
  360. def sell_order_draft(self):
  361. '''撤销确认销售订单'''
  362. self.ensure_one()
  363. # 执行撤销前检查
  364. self._check_sell_order_draft()
  365. # 删除产生的发货单
  366. self.delivery_ids.unlink()
  367. # 删除产生的收款单
  368. if self.money_order_id:
  369. self.money_order_id.unlink()
  370. # 重置订单状态
  371. self.approve_uid = False
  372. self.state = 'draft'
  373. return True
  374. def action_cancel(self):
  375. self.ensure_one()
  376. self._check_sell_order_manage_access()
  377. if self.state == 'cancel':
  378. raise UserError(_('请不要重复作废 %s') % self._description)
  379. return super().action_cancel()
  380. def get_delivery_line(self, line, single=False):
  381. '''返回销售发货/退货单行'''
  382. self.ensure_one()
  383. qty = 0
  384. discount_amount = 0
  385. if single:
  386. qty = 1
  387. discount_amount = line.discount_amount \
  388. / (line.quantity or 1)
  389. else:
  390. qty = line.quantity - line.quantity_out
  391. discount_amount = line.discount_amount / (line.quantity or 1) * qty
  392. return {
  393. 'type': self.type == 'sell' and 'out' or 'in',
  394. 'sell_line_id': line.id,
  395. 'goods_id': line.goods_id.id,
  396. 'attribute_id': line.attribute_id.id,
  397. 'uos_id': line.goods_id.uos_id.id,
  398. 'goods_qty': qty,
  399. 'uom_id': line.uom_id.id,
  400. 'cost_unit': line.goods_id.cost,
  401. 'price': line.price,
  402. 'price_taxed': line.price_taxed,
  403. 'discount_rate': line.discount_rate,
  404. 'discount_amount': discount_amount,
  405. 'tax_rate': line.tax_rate,
  406. 'plan_date':self.delivery_date,
  407. }
  408. def _generate_delivery(self, delivery_line):
  409. '''根据明细行生成发货单或退货单'''
  410. # 如果退货,warehouse_dest_id,warehouse_id要调换
  411. warehouse = (self.type == 'sell'
  412. and self.warehouse_id
  413. or self.env.ref("warehouse.warehouse_customer"))
  414. warehouse_dest = (self.type == 'sell'
  415. and self.env.ref("warehouse.warehouse_customer")
  416. or self.warehouse_id)
  417. rec = (self.type == 'sell' and self.with_context(is_return=False)
  418. or self.with_context(is_return=True))
  419. delivery_id = rec.env['sell.delivery'].create({
  420. 'partner_id': self.partner_id.id,
  421. 'warehouse_id': warehouse.id,
  422. 'warehouse_dest_id': warehouse_dest.id,
  423. 'user_id': self.user_id.id,
  424. 'date': self.delivery_date,
  425. 'order_id': self.id,
  426. 'ref':self.ref,
  427. 'origin': 'sell.delivery',
  428. 'discount_rate': self.discount_rate,
  429. 'discount_amount': self.discount_amount,
  430. 'currency_id': self.currency_id.id,
  431. 'contact': self.contact,
  432. 'address_id': self.address_id.id,
  433. 'mobile': self.mobile,
  434. 'express_type': self.express_type,
  435. 'project_id': self.project_id.id,
  436. })
  437. if self.type == 'sell':
  438. delivery_id.write({'line_out_ids': [
  439. (0, 0, line) for line in delivery_line]})
  440. else:
  441. delivery_id.write({'line_in_ids': [
  442. (0, 0, line) for line in delivery_line]})
  443. return delivery_id
  444. def sell_generate_delivery(self):
  445. '''由销售订单生成销售发货单'''
  446. self.ensure_one()
  447. delivery_line = [] # 销售发货单行
  448. for line in self.line_ids:
  449. # 如果订单部分出库,则点击此按钮时生成剩余数量的出库单
  450. to_out = line.quantity - line.quantity_out
  451. if to_out <= 0:
  452. continue
  453. if line.goods_id.force_batch_one:
  454. i = 0
  455. while i < to_out:
  456. i += 1
  457. delivery_line.append(
  458. self.get_delivery_line(line, single=True))
  459. else:
  460. delivery_line.append(
  461. self.get_delivery_line(line, single=False))
  462. if not delivery_line:
  463. return {}
  464. self._generate_delivery(delivery_line)
  465. return {}
  466. @api.depends('delivery_ids')
  467. def _compute_invoice(self):
  468. for order in self:
  469. money_invoices = self.env['money.invoice'].search([
  470. ('name', '=', order.name)])
  471. order.invoice_ids = not money_invoices and order.delivery_ids.mapped('invoice_id') or money_invoices + order.delivery_ids.mapped('invoice_id')
  472. order.invoice_count = len(order.invoice_ids.ids)
  473. def action_view_invoice(self):
  474. self.ensure_one()
  475. if self.invoice_count == 0:
  476. return False
  477. action = {
  478. 'name': _('结算单(客户发票)'),
  479. 'type': 'ir.actions.act_window',
  480. 'view_mode': 'form',
  481. 'res_model': 'money.invoice',
  482. 'view_id': False,
  483. 'target': 'current',
  484. }
  485. invoice_ids = self.invoice_ids.ids
  486. # choose the view_mode accordingly
  487. action['domain'] = "[('id','in',[" + \
  488. ','.join(map(str, invoice_ids)) + "])]"
  489. action['view_mode'] = 'list'
  490. return action
  491. def action_view_delivery(self):
  492. '''
  493. This function returns an action that display existing deliverys of given sells order ids.
  494. When only one found, show the delivery immediately.
  495. '''
  496. self.ensure_one()
  497. if not self.delivery_count:
  498. return False
  499. action = {
  500. 'name': _('销售发货单'),
  501. 'type': 'ir.actions.act_window',
  502. 'view_mode': 'form',
  503. 'res_model': 'sell.delivery',
  504. 'view_id': False,
  505. 'target': 'current',
  506. }
  507. delivery_ids = [delivery.id for delivery in self.delivery_ids if not delivery.is_return]
  508. if len(delivery_ids) > 1:
  509. action['domain'] = "[('id','in',[" + \
  510. ','.join(map(str, delivery_ids)) + "])]"
  511. action['view_mode'] = 'list,form'
  512. elif len(delivery_ids) == 1:
  513. view_id = self.env.ref('sell.sell_delivery_form').id
  514. action['views'] = [(view_id, 'form')]
  515. action['res_id'] = delivery_ids and delivery_ids[0] or False
  516. return action
  517. def action_view_return(self):
  518. '''
  519. 该销售订单对应的退货单
  520. '''
  521. self.ensure_one()
  522. if not self.return_count:
  523. return False
  524. action = {
  525. 'name': _('销售退货单'),
  526. 'type': 'ir.actions.act_window',
  527. 'view_type': 'form',
  528. 'view_mode': 'form',
  529. 'res_model': 'sell.delivery',
  530. 'view_id': False,
  531. 'target': 'current',
  532. }
  533. list_view_id = self.env.ref('sell.sell_return_list').id
  534. form_view_id = self.env.ref('sell.sell_return_form').id
  535. delivery_ids = [delivery.id for delivery in self.delivery_ids if delivery.is_return]
  536. if len(delivery_ids) > 1:
  537. action['domain'] = "[('id','in',[" + \
  538. ','.join(map(str, delivery_ids)) + "])]"
  539. action['view_mode'] = 'list,form'
  540. action['views'] = [(list_view_id, 'list'), (form_view_id, 'form')]
  541. elif len(delivery_ids) == 1:
  542. action['views'] = [(form_view_id, 'form')]
  543. action['res_id'] = delivery_ids and delivery_ids[0] or False
  544. return action
  545. class SellOrderLine(models.Model):
  546. _name = 'sell.order.line'
  547. _description = '销售订单明细'
  548. @api.depends('goods_id')
  549. def _compute_using_attribute(self):
  550. '''返回订单行中商品是否使用属性'''
  551. for l in self:
  552. l.using_attribute = l.goods_id.attribute_ids and True or False
  553. @api.depends('quantity', 'price_taxed', 'discount_amount', 'tax_rate')
  554. def _compute_all_amount(selfs):
  555. '''当订单行的数量、含税单价、折扣额、税率改变时,改变销售金额、税额、价税合计'''
  556. for self in selfs:
  557. if self.order_id.currency_id.id == self.env.user.company_id.currency_id.id:
  558. self.subtotal = self.price_taxed * self.quantity - self.discount_amount # 价税合计
  559. self.tax_amount = self.subtotal / \
  560. (100 + self.tax_rate) * self.tax_rate # 税额
  561. self.amount = self.subtotal - self.tax_amount # 金额
  562. else:
  563. rate_silent = self.env['res.currency'].get_rate_silent(
  564. self.order_id.date, self.order_id.currency_id.id) or 1
  565. if not self.order_id.pay_base_currency:
  566. rate_silent = 1
  567. self.subtotal = (self.price_taxed * self.quantity -
  568. self.discount_amount) * rate_silent # 价税合计
  569. self.tax_amount = self.subtotal / \
  570. (100 + self.tax_rate) * self.tax_rate # 税额
  571. self.amount = self.subtotal - self.tax_amount # 本位币金额
  572. @api.onchange('price', 'tax_rate')
  573. def onchange_price(self):
  574. '''当订单行的不含税单价改变时,改变含税单价。
  575. 如果将含税价改为99,则self.price计算出来为84.62,price=99/1.17,
  576. 跟84.62保留相同位数比较时是相等的,这种情况则保留含税价不变,
  577. 这样处理是为了使得修改含税价时不再重新计算含税价。
  578. '''
  579. _logger.info('单价或税率发生变化')
  580. price = self.price_taxed / (1 + self.tax_rate * 0.01) # 不含税单价
  581. decimal = self.env.ref('core.decimal_price')
  582. if float_compare(price, self.price, precision_digits=decimal.digits) != 0:
  583. self.price_taxed = self.price * (1 + self.tax_rate * 0.01)
  584. order_id = fields.Many2one('sell.order', '订单编号', index=True,
  585. required=True, ondelete='cascade',
  586. help='关联订单的编号')
  587. partner_id = fields.Many2one(
  588. 'partner',
  589. string="客户",
  590. related='order_id.partner_id',
  591. store=True)
  592. goods_id = fields.Many2one('goods',
  593. '商品',
  594. required=True,
  595. ondelete='restrict',
  596. help='商品')
  597. using_attribute = fields.Boolean('使用属性', compute=_compute_using_attribute,
  598. help='商品是否使用属性')
  599. attribute_id = fields.Many2one('attribute', '属性',
  600. ondelete='restrict',
  601. domain="[('goods_id', '=', goods_id)]",
  602. help='商品的属性,当商品有属性时,该字段必输')
  603. uom_id = fields.Many2one('uom', '单位', ondelete='restrict',
  604. help='商品计量单位')
  605. quantity = fields.Float('数量',
  606. default=1,
  607. required=True,
  608. digits='Quantity',
  609. help='下单数量')
  610. quantity_out = fields.Float('已执行数量', copy=False,
  611. digits='Quantity',
  612. help='销售订单产生的发货单/退货单已执行数量')
  613. price = fields.Float('销售单价',
  614. store=True,
  615. digits='Price',
  616. help='不含税单价,由含税单价计算得出')
  617. price_taxed = fields.Float('含税单价',
  618. digits='Price',
  619. help='含税单价,取商品零售价')
  620. discount_rate = fields.Float('折扣率%',
  621. help='折扣率')
  622. discount_amount = fields.Float('折扣额',
  623. help='输入折扣率后自动计算得出,也可手动输入折扣额')
  624. amount = fields.Float('金额',
  625. compute=_compute_all_amount,
  626. store=True,
  627. digits='Amount',
  628. help='金额 = 价税合计 - 税额')
  629. tax_rate = fields.Float('税率(%)',
  630. help='税率')
  631. tax_amount = fields.Float('税额',
  632. compute=_compute_all_amount,
  633. store=True,
  634. digits='Amount',
  635. help='税额')
  636. subtotal = fields.Float('价税合计',
  637. compute=_compute_all_amount,
  638. store=True,
  639. digits='Amount',
  640. help='含税单价 乘以 数量')
  641. note = fields.Char('备注',
  642. help='本行备注')
  643. company_id = fields.Many2one(
  644. 'res.company', string='公司',
  645. change_default=True,
  646. default=lambda self: self.env.company)
  647. # 销售订单行上增加订单的重要字段以便销售订单明细表界面可针对其筛选分组
  648. order_date = fields.Date(related='order_id.date', string='订单日期', store=True)
  649. order_state = fields.Selection(related='order_id.state', string='订单状态', store=True)
  650. order_currency = fields.Many2one('res.currency', related='order_id.currency_id', string='订单币种', store=True)
  651. quantity_todo = fields.Float(
  652. '未执行数量', compute="_compute_quantity_todo",
  653. store=True, digits='Quantity')
  654. @api.depends('quantity_out')
  655. def _compute_quantity_todo(self):
  656. for s in self:
  657. s.quantity_todo = s.quantity - s.quantity_out
  658. @api.onchange('goods_id')
  659. def onchange_warehouse_id(self):
  660. '''当订单行的仓库变化时,带出定价策略中的折扣率'''
  661. if self.order_id.warehouse_id and self.goods_id:
  662. partner = self.order_id.partner_id
  663. warehouse = self.order_id.warehouse_id
  664. goods = self.goods_id
  665. date = self.order_id.date
  666. pricing = self.env['pricing'].get_pricing_id(
  667. partner, warehouse, goods, date)
  668. if pricing:
  669. self.discount_rate = pricing.discount_rate
  670. else:
  671. self.discount_rate = 0
  672. @api.onchange('goods_id')
  673. def onchange_goods_id(self):
  674. '''当订单行的商品变化时,带出商品上的单位、默认仓库、价格、税率'''
  675. if self.goods_id:
  676. self.uom_id = self.goods_id.uom_id
  677. self.price = self.goods_id.price
  678. self.tax_rate = self.goods_id.get_tax_rate(self.goods_id, self.order_id.partner_id, 'sell')
  679. @api.onchange('quantity', 'price_taxed', 'discount_rate')
  680. def onchange_discount_rate(self):
  681. '''当数量、单价或优惠率发生变化时,优惠金额发生变化'''
  682. _logger.info('数量、含税价、折扣率发生变化')
  683. self.price = self.price_taxed / (1 + self.tax_rate * 0.01)
  684. self.discount_amount = self.quantity * self.price \
  685. * self.discount_rate * 0.01
  686. @api.constrains('tax_rate')
  687. def _check_tax_rate(selfs):
  688. for self in selfs:
  689. if self.tax_rate > 100:
  690. raise UserError(_('税率不能输入超过100的数!\n输入税率:%s') % self.tax_rate)
  691. if self.tax_rate < 0:
  692. raise UserError(_('税率不能输入负数\n 输入税率:%s') % self.tax_rate)
  693. class ApproveMultiSellOrder(models.TransientModel):
  694. _name = "approve.multi.sell.order"
  695. _description = '批量确认销售订单'
  696. def set_default_note(self):
  697. """
  698. 设置默认值, 用来确认要批量确认的订单
  699. """
  700. context = self.env.context
  701. order_names = [order.name for order in self.env['sell.order'].browse(context.get('active_ids'))]
  702. return '-'.join(order_names)
  703. note = fields.Char('本次处理销售订单', default=set_default_note, readonly=True)
  704. @api.model
  705. def default_get(self, fields_list):
  706. """ 根据内容判断 报出错误 """
  707. # Validate each wizard opening through defaults, outside the cached view API.
  708. res = super().default_get(fields_list)
  709. orders = self.env['sell.order'].browse(self.env.context.get('active_ids'))
  710. done_lists = ''
  711. for order in orders:
  712. if order.state == 'done':
  713. done_lists += order.name
  714. if done_lists:
  715. raise UserError(_('销售订单 ') + done_lists + _(' 已确认!'))
  716. return res
  717. def approve_sell_order(self):
  718. """ 确认销售订单 """
  719. for order in self.env['sell.order'].search([('id', 'in', self.env.context.get('active_ids'))]):
  720. order.sell_order_done()
上海开阖软件有限公司 沪ICP备12045867号-1