SearchKit - Use contribution currency when formatting LineItem amounts
authorColeman Watts <coleman@civicrm.org>
Thu, 15 Sep 2022 19:12:27 +0000 (15:12 -0400)
committerColeman Watts <coleman@civicrm.org>
Thu, 15 Sep 2022 19:12:27 +0000 (15:12 -0400)
ext/search_kit/Civi/Api4/Action/SearchDisplay/AbstractRunAction.php
ext/search_kit/tests/phpunit/api/v4/SearchDisplay/SearchRunTest.php

index 2a747a264773c675b182c7e9b360fbc8be6960c8..1dfb5d75d08ab9e387bc4e3b5b1a67db65cec431 100644 (file)
@@ -972,6 +972,19 @@ abstract class AbstractRunAction extends \Civi\Api4\Generic\AbstractAction {
         }
       }
     }
+    // If the base entity has a field named 'currency', fall back on that.
+    if ($this->getField('currency')) {
+      return 'currency';
+    }
+    // Finally, if there's a FK field to civicrm_contribution, we can use an implicit join
+    // E.G. the LineItem entity has no `currency` field of its own & uses that of the contribution record
+    if ($entityDao) {
+      foreach ($entityDao::getSupportedFields() as $fieldName => $field) {
+        if (($field['FKClassName'] ?? NULL) === 'CRM_Contribute_DAO_Contribution') {
+          return $prefix . $fieldName . '.currency';
+        }
+      }
+    }
     return NULL;
   }
 
index 3e6cc7d1a4a05bbcb5dbc6f269554af023fe522c..b7f3e9d2519d213150ae26b166d7a427492dc751 100644 (file)
@@ -1396,6 +1396,29 @@ class SearchRunTest extends Api4TestBase implements TransactionalInterface {
 
     $this->assertEquals('JPY', $result[2]['data']['currency']);
     $this->assertEquals('¥ 500.00', $result[2]['columns'][0]['val']);
+
+    // Now do a search for the contribution line-items
+    $params['savedSearch'] = [
+      'api_entity' => 'LineItem',
+      'api_params' => [
+        'version' => 4,
+        'select' => ['line_total'],
+        'where' => [['contribution_id', 'IN', $contributions->column('id')]],
+      ],
+    ];
+
+    $result = civicrm_api4('SearchDisplay', 'run', $params);
+    $this->assertCount(3, $result);
+
+    // An automatic join should have been added to fetch the contribution currency
+    $this->assertEquals('GBP', $result[0]['data']['contribution_id.currency']);
+    $this->assertEquals('£ 100.00', $result[0]['columns'][0]['val']);
+
+    $this->assertEquals('USD', $result[1]['data']['contribution_id.currency']);
+    $this->assertEquals('$ 200.00', $result[1]['columns'][0]['val']);
+
+    $this->assertEquals('JPY', $result[2]['data']['contribution_id.currency']);
+    $this->assertEquals('¥ 500.00', $result[2]['columns'][0]['val']);
   }
 
 }