[FIX] sale_coupon: generate only one coupon per program per SO

Before this commit:
Everytime the SO met a 'on_next_order' program requirements, a coupon would be
generated on that SO. Even if there was already a coupon for that program set to
'expired', for instance when the SO did not met the requirements anymore.

Now:
When the requirements are met, it checks that an `expired` coupon does not
already exist.
It it does, it will set that coupon back to `reserved` state.

Step to reproduce:
  - Create a program on `next_order` with requirements, eg $300 amount
  - Create a SO and add $300 worth of products
  - Update promotion, a coupon is created and set to `reserved`
  - Now update the SO to go below $300
  - Update promotion, the coupon is set to `expired` as it should
  - Update again the SO to meet the $300 requirements again
  - Update promotion, a new `reserved` coupon is generated instead of updating
    the state of the previous one from `expired` to `reserved`

Closes #3062
This commit is contained in:
Romain Derie
2018-11-15 15:56:19 +01:00
parent 51c7afff48
commit 7b99c0db92
+18 -7
View File
@@ -216,13 +216,24 @@ class SaleOrder(models.Model):
self.write({'order_line': [(0, False, value) for value in self._get_reward_line_values(program)]})
def _create_reward_coupon(self, program):
coupon = self.env['sale.coupon'].create({
'program_id': program.id,
'state': 'reserved',
'partner_id': self.partner_id.id,
'order_id': self.id,
'discount_line_product_id': program.discount_line_product_id.id
})
# if there is already a coupon that was set as expired, reactivate that one instead of creating a new one
coupon = self.env['sale.coupon'].search([
('program_id', '=', program.id),
('state', '=', 'expired'),
('partner_id', '=', self.partner_id.id),
('order_id', '=', self.id),
('discount_line_product_id', '=', program.discount_line_product_id.id),
], limit=1)
if coupon:
coupon.write({'state': 'reserved'})
else:
coupon = self.env['sale.coupon'].create({
'program_id': program.id,
'state': 'reserved',
'partner_id': self.partner_id.id,
'order_id': self.id,
'discount_line_product_id': program.discount_line_product_id.id
})
self.generated_coupon_ids |= coupon
return coupon