pos_loyalty_usage_limit_custom/models/pos_order.py

48 lines
2.0 KiB
Python

# -*- coding: utf-8 -*-
from odoo import models, fields, _
class PosOrder(models.Model):
_inherit = 'pos.order'
def validate_coupon_programs(self, point_changes, new_codes):
res = super().validate_coupon_programs(point_changes, new_codes)
if not res.get('successful'):
return res
point_changes = {int(k): v for k, v in point_changes.items()}
coupon_ids_from_pos = set(point_changes.keys())
coupons = self.env['loyalty.card'].browse(coupon_ids_from_pos).exists()
for coupon in coupons:
if not coupon.limit:
continue
# Check if this coupon is being used for redemption (points are spent, i.e., point_change < 0)
# Or if it's 0 (maybe a reward that doesn't cost points?), but wait, point_changes is negative when spent.
if point_changes.get(coupon.id, 0) >= 0:
continue
# Calculate usages
domain = [('card_id', '=', coupon.id), ('used', '>', 0)]
today = fields.Datetime.now()
if coupon.limit_period == 'day':
domain.append(('create_date', '>=', today.replace(hour=0, minute=0, second=0, microsecond=0)))
elif coupon.limit_period == 'month':
domain.append(('create_date', '>=', today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)))
elif coupon.limit_period == 'year':
domain.append(('create_date', '>=', today.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)))
usage_count = self.env['loyalty.history'].search_count(domain)
if usage_count >= coupon.limit_count:
return {
'successful': False,
'payload': {
'message': _('The loyalty card %s has reached its usage limit of %s per %s.', coupon.code, coupon.limit_count, coupon.limit_period),
}
}
return res