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

805 行
34KB

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