From f14d5aa98c4a6d0ab4112547c1554f154fb3a2e9 Mon Sep 17 00:00:00 2001
From: Rafael Monnerat <rafael@nexedi.com>
Date: Wed, 30 Sep 2020 23:21:46 +0000
Subject: [PATCH] slapos_crm: Invalidate Regularisation Request with the same
 rule of Person_checkToCreateRegularisationRequest

---
 ...onRequest_invalidateIfPersonBalanceIsOk.py | 22 ++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)

diff --git a/master/bt5/slapos_crm/SkinTemplateItem/portal_skins/slapos_crm/RegularisationRequest_invalidateIfPersonBalanceIsOk.py b/master/bt5/slapos_crm/SkinTemplateItem/portal_skins/slapos_crm/RegularisationRequest_invalidateIfPersonBalanceIsOk.py
index 5c6f63a49..aa774945b 100644
--- a/master/bt5/slapos_crm/SkinTemplateItem/portal_skins/slapos_crm/RegularisationRequest_invalidateIfPersonBalanceIsOk.py
+++ b/master/bt5/slapos_crm/SkinTemplateItem/portal_skins/slapos_crm/RegularisationRequest_invalidateIfPersonBalanceIsOk.py
@@ -5,8 +5,24 @@ if REQUEST is not None:
 state = context.getSimulationState()
 person = context.getSourceProjectValue(portal_type="Person")
 if (state != 'suspended') or \
-   (person is None) or \
-   (int(person.Entity_statOutstandingAmount()) > 0):
+   (person is None):
   return
-else:
+
+outstanding_amount = person.Entity_statSlapOSOutstandingAmount()
+
+# Amount to be ignored, as it comes from the first invoice generated
+# after the subscription. We do not take it into account as no service
+# was provided yet.
+unpaid_payment_amount = 0
+for payment in person.Person_getSubscriptionRequestFirstUnpaidPaymentList():
+  unpaid_payment_amount += payment.PaymentTransaction_getTotalPayablePrice()
+
+# It can't be smaller, we are considernig all open invoices are from unpaid_payment_amount
+if round(float(outstanding_amount), 2) == round(-float(unpaid_payment_amount), 2):
   context.invalidate(comment="Automatically disabled as balance is %s" % person.Entity_statOutstandingAmount())
+
+
+if (int(outstanding_amount) > 0):
+  return
+
+context.invalidate(comment="Automatically disabled as balance is %s" % person.Entity_statOutstandingAmount())
-- 
2.30.9