fix: archive rather than delete old loyalty cards to maintain integrity of order history references

This commit is contained in:
Suherdy Yacob 2026-05-21 20:57:49 +07:00
parent 0f1ee75f86
commit 445ccf2f06

View File

@ -65,13 +65,13 @@ class PosOrder(models.Model):
other_programs = [pid for pid in all_multi_level_program_ids if pid != matched_program.id]
if other_programs:
old_cards = self.env['loyalty.card'].sudo().search([
# Find ALL old cards (with or without points) to clean them up
all_old_cards = self.env['loyalty.card'].sudo().search([
('partner_id', '=', partner.id),
('program_id', 'in', other_programs),
('points', '!=', 0),
])
if old_cards:
if all_old_cards:
new_card = self.env['loyalty.card'].sudo().search([
('partner_id', '=', partner.id),
('program_id', '=', matched_program.id),
@ -84,9 +84,14 @@ class PosOrder(models.Model):
'points': 0,
})
for old_card in old_cards:
# Transfer non-zero points to the new card, then delete ALL old cards
for old_card in all_old_cards:
pts = old_card.points
if abs(pts) > 0.0001:
new_card.points += pts
old_card.points = 0
# Archive old-level cards (active=False) instead of deleting,
# because pos_order_line.coupon_id may reference them (FK constraint).
# Archiving hides them from the UI while preserving order history.
all_old_cards.write({'active': False})