GoodERP
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

804 líneas
34KB

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