From 1373367ac39bd0a959faaaf13f56b5a97926aa1e Mon Sep 17 00:00:00 2001
From: Johannes Hoermann <j.hoermann@adito.de>
Date: Tue, 26 Nov 2019 14:10:45 +0100
Subject: [PATCH] check also commrestriction from organisation

---
 process/Contact_lib/process.js | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/process/Contact_lib/process.js b/process/Contact_lib/process.js
index 87c6e1b111..1f8eef3ec9 100644
--- a/process/Contact_lib/process.js
+++ b/process/Contact_lib/process.js
@@ -323,9 +323,9 @@ ContactUtils.getOrganisationContactId = function(pAnyContactId)
 {
     if (!pAnyContactId)
         return "";
-    
+
     var idSql = SqlCondition.begin()
-            .andPrepare("anyContact.CONTACTID", pAnyContactId, null, SqlUtils.getSingleColumnType("CONTACT", "CONTACTID"))
+            .andPrepare(["CONTACT", "CONTACTID", "anyContact"], pAnyContactId)
             .and("CONTACT.PERSON_ID is null")
             .buildSql("select CONTACT.CONTACTID \n\
                 from CONTACT\n\
@@ -459,7 +459,7 @@ ContactUtils.getDefaultAddressId = function(pContactId)
  * @param {String} pMedium medium to check
  * @param {boolean} [pNoRestriction=false] if true, the condition gets every contact that has no
  *                                     a commrestriction, otherwise every contact that has a commrestriction
- * @param {String|Number} [pStartDate=current date] the start date of the commrestriction
+ * @param {String|Number} [pStartDate=current date] date to check against the start date of the commrestriction
  * 
  * @return {SqlCondition} the condition
  */
@@ -473,9 +473,16 @@ ContactUtils.getCommRestrictionCondition = function (pMedium, pNoRestriction, pS
         .where(SqlCondition.begin()
             .andPrepare("COMMRESTRICTION.MEDIUM", pMedium)
             .andPrepare("COMMRESTRICTION.STARTDATE", pStartDate, "# <= ?")
-            .and("(COMMRESTRICTION.CONTACT_ID = CONTACT.CONTACTID or COMMRESTRICTION.CONTACT_ID = CONTACT.PERSON_ID)")
+            .and(SqlCondition.begin()
+                    // check contactid
+                    .or("COMMRESTRICTION.CONTACT_ID = CONTACT.CONTACTID")
+                    // or the contact id of the organisation
+                    .or("COMMRESTRICTION.CONTACT_ID = (select orgContact.CONTACTID from CONTACT anyContact \n\
+                            join CONTACT orgContact on anyContact.ORGANISATION_ID = orgContact.ORGANISATION_ID \n\
+                            and orgContact.PERSON_ID is null where anyContact.CONTACTID = CONTACT.CONTACTID)")
+                )
             .build("1=2"));
-            
+
     var cond = "exists";
     if (pNoRestriction)
         cond = "not " + cond;
-- 
GitLab