From 445ccf2f067d92e579f50f5ee8824a2703330c6b Mon Sep 17 00:00:00 2001 From: Suherdy Yacob Date: Thu, 21 May 2026 20:57:49 +0700 Subject: [PATCH] fix: archive rather than delete old loyalty cards to maintain integrity of order history references --- models/pos_order.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/models/pos_order.py b/models/pos_order.py index b65848d..c8d4134 100644 --- a/models/pos_order.py +++ b/models/pos_order.py @@ -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})