GoodERP
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

799 Zeilen
35KB

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