GoodERP
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

713 行
33KB

  1. from odoo import fields, models, api
  2. import datetime
  3. from odoo.exceptions import UserError
  4. from odoo.tools import float_compare, float_is_zero
  5. from odoo import _
  6. ISODATEFORMAT = '%Y-%m-%d'
  7. class SellDelivery(models.Model):
  8. _name = 'sell.delivery'
  9. _inherits = {'wh.move': 'sell_move_id'}
  10. _inherit = ['mail.thread', 'barcodes.barcode_events_mixin', 'mail.activity.mixin']
  11. _description = '销售发货单'
  12. _order = 'date desc, id desc'
  13. @api.depends('delivery_ids')
  14. def _compute_delivery(self):
  15. for order in self:
  16. order.return_count = len([deli for deli in order.delivery_ids if deli.is_return])
  17. @api.depends('line_out_ids.subtotal', 'discount_amount', 'partner_cost',
  18. 'receipt', 'partner_id', 'line_in_ids.subtotal')
  19. def _compute_all_amount(selfs):
  20. '''当优惠金额改变时,改变成交金额'''
  21. for self in selfs:
  22. total = 0
  23. if self.line_out_ids:
  24. # 发货时优惠前总金
  25. total = sum(line.subtotal for line in self.line_out_ids)
  26. elif self.line_in_ids:
  27. # 退货时优惠前总金额
  28. total = sum(line.subtotal for line in self.line_in_ids)
  29. self.amount = total - self.discount_amount
  30. @api.depends('is_return', 'invoice_id.reconciled', 'invoice_id.amount')
  31. def _get_sell_money_state(selfs):
  32. '''返回收款状态'''
  33. for self in selfs:
  34. if not self.is_return:
  35. if self.invoice_id.reconciled == 0:
  36. self.money_state = '未收款'
  37. elif self.invoice_id.reconciled < self.invoice_id.amount:
  38. self.money_state = '部分收款'
  39. elif self.invoice_id.reconciled == self.invoice_id.amount:
  40. self.money_state = '全部收款'
  41. # 返回退款状态
  42. if self.is_return:
  43. if self.invoice_id.reconciled == 0:
  44. self.return_state = '未退款'
  45. elif abs(self.invoice_id.reconciled) < abs(self.invoice_id.amount):
  46. self.return_state = '部分退款'
  47. elif self.invoice_id.reconciled == self.invoice_id.amount:
  48. self.return_state = '全部退款'
  49. currency_id = fields.Many2one('res.currency', '外币币别', readonly=True,
  50. help='外币币别')
  51. is_multi_currency = fields.Boolean('多币种', related='company_id.is_multi_currency')
  52. sell_move_id = fields.Many2one('wh.move', '发货单', required=True,
  53. ondelete='cascade',
  54. help='发货单号')
  55. is_return = fields.Boolean('是否退货', default=lambda self:
  56. self.env.context.get('is_return'),
  57. help='是否为退货类型')
  58. order_id = fields.Many2one('sell.order', '订单号', copy=False,
  59. ondelete='cascade',
  60. help='产生发货单/退货单的销售订单')
  61. invoice_id = fields.Many2one('money.invoice', '发票号',
  62. copy=False, ondelete='set null',
  63. help='产生的发票号')
  64. date_due = fields.Date('到期日期', copy=False,
  65. default=lambda self: fields.Date.context_today(
  66. self),
  67. help='收款截止日期')
  68. discount_rate = fields.Float('优惠率(%)',
  69. help='整单优惠率')
  70. discount_amount = fields.Float('优惠金额',
  71. digits='Amount',
  72. help='整单优惠金额,可由优惠率自动计算得出,也可手动输入')
  73. amount = fields.Float('成交金额', compute=_compute_all_amount,
  74. store=True, readonly=True,
  75. digits='Amount',
  76. help='总金额减去优惠金额')
  77. partner_cost = fields.Float('客户承担费用',
  78. digits='Amount',
  79. help='客户承担费用')
  80. receipt = fields.Float('本次收款',
  81. digits='Amount',
  82. help='本次收款金额')
  83. bank_account_id = fields.Many2one('bank.account',
  84. '结算账户', ondelete='restrict',
  85. help='用来核算和监督企业与其他单位或个人之间的债权债务的结算情况')
  86. cost_line_ids = fields.One2many('cost.line', 'sell_id', '销售费用',
  87. copy=False,
  88. help='销售费用明细行')
  89. money_state = fields.Char('收款状态', compute=_get_sell_money_state,
  90. store=True, default='未收款',
  91. help="销售发货单的收款状态", index=True, copy=False)
  92. return_state = fields.Char('退款状态', compute=_get_sell_money_state,
  93. store=True, default='未退款',
  94. help="销售退货单的退款状态", index=True, copy=False)
  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. origin_id = fields.Many2one('sell.delivery', '来源单据', ondelete='restrict',)
  103. voucher_id = fields.Many2one('voucher', '出库凭证', readonly=True,
  104. help='发货时产生的出库凭证')
  105. money_order_id = fields.Many2one(
  106. 'money.order',
  107. '收款单',
  108. readonly=True,
  109. copy=False,
  110. help='输入本次收款确认时产生的收款单')
  111. project_id = fields.Many2one('project', string='项目')
  112. delivery_ids = fields.One2many(
  113. 'sell.delivery', 'origin_id', string='退货单', copy=False)
  114. return_count = fields.Integer(
  115. compute='_compute_delivery', string='退货单数量', default=0)
  116. def set_today(self):
  117. self.date = fields.Date.today()
  118. @api.onchange('address_id')
  119. def onchange_address_id(self):
  120. ''' 选择地址填充 联系人、电话 '''
  121. if self.address_id:
  122. self.contact = self.address_id.contact
  123. self.mobile = self.address_id.mobile
  124. @api.onchange('partner_id')
  125. def onchange_partner_id(self):
  126. '''选择客户带出其默认地址信息'''
  127. if self.partner_id:
  128. self.contact = self.partner_id.contact
  129. self.mobile = self.partner_id.mobile
  130. for child in self.partner_id.child_ids:
  131. if child.is_default_add:
  132. self.address_id = child.id
  133. if self.partner_id.child_ids and not any([child.is_default_add for child in self.partner_id.child_ids]):
  134. partners_add = self.env['partner.address'].search(
  135. [('partner_id', '=', self.partner_id.id)], order='id')
  136. self.address_id = partners_add[0].id
  137. for line in self.line_out_ids:
  138. line.tax_rate = line.goods_id.get_tax_rate(line.goods_id, self.partner_id, 'sell')
  139. address_list = [
  140. child_list.id for child_list in self.partner_id.child_ids]
  141. if address_list:
  142. return {'domain': {'address_id': [('id', 'in', address_list)]}}
  143. else:
  144. self.address_id = False
  145. @api.onchange('discount_rate', 'line_in_ids', 'line_out_ids')
  146. def onchange_discount_rate(self):
  147. '''当优惠率或订单行发生变化时,单据优惠金额发生变化'''
  148. total = 0
  149. if self.line_out_ids:
  150. # 发货时优惠前总金额
  151. total = sum(line.subtotal for line in self.line_out_ids)
  152. elif self.line_in_ids:
  153. # 退货时优惠前总金额
  154. total = sum(line.subtotal for line in self.line_in_ids)
  155. if self.discount_rate:
  156. self.discount_amount = total * self.discount_rate * 0.01
  157. def get_move_origin(self, vals):
  158. return self._name + (self.env.context.get('is_return') and '.return'
  159. or '.sell')
  160. @api.model_create_multi
  161. def create(self, vals_list):
  162. '''创建销售发货单时生成有序编号'''
  163. if not self.env.context.get('is_return'):
  164. name = self._name
  165. else:
  166. name = 'sell.return'
  167. for vals in vals_list:
  168. if vals.get('name', '/') == '/':
  169. vals['name'] = self.env['ir.sequence'].next_by_code(name) or '/'
  170. vals.update({
  171. 'origin': self.get_move_origin(vals),
  172. 'finance_category_id': self.env.ref('finance.categ_sell_goods').id,
  173. })
  174. return super(SellDelivery, self).create(vals_list)
  175. def unlink(self):
  176. for delivery in self:
  177. return delivery.sell_move_id.unlink()
  178. def goods_inventory(self, vals):
  179. """
  180. 审核时若仓库中商品不足,则产生补货向导生成其他入库单并审核。
  181. :param vals: 创建其他入库单需要的字段及取值信息构成的字典
  182. :return:
  183. """
  184. auto_in = self.env['wh.in'].create(vals)
  185. line_ids = [line.id for line in auto_in.line_in_ids]
  186. self.with_context({'wh_in_line_ids': line_ids}).sell_delivery_done()
  187. return True
  188. def _wrong_delivery_done(self):
  189. self.ensure_one()
  190. '''审核时不合法的给出报错'''
  191. if self.state == 'done':
  192. raise UserError('请不要重复发货')
  193. for line in self.line_in_ids:
  194. if line.goods_qty <= 0 or line.price_taxed < 0:
  195. raise UserError('商品 %s 的数量和商品含税单价不能小于0!' % line.goods_id.name)
  196. if not self.bank_account_id and self.receipt:
  197. raise UserError('收款额不为空时,请选择结算账户!')
  198. decimal_amount = self.env.ref('core.decimal_amount')
  199. if float_compare(self.receipt, self.amount + self.partner_cost, precision_digits=decimal_amount.digits) == 1:
  200. raise UserError('本次收款金额不能大于成交金额!\n本次收款金额:%s 成交金额:%s' %
  201. (self.receipt, self.amount + self.partner_cost))
  202. # TODO:客户有自己的发货时检查信用额度的逻辑,这里暂时去掉gooderp原生的检查
  203. return
  204. # 发库单/退货单 计算客户的 本次发货金额+客户应收余额 是否小于客户信用额度, 否则报错
  205. if not self.is_return:
  206. amount = self.amount + self.partner_cost
  207. if self.partner_id.credit_limit != 0:
  208. if float_compare(amount - self.receipt + self.partner_id.receivable, self.partner_id.credit_limit,
  209. precision_digits=decimal_amount.digits) == 1:
  210. raise UserError('本次发货金额 + 客户应收余额 - 本次收款金额 不能大于客户信用额度!\n\
  211. 本次发货金额:%s\n 客户应收余额:%s\n 本次收款金额:%s\n客户信用额度:%s' % (
  212. amount, self.partner_id.receivable, self.receipt, self.partner_id.credit_limit))
  213. def _line_qty_write(self):
  214. if self.order_id:
  215. for line in self.line_in_ids:
  216. if self.order_id.type == 'return':
  217. line.sell_line_id.quantity_out += line.goods_qty
  218. else:
  219. line.sell_line_id.quantity_out -= line.goods_qty
  220. for line in self.line_out_ids:
  221. decimal_quantity = self.env.ref('core.decimal_quantity')
  222. if float_compare(
  223. line.sell_line_id.quantity_out + line.goods_qty,
  224. line.sell_line_id.quantity,
  225. decimal_quantity.digits) == 1:
  226. if not line.goods_id.excess:
  227. raise UserError('%s发货数量大于订单数量' % line.goods_id.name)
  228. line.sell_line_id.write({'quantity_out':line.sell_line_id.quantity_out + line.goods_qty})
  229. return
  230. def _get_invoice_vals(self, partner_id, category_id, date, amount, tax_amount):
  231. '''返回创建 money_invoice 时所需数据'''
  232. return {
  233. 'move_id': self.sell_move_id.id,
  234. 'name': self.name,
  235. 'partner_id': partner_id.id,
  236. 'pay_method': self.order_id.pay_method.id,
  237. 'category_id': category_id.id,
  238. 'date': date,
  239. 'amount': amount,
  240. 'reconciled': 0,
  241. 'to_reconcile': amount,
  242. 'tax_amount': tax_amount,
  243. 'date_due': self.date_due,
  244. 'state': 'draft',
  245. 'currency_id': self.currency_id.id,
  246. }
  247. def _delivery_make_invoice(self):
  248. '''发货单/退货单 生成结算单'''
  249. if not self.is_return:
  250. amount = self.amount + self.partner_cost
  251. tax_amount = sum(line.tax_amount for line in self.line_out_ids)
  252. else:
  253. amount = -(self.amount + self.partner_cost)
  254. tax_amount = - sum(line.tax_amount for line in self.line_in_ids)
  255. category = self.env.ref('money.core_category_sale')
  256. invoice_id = False
  257. if not float_is_zero(amount, 2):
  258. invoice_id = self.env['money.invoice'].create(
  259. self._get_invoice_vals(
  260. self.partner_id, category, self.date, amount, tax_amount)
  261. )
  262. return invoice_id
  263. def _sell_amount_to_invoice(self):
  264. '''销售费用产生结算单'''
  265. invoice_id = False
  266. if sum(cost_line.amount for cost_line in self.cost_line_ids) > 0:
  267. for line in self.cost_line_ids:
  268. if not float_is_zero(line.amount, 2):
  269. invoice_id = self.env['money.invoice'].create(
  270. self._get_invoice_vals(
  271. line.partner_id, line.category_id, self.date, line.amount + line.tax, line.tax)
  272. )
  273. return invoice_id
  274. def _make_money_order(self, invoice_id, amount, this_reconcile):
  275. '''生成收款单'''
  276. categ = self.env.ref('money.core_category_sale')
  277. money_lines = [{
  278. 'bank_id': self.bank_account_id.id,
  279. 'amount': this_reconcile,
  280. }]
  281. source_lines = [{
  282. 'name': invoice_id and invoice_id.id,
  283. 'category_id': categ.id,
  284. 'date': invoice_id and invoice_id.date,
  285. 'amount': amount,
  286. 'reconciled': 0.0,
  287. 'to_reconcile': amount,
  288. 'this_reconcile': this_reconcile,
  289. }]
  290. rec = self.with_context(type='get')
  291. money_order = rec.env['money.order'].create({
  292. 'partner_id': self.partner_id.id,
  293. 'date': self.date,
  294. 'line_ids': [(0, 0, line) for line in money_lines],
  295. 'source_ids': [(0, 0, line) for line in source_lines] if invoice_id.state == 'done' else False,
  296. 'amount': amount,
  297. 'reconciled': this_reconcile,
  298. 'to_reconcile': amount,
  299. 'state': 'draft',
  300. 'origin_name': self.name,
  301. 'sell_id': self.order_id.id,
  302. })
  303. return money_order
  304. def _create_voucher_line(self, account_id, debit, credit, voucher, goods_id, goods_qty):
  305. """
  306. 创建凭证明细行
  307. :param account_id: 科目
  308. :param debit: 借方
  309. :param credit: 贷方
  310. :param voucher: 凭证
  311. :param goods_id: 商品
  312. :return:
  313. """
  314. voucher_line = self.env['voucher.line'].create({
  315. 'name': '%s ' % (self.name),
  316. 'account_id': account_id and account_id.id,
  317. 'partner_id': not goods_id and self.partner_id.id,
  318. 'debit': debit,
  319. 'credit': credit,
  320. 'voucher_id': voucher and voucher.id,
  321. 'goods_qty': goods_qty,
  322. 'goods_id': goods_id and goods_id.id,
  323. 'auxiliary_id': self.project_id.auxiliary_id.id if self.project_id else False,
  324. })
  325. return voucher_line
  326. def create_voucher(self):
  327. '''
  328. 销售发货单、退货单审核时生成会计凭证
  329. 借:主营业务成本(核算分类上会计科目)
  330. 贷:库存商品(商品分类上会计科目)
  331. 当一张发货单有多个商品的时候,按对应科目汇总生成多个贷方凭证行。
  332. 退货单生成的金额为负
  333. '''
  334. self.ensure_one()
  335. voucher = self.env['voucher'].create({'date': self.date, 'ref': '%s,%s' % (self._name, self.id)})
  336. sum_amount = 0
  337. line_ids = self.is_return and self.line_in_ids or self.line_out_ids
  338. for line in line_ids: # 发货单/退货单明细
  339. cost = self.is_return and -line.cost or line.cost
  340. if not cost:
  341. continue # 缺货审核发货单时不产生出库凭证
  342. else: # 贷方明细
  343. sum_amount += cost
  344. self._create_voucher_line(line.goods_id.category_id.account_id,
  345. 0, cost, voucher, line.goods_id, line.goods_qty)
  346. if sum_amount: # 借方明细
  347. self._create_voucher_line(self.sell_move_id.finance_category_id.account_id,
  348. sum_amount, 0, voucher, False, 0)
  349. if len(voucher.line_ids) > 0:
  350. voucher.voucher_done()
  351. return voucher
  352. else:
  353. voucher.unlink()
  354. def auto_reconcile_sell_order(self):
  355. ''' 预收款与结算单自动核销 '''
  356. self.ensure_one()
  357. all_delivery_amount = 0
  358. for delivery in self.order_id.delivery_ids:
  359. all_delivery_amount += delivery.amount
  360. if (self.order_id.received_amount and self.order_id.received_amount == all_delivery_amount and
  361. not self.env.user.company_id.draft_invoice): #根据发票确认应收应付勾选时不自动核销
  362. adv_pay_result = []
  363. receive_source_result = []
  364. # 预收款
  365. adv_pay_orders = self.env['money.order'].search([('partner_id', '=', self.partner_id.id),
  366. ('type', '=', 'get'),
  367. ('state', '=', 'done'),
  368. ('to_reconcile',
  369. '!=', 0),
  370. ('sell_id', '=', self.order_id.id)])
  371. for order in adv_pay_orders:
  372. adv_pay_result.append((0, 0, {'name': order.id,
  373. 'amount': order.amount,
  374. 'date': order.date,
  375. 'reconciled': order.reconciled,
  376. 'to_reconcile': order.to_reconcile,
  377. 'this_reconcile': order.to_reconcile,
  378. }))
  379. # 结算单
  380. receive_source_name = [
  381. delivery.name for delivery in self.order_id.delivery_ids]
  382. receive_source_orders = self.env['money.invoice'].search([('category_id.type', '=', 'income'),
  383. ('partner_id', '=',
  384. self.partner_id.id),
  385. ('to_reconcile',
  386. '!=', 0),
  387. ('name', 'in', receive_source_name)])
  388. for invoice in receive_source_orders:
  389. receive_source_result.append((0, 0, {
  390. 'name': invoice.id,
  391. 'category_id': invoice.category_id.id,
  392. 'amount': invoice.amount,
  393. 'date': invoice.date,
  394. 'reconciled': invoice.reconciled,
  395. 'to_reconcile': invoice.to_reconcile,
  396. 'date_due': invoice.date_due,
  397. 'this_reconcile': invoice.to_reconcile,
  398. }))
  399. # 创建核销单
  400. reconcile_order = self.env['reconcile.order'].create({
  401. 'partner_id': self.partner_id.id,
  402. 'business_type': 'adv_pay_to_get',
  403. 'advance_payment_ids': adv_pay_result,
  404. 'receivable_source_ids': receive_source_result,
  405. 'note': '自动核销',
  406. })
  407. reconcile_order.reconcile_order_done() # 自动审核
  408. def sell_delivery_done(self):
  409. '''审核销售发货单/退货单,更新本单的收款状态/退款状态,并生成结算单和收款单'''
  410. for record in self:
  411. record._wrong_delivery_done()
  412. # 库存不足 生成零的
  413. if self.env.user.company_id.is_enable_negative_stock:
  414. result_vals = self.env['wh.move'].create_zero_wh_in(
  415. record, record._name)
  416. if result_vals:
  417. return result_vals
  418. # 调用wh.move中审核方法,更新审核人和审核状态
  419. record.sell_move_id.approve_order()
  420. # 将发货/退货数量写入销售订单行
  421. if record.order_id:
  422. record._line_qty_write()
  423. voucher = False
  424. # 创建出库的会计凭证,生成盘盈的入库单的不产生出库凭证
  425. if not self.env.user.company_id.endmonth_generation_cost:
  426. voucher = record.create_voucher()
  427. record.voucher_id = voucher
  428. # 发货单/退货单 生成结算单
  429. invoice_id = record._delivery_make_invoice()
  430. # 销售费用产生结算单
  431. record._sell_amount_to_invoice()
  432. # 生成收款单,并审核
  433. money_order = False
  434. if record.receipt:
  435. flag = not record.is_return and 1 or -1
  436. amount = flag * (record.amount + record.partner_cost)
  437. this_reconcile = flag * record.receipt
  438. money_order = record._make_money_order(
  439. invoice_id, amount, this_reconcile)
  440. money_order.money_order_done()
  441. record.write({
  442. 'voucher_id': voucher and voucher.id,
  443. 'invoice_id': invoice_id and invoice_id.id,
  444. 'money_order_id': money_order and money_order.id,
  445. 'state': 'done', # 为保证审批流程顺畅,否则,未审批就可审核
  446. })
  447. # 先收款后发货订单自动核销
  448. self.auto_reconcile_sell_order()
  449. if record.order_id:
  450. # 如果已退货也已退款,不生成新的分单
  451. if record.is_return and record.receipt:
  452. return True
  453. #产生新的销售发货单时,如果已经存在草稿的销售发货单时,先将已经存在的草稿发货单进行删除
  454. self.env['sell.delivery'].search(['&',('state', '=', 'draft'),'&',('order_id','=', record.order_id.id),('is_return', '=', False)]).unlink()
  455. return record.order_id.sell_generate_delivery()
  456. def sell_delivery_draft(self):
  457. '''反审核销售发货单/退货单,更新本单的收款状态/退款状态,并删除生成的结算单、收款单及凭证'''
  458. self.ensure_one()
  459. if self.state == 'draft':
  460. raise UserError('请不要重复撤销 %s' % self._description)
  461. # 当此发货单有关联的退货单时,禁止撤销此发货单
  462. related_returns = self.env['sell.delivery'].search([('origin_id', '=', self.id)])
  463. if related_returns:
  464. raise UserError(
  465. _("此发货单关联退货单,不能撤销!\n关联的单据号:%s") % (', '.join(related_returns.mapped('name'))))
  466. # 查找产生的结算单(除了开给客户的发票还有可能是采购费用发票)
  467. invoice_ids = self.env['money.invoice'].search([('name', '=', self.name)])
  468. for invoice in invoice_ids:
  469. # 不能反审核已核销的发货单
  470. if invoice.reconciled != 0:
  471. raise UserError('发票已核销,不能撤销发货!')
  472. if invoice.state == 'done':
  473. if self.env.company.draft_invoice:
  474. raise UserError('发票已开不可撤销发货')
  475. invoice.money_invoice_draft()
  476. invoice.unlink()
  477. # 删除产生的出库凭证
  478. voucher = self.voucher_id
  479. if voucher and voucher.state == 'done':
  480. voucher.voucher_draft()
  481. voucher.unlink()
  482. self.write({
  483. 'state': 'draft',
  484. })
  485. # 将原始订单中已执行数量清零
  486. if self.order_id:
  487. for line in self.line_out_ids:
  488. line.sell_line_id.quantity_out -= line.goods_qty
  489. for line in self.line_in_ids:
  490. if self.order_id.type == 'return':
  491. line.sell_line_id.quantity_out -= line.goods_qty
  492. else:
  493. line.sell_line_id.quantity_out += line.goods_qty
  494. # 调用wh.move中反审核方法,更新审核人和审核状态
  495. self.sell_move_id.cancel_approved_order()
  496. return True
  497. def sell_to_return(self):
  498. '''销售发货单转化为销售退货单'''
  499. return_goods = {}
  500. return_order_draft = self.search([
  501. ('is_return', '=', True),
  502. ('origin_id', '=', self.id),
  503. ('state', '=', 'draft')
  504. ])
  505. if return_order_draft:
  506. raise UserError('销售发货单存在草稿状态的退货单!')
  507. return_order = self.search([
  508. ('is_return', '=', True),
  509. ('origin_id', '=', self.id),
  510. ('state', '=', 'done')
  511. ])
  512. for order in return_order:
  513. for return_line in order.line_in_ids:
  514. # 用产品、属性、批次做key记录已退货数量
  515. t_key = (return_line.goods_id.id,
  516. return_line.attribute_id.id, return_line.lot)
  517. if return_goods.get(t_key):
  518. return_goods[t_key] += return_line.goods_qty
  519. else:
  520. return_goods[t_key] = return_line.goods_qty
  521. receipt_line = []
  522. for line in self.line_out_ids:
  523. qty = line.goods_qty
  524. l_key = (line.goods_id.id, line.attribute_id.id, line.lot_id.lot)
  525. if return_goods.get(l_key):
  526. qty = qty - return_goods[l_key]
  527. if qty > 0:
  528. dic = {
  529. 'goods_id': line.goods_id.id,
  530. 'attribute_id': line.attribute_id.id,
  531. 'uom_id': line.uom_id.id,
  532. 'warehouse_id': line.warehouse_dest_id.id,
  533. 'warehouse_dest_id': line.warehouse_id.id,
  534. 'goods_qty': qty,
  535. 'sell_line_id': line.sell_line_id.id,
  536. 'price_taxed': line.price_taxed,
  537. 'price': line.price,
  538. 'tax_rate':line.tax_rate,
  539. 'cost_unit': line.cost_unit,
  540. 'cost': line.cost,#退货取不到成本
  541. 'discount_rate': line.discount_rate,
  542. 'discount_amount': line.discount_amount,
  543. 'type': 'in',
  544. }
  545. if line.goods_id.using_batch:
  546. dic.update({'lot': line.lot_id.lot})
  547. receipt_line.append(dic)
  548. if len(receipt_line) == 0:
  549. raise UserError('该订单已全部退货!')
  550. vals = {'partner_id': self.partner_id.id,
  551. 'is_return': True,
  552. 'order_id': self.order_id.id,
  553. 'user_id': self.user_id.id,
  554. 'origin_id': self.id,
  555. 'origin': 'sell.delivery.return',
  556. 'warehouse_dest_id': self.warehouse_id.id,
  557. 'warehouse_id': self.warehouse_dest_id.id,
  558. 'bank_account_id': self.bank_account_id.id,
  559. 'date_due': (datetime.datetime.now()).strftime(ISODATEFORMAT),
  560. 'date': (datetime.datetime.now()).strftime(ISODATEFORMAT),
  561. 'line_in_ids': [(0, 0, line) for line in receipt_line],
  562. 'discount_amount': self.discount_amount,
  563. }
  564. delivery_return = self.with_context(is_return=True).create(vals)
  565. view_id = self.env.ref('sell.sell_return_form').id
  566. name = '销售退货单'
  567. return {
  568. 'name': name,
  569. 'view_mode': 'form',
  570. 'view_id': False,
  571. 'views': [(view_id, 'form')],
  572. 'res_model': 'sell.delivery',
  573. 'type': 'ir.actions.act_window',
  574. 'res_id': delivery_return.id,
  575. 'target': 'current'
  576. }
  577. def action_view_return(self):
  578. '''
  579. 该销售发货单对应的退货单
  580. '''
  581. self.ensure_one()
  582. action = {
  583. 'name': '销售退货单',
  584. 'type': 'ir.actions.act_window',
  585. 'view_type': 'form',
  586. 'view_mode': 'form',
  587. 'res_model': 'sell.delivery',
  588. 'view_id': False,
  589. 'target': 'current',
  590. }
  591. list_view_id = self.env.ref('sell.sell_return_list').id
  592. form_view_id = self.env.ref('sell.sell_return_form').id
  593. delivery_ids = [delivery.id for delivery in self.delivery_ids if delivery.is_return]
  594. if len(delivery_ids) > 1:
  595. action['domain'] = "[('id','in',[" + \
  596. ','.join(map(str, delivery_ids)) + "])]"
  597. action['view_mode'] = 'list,form'
  598. action['views'] = [(list_view_id, 'list'), (form_view_id, 'form')]
  599. elif len(delivery_ids) == 1:
  600. action['views'] = [(form_view_id, 'form')]
  601. action['res_id'] = delivery_ids and delivery_ids[0] or False
  602. return action
  603. class WhMoveLine(models.Model):
  604. _inherit = 'wh.move.line'
  605. sell_line_id = fields.Many2one('sell.order.line', '销售单行',
  606. ondelete='cascade',
  607. help='对应的销售订单行')
  608. @api.onchange('warehouse_id', 'goods_id')
  609. def onchange_warehouse_id(self):
  610. '''当订单行的仓库变化时,带出定价策略中的折扣率'''
  611. if self.warehouse_id and self.goods_id:
  612. partner_id = self.env.context.get('default_partner')
  613. partner = self.env['partner'].browse(
  614. partner_id) or self.move_id.partner_id
  615. warehouse = self.warehouse_id
  616. goods = self.goods_id
  617. date = self.env.context.get('default_date') or self.move_id.date
  618. if self.env.context.get('warehouse_type') == 'customer' or \
  619. self.env.context.get('warehouse_dest_type') == 'customer':
  620. pricing = self.env['pricing'].get_pricing_id(
  621. partner, warehouse, goods, date)
  622. if pricing:
  623. self.discount_rate = pricing.discount_rate
  624. else:
  625. self.discount_rate = 0
  626. def _delivery_get_price_and_tax(self):
  627. self.tax_rate = self.env.user.company_id.output_tax_rate
  628. self.price_taxed = self.goods_id.price
  629. if self.env.context.get('order_id'):
  630. line = self.env['sell.order.line'].search([
  631. ('order_id', '=', self.env.context.get('order_id')),
  632. ('goods_id', '=', self.goods_id.id)
  633. ], limit=1)
  634. if line:
  635. self.sell_line_id = line.id
  636. self.uos_id = line.goods_id.uos_id.id
  637. self.uom_id = line.uom_id.id
  638. self.price = line.price
  639. self.price_taxed = line.price_taxed
  640. self.discount_rate = line.discount_rate
  641. self.tax_rate = line.tax_rate
  642. self.plan_date = line.order_id.delivery_date
  643. else:
  644. raise UserError('无此商品的订单行')
  645. @api.onchange('goods_id')
  646. def onchange_goods_id(self):
  647. '''当订单行的商品变化时,带出商品上的零售价,以及公司的销项税'''
  648. self.ensure_one()
  649. is_return = self.env.context.get('default_is_return')
  650. if self.goods_id:
  651. # 如果是销售发货单行 或 销售退货单行
  652. if is_return is not None and \
  653. ((self.type == 'out' and not is_return) or (self.type == 'in' and is_return)):
  654. self._delivery_get_price_and_tax()
  655. return super(WhMoveLine, self).onchange_goods_id()
上海开阖软件有限公司 沪ICP备12045867号-1