diff --git a/CRM/Tbusainvoicegen/Timebank.php b/CRM/Tbusainvoicegen/Timebank.php index 08cd2e7..b0dded9 100644 --- a/CRM/Tbusainvoicegen/Timebank.php +++ b/CRM/Tbusainvoicegen/Timebank.php @@ -6,9 +6,11 @@ class CRM_Tbusainvoicegen_Timebank { * Live settings * const TBBILLABLEFIELD = 'custom_202'; * const BILLABLEMEMBERFIELD = 'custom_199'; + * const BILLINGPERIODFIELD = 'custom_228'; */ const TBBILLABLEFIELD = 'custom_9'; const BILLABLEMEMBERFIELD = 'custom_10'; + const BILLINGPERIODFIELD = 'custom_11'; /** * Set the pricing here. @@ -84,9 +86,12 @@ class CRM_Tbusainvoicegen_Timebank { 'options' => ['limit' => 0], ])['values']; self::setContributionExists(); - foreach ($result as $k => $contact) { - $tb = new CRM_Tbusainvoicegen_Timebank($k, $contact[self::BILLABLEMEMBERFIELD]); - $price = $tb->setPrice(); + foreach ($contacts as $k => $contact) { + if (!in_array($k, self::$contributionExists)) { + $tb = new CRM_Tbusainvoicegen_Timebank($k, $contact[self::BILLABLEMEMBERFIELD]); + $tb->setPrice(); + $tb->createContribution(); + } } } @@ -103,8 +108,16 @@ class CRM_Tbusainvoicegen_Timebank { * Generate an array of contacts who already have a contribution created in this billing period. */ public static function setContributionExists() { - // API call to contribution.get to find all records with this billing period - // Return an array of contact IDs. + $existing = []; + $result = civicrm_api3('Contribution', 'get', [ + self::BILLINGPERIODFIELD => self::$billingPeriod, + ]); + if ($result['count']) { + foreach ($result['values'] as $contrib) { + $existing[$contrib['contact_id']] = $contrib['contact_id']; + } + } + self::$contributionExists = $existing; } private function setPrice() { @@ -121,4 +134,31 @@ class CRM_Tbusainvoicegen_Timebank { return $this->price; } + private function createContribution() { + $dueDate = $this->calculateDueDate(); + civicrm_api3('Contribution', 'create', [ + 'financial_type_id' => 'CW License Fee', + 'date_received' => $dueDate, + 'total_amount' => $this->price, + 'contact_id' => $this->cid, + 'contribution_status_id' => 'Pending', + self::BILLINGPERIODFIELD => self::$billingPeriod, + ]); + } + + /** + * Returns the due date as a string. + * @return string + */ + private function calculateDueDate() { + list($year, $number) = explode('-', self::$billingPeriod); + if ($number == 1) { + $dueDate = $year . '-03-31'; + } + else { + $dueDate = $year . '-09-30'; + } + return $dueDate; + } + } diff --git a/api/v3/Invoicegen/Generate.php b/api/v3/Invoicegen/Generate.php index b6763ca..33550c8 100644 --- a/api/v3/Invoicegen/Generate.php +++ b/api/v3/Invoicegen/Generate.php @@ -11,7 +11,7 @@ use CRM_Tbusainvoicegen_ExtensionUtil as E; */ function _civicrm_api3_invoicegen_Generate_spec(&$spec) { $spec['contact_id']['api.required'] = 0; - $spec['billing_period']['api.required'] = 0; + $spec['billing_period']['api.required'] = 1; } /**