GoodERP
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

856 lignes
38KB

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