Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | class CRM_Pledge_BAO_Pledge extends CRM_Pledge_DAO_Pledge { | |
18 | ||
19 | /** | |
fe482240 | 20 | * Static field for all the pledge information that we can potentially export. |
6a488035 TO |
21 | * |
22 | * @var array | |
6a488035 | 23 | */ |
c86d4e7c | 24 | public static $_exportableFields = NULL; |
6a488035 | 25 | |
6a488035 | 26 | /** |
fe482240 EM |
27 | * Retrieve DB object based on input parameters. |
28 | * | |
29 | * It also stores all the retrieved values in the default array. | |
6a488035 | 30 | * |
3a1617b6 TO |
31 | * @param array $params |
32 | * (reference ) an assoc array of name/value pairs. | |
33 | * @param array $defaults | |
34 | * (reference ) an assoc array to hold the flattened values. | |
6a488035 | 35 | * |
16b10e64 | 36 | * @return CRM_Pledge_BAO_Pledge |
6a488035 | 37 | */ |
00be9182 | 38 | public static function retrieve(&$params, &$defaults) { |
6a488035 TO |
39 | $pledge = new CRM_Pledge_DAO_Pledge(); |
40 | $pledge->copyValues($params); | |
41 | if ($pledge->find(TRUE)) { | |
42 | CRM_Core_DAO::storeValues($pledge, $defaults); | |
43 | return $pledge; | |
44 | } | |
45 | return NULL; | |
46 | } | |
47 | ||
48 | /** | |
fe482240 | 49 | * Add pledge. |
6a488035 | 50 | * |
3a1617b6 TO |
51 | * @param array $params |
52 | * Reference array contains the values submitted by the form. | |
6a488035 | 53 | * |
45ae836f | 54 | * @return CRM_Pledge_DAO_Pledge |
6a488035 | 55 | */ |
45ae836f | 56 | public static function add(array $params): CRM_Pledge_DAO_Pledge { |
1f6f2538 | 57 | CRM_Core_Error::deprecatedFunctionWarning('v4 api'); |
45ae836f | 58 | $hook = empty($params['id']) ? 'create' : 'edit'; |
59 | CRM_Utils_Hook::pre($hook, 'Pledge', $params['id'] ?? NULL, $params); | |
6a488035 TO |
60 | |
61 | $pledge = new CRM_Pledge_DAO_Pledge(); | |
62 | ||
63 | // if pledge is complete update end date as current date | |
64 | if ($pledge->status_id == 1) { | |
65 | $pledge->end_date = date('Ymd'); | |
66 | } | |
67 | ||
68 | $pledge->copyValues($params); | |
69 | ||
70 | // set currency for CRM-1496 | |
71 | if (!isset($pledge->currency)) { | |
bb06e9ed | 72 | $pledge->currency = CRM_Core_Config::singleton()->defaultCurrency; |
6a488035 TO |
73 | } |
74 | ||
75 | $result = $pledge->save(); | |
76 | ||
45ae836f | 77 | CRM_Utils_Hook::post($hook, 'Pledge', $pledge->id, $pledge); |
6a488035 TO |
78 | |
79 | return $result; | |
80 | } | |
81 | ||
82 | /** | |
83 | * Given the list of params in the params array, fetch the object | |
84 | * and store the values in the values array | |
85 | * | |
3a1617b6 TO |
86 | * @param array $params |
87 | * Input parameters to find object. | |
88 | * @param array $values | |
89 | * Output values of the object. | |
90 | * @param array $returnProperties | |
91 | * If you want to return specific fields. | |
6a488035 | 92 | * |
a6c01b45 CW |
93 | * @return array |
94 | * associated array of field values | |
6a488035 | 95 | */ |
00be9182 | 96 | public static function &getValues(&$params, &$values, $returnProperties = NULL) { |
6a488035 TO |
97 | if (empty($params)) { |
98 | return NULL; | |
99 | } | |
100 | CRM_Core_DAO::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties); | |
101 | return $values; | |
102 | } | |
103 | ||
104 | /** | |
fe482240 | 105 | * Takes an associative array and creates a pledge object. |
6a488035 | 106 | * |
3a1617b6 | 107 | * @param array $params |
45ae836f | 108 | * Assoc array of name/value pairs. |
6a488035 | 109 | * |
45ae836f | 110 | * @return CRM_Pledge_DAO_Pledge |
111 | * @throws \CRM_Core_Exception | |
6a488035 | 112 | */ |
1f6f2538 | 113 | public static function create(array $params): CRM_Pledge_DAO_Pledge { |
7c86e53f | 114 | $action = empty($params['id']) ? 'create' : 'edit'; |
115 | if ($action === 'create') { | |
116 | $defaults = [ | |
117 | 'currency' => CRM_Core_Config::singleton()->defaultCurrency, | |
118 | 'installments' => (int) self::fields()['installments']['default'], | |
119 | 'scheduled_date' => $params['start_date'] ?? date('Ymd'), | |
120 | ]; | |
121 | $params = array_merge($defaults, $params); | |
122 | } | |
6a488035 | 123 | |
f27fa890 | 124 | $isRecalculatePledgePayment = self::isPaymentsRequireRecalculation($params); |
6a488035 TO |
125 | $transaction = new CRM_Core_Transaction(); |
126 | ||
affcc9d2 | 127 | $paymentParams = []; |
a7488080 | 128 | if (!empty($params['installment_amount'])) { |
6a488035 TO |
129 | $params['amount'] = $params['installment_amount'] * $params['installments']; |
130 | } | |
131 | ||
1c0174c9 | 132 | if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) { |
6a488035 TO |
133 | if (isset($params['contribution_id'])) { |
134 | if ($params['installments'] > 1) { | |
ab6ba136 | 135 | $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress'); |
6a488035 TO |
136 | } |
137 | } | |
138 | else { | |
139 | if (!empty($params['id'])) { | |
140 | $params['status_id'] = CRM_Pledge_BAO_PledgePayment::calculatePledgeStatus($params['id']); | |
141 | } | |
142 | else { | |
ab6ba136 | 143 | $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending'); |
6a488035 TO |
144 | } |
145 | } | |
146 | } | |
9c1bc317 | 147 | $paymentParams['status_id'] = $params['status_id'] ?? NULL; |
6a488035 | 148 | |
bf46adf0 | 149 | $pledge = self::writeRecord($params); |
6a488035 | 150 | |
7c86e53f | 151 | // skip payment stuff in edit mode |
f27fa890 | 152 | if (empty($params['id']) || $isRecalculatePledgePayment) { |
6a488035 | 153 | |
cc28438b | 154 | // if pledge is pending delete all payments and recreate. |
f27fa890 | 155 | if ($isRecalculatePledgePayment) { |
6a488035 TO |
156 | CRM_Pledge_BAO_PledgePayment::deletePayments($pledge->id); |
157 | } | |
158 | ||
cc28438b | 159 | // building payment params |
6a488035 | 160 | $paymentParams['pledge_id'] = $pledge->id; |
6f1bfb6d | 161 | $paymentKeys = [ |
353ffa53 TO |
162 | 'amount', |
163 | 'installments', | |
164 | 'scheduled_date', | |
165 | 'frequency_unit', | |
166 | 'currency', | |
167 | 'frequency_day', | |
168 | 'frequency_interval', | |
169 | 'contribution_id', | |
170 | 'installment_amount', | |
171 | 'actual_amount', | |
6f1bfb6d | 172 | ]; |
6a488035 | 173 | foreach ($paymentKeys as $key) { |
9c1bc317 | 174 | $paymentParams[$key] = $params[$key] ?? NULL; |
6a488035 | 175 | } |
4cc3286d | 176 | CRM_Pledge_BAO_PledgePayment::createMultiple($paymentParams); |
6a488035 TO |
177 | } |
178 | ||
179 | $transaction->commit(); | |
180 | ||
181 | $url = CRM_Utils_System::url('civicrm/contact/view/pledge', | |
182 | "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home" | |
183 | ); | |
184 | ||
affcc9d2 | 185 | $recentOther = []; |
6a488035 TO |
186 | if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) { |
187 | $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', | |
188 | "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home" | |
189 | ); | |
190 | } | |
191 | if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) { | |
192 | $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', | |
193 | "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home" | |
194 | ); | |
195 | } | |
196 | ||
25e778a5 E |
197 | $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); |
198 | $title = CRM_Contact_BAO_Contact::displayName($pledge->contact_id) . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($pledge->amount, $pledge->currency) . ' - ' . CRM_Utils_Array::value($pledge->financial_type_id, $contributionTypes) . ')'; | |
6a488035 TO |
199 | |
200 | // add the recently created Pledge | |
201 | CRM_Utils_Recent::add($title, | |
202 | $url, | |
203 | $pledge->id, | |
204 | 'Pledge', | |
205 | $pledge->contact_id, | |
206 | NULL, | |
207 | $recentOther | |
208 | ); | |
209 | ||
210 | return $pledge; | |
211 | } | |
212 | ||
1e071f70 | 213 | /** |
6f1bfb6d | 214 | * Is this a change to an existing pending pledge requiring payment schedule |
215 | * changes. | |
1e071f70 | 216 | * |
6f1bfb6d | 217 | * If the pledge is pending the code (slightly lazily) deletes & recreates |
218 | * pledge payments. | |
1e071f70 | 219 | * |
6f1bfb6d | 220 | * If the payment dates or amounts have been manually edited then this can |
221 | * cause data loss. We can mitigate this to some extent by making sure we | |
222 | * have a change that could potentially affect the schedule (rather than just | |
223 | * a custom data change or similar). | |
1e071f70 | 224 | * |
6f1bfb6d | 225 | * This calculation needs to be performed before update takes place as |
226 | * previous & new pledges are compared. | |
1e071f70 | 227 | * |
228 | * @param array $params | |
229 | * | |
230 | * @return bool | |
231 | */ | |
232 | protected static function isPaymentsRequireRecalculation($params) { | |
233 | if (empty($params['is_pledge_pending']) || empty($params['id'])) { | |
234 | return FALSE; | |
235 | } | |
6f1bfb6d | 236 | $scheduleChangingParameters = [ |
1e071f70 | 237 | 'amount', |
238 | 'frequency_unit', | |
239 | 'frequency_interval', | |
240 | 'frequency_day', | |
241 | 'installments', | |
242 | 'start_date', | |
6f1bfb6d | 243 | ]; |
1e071f70 | 244 | $existingPledgeDAO = new CRM_Pledge_BAO_Pledge(); |
245 | $existingPledgeDAO->id = $params['id']; | |
246 | $existingPledgeDAO->find(TRUE); | |
247 | foreach ($scheduleChangingParameters as $parameter) { | |
248 | if ($parameter == 'start_date') { | |
249 | if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) { | |
250 | return TRUE; | |
251 | } | |
252 | } | |
253 | elseif ($params[$parameter] != $existingPledgeDAO->$parameter) { | |
254 | return TRUE; | |
255 | } | |
256 | } | |
257 | } | |
258 | ||
6a488035 | 259 | /** |
fe482240 | 260 | * Delete the pledge. |
6a488035 | 261 | * |
3a1617b6 TO |
262 | * @param int $id |
263 | * Pledge id. | |
6a488035 | 264 | * |
77b97be7 | 265 | * @return mixed |
6a488035 | 266 | */ |
00be9182 | 267 | public static function deletePledge($id) { |
be12df5a | 268 | CRM_Utils_Hook::pre('delete', 'Pledge', $id); |
6a488035 TO |
269 | |
270 | $transaction = new CRM_Core_Transaction(); | |
271 | ||
cc28438b | 272 | // check for no Completed Payment records with the pledge |
6a488035 TO |
273 | $payment = new CRM_Pledge_DAO_PledgePayment(); |
274 | $payment->pledge_id = $id; | |
275 | $payment->find(); | |
276 | ||
277 | while ($payment->fetch()) { | |
cc28438b | 278 | // also delete associated contribution. |
6a488035 TO |
279 | if ($payment->contribution_id) { |
280 | CRM_Contribute_BAO_Contribution::deleteContribution($payment->contribution_id); | |
281 | } | |
282 | $payment->delete(); | |
283 | } | |
284 | ||
353ffa53 | 285 | $dao = new CRM_Pledge_DAO_Pledge(); |
6a488035 TO |
286 | $dao->id = $id; |
287 | $results = $dao->delete(); | |
288 | ||
289 | $transaction->commit(); | |
290 | ||
291 | CRM_Utils_Hook::post('delete', 'Pledge', $dao->id, $dao); | |
292 | ||
6a488035 TO |
293 | return $results; |
294 | } | |
295 | ||
296 | /** | |
100fef9d | 297 | * Get the amount details date wise. |
b55cf2b2 EM |
298 | * |
299 | * @param string $status | |
300 | * @param string $startDate | |
301 | * @param string $endDate | |
302 | * | |
303 | * @return array|null | |
6a488035 | 304 | */ |
00be9182 | 305 | public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) { |
affcc9d2 | 306 | $where = []; |
6a488035 | 307 | $select = $from = $queryDate = NULL; |
ab6ba136 | 308 | $statusId = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status); |
6a488035 TO |
309 | |
310 | switch ($status) { | |
311 | case 'Completed': | |
ab6ba136 | 312 | $where[] = 'status_id != ' . CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled'); |
6a488035 TO |
313 | break; |
314 | ||
315 | case 'Cancelled': | |
6a488035 | 316 | case 'In Progress': |
6a488035 | 317 | case 'Pending': |
6a488035 TO |
318 | case 'Overdue': |
319 | $where[] = 'status_id = ' . $statusId; | |
320 | break; | |
321 | } | |
322 | ||
323 | if ($startDate) { | |
324 | $where[] = "create_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'"; | |
325 | } | |
326 | if ($endDate) { | |
327 | $where[] = "create_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'"; | |
328 | } | |
329 | ||
330 | $whereCond = implode(' AND ', $where); | |
331 | ||
332 | $query = " | |
333 | SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency | |
334 | FROM civicrm_pledge | |
335 | WHERE $whereCond AND is_test=0 | |
336 | GROUP BY currency | |
337 | "; | |
353ffa53 TO |
338 | $start = substr($startDate, 0, 8); |
339 | $end = substr($endDate, 0, 8); | |
340 | $pCount = 0; | |
affcc9d2 | 341 | $pamount = []; |
9d2678f4 | 342 | $dao = CRM_Core_DAO::executeQuery($query); |
6a488035 TO |
343 | while ($dao->fetch()) { |
344 | $pCount += $dao->pledge_count; | |
345 | $pamount[] = CRM_Utils_Money::format($dao->pledge_amount, $dao->currency); | |
346 | } | |
347 | ||
6f1bfb6d | 348 | $pledge_amount = [ |
353ffa53 | 349 | 'pledge_amount' => implode(', ', $pamount), |
6a488035 TO |
350 | 'pledge_count' => $pCount, |
351 | 'purl' => CRM_Utils_System::url('civicrm/pledge/search', | |
352 | "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0" | |
353 | ), | |
6f1bfb6d | 354 | ]; |
6a488035 | 355 | |
affcc9d2 | 356 | $where = []; |
6a488035 TO |
357 | switch ($status) { |
358 | case 'Completed': | |
353ffa53 TO |
359 | $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count'; |
360 | $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0'; | |
6a488035 | 361 | $queryDate = 'receive_date'; |
353ffa53 | 362 | $from = ' civicrm_contribution cd, civicrm_pledge_payment cp'; |
6a488035 TO |
363 | break; |
364 | ||
365 | case 'Cancelled': | |
353ffa53 TO |
366 | $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count'; |
367 | $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0'; | |
6a488035 | 368 | $queryDate = 'receive_date'; |
353ffa53 | 369 | $from = ' civicrm_contribution cd, civicrm_pledge_payment cp'; |
6a488035 TO |
370 | break; |
371 | ||
372 | case 'Pending': | |
353ffa53 TO |
373 | $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count'; |
374 | $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0'; | |
6a488035 | 375 | $queryDate = 'scheduled_date'; |
353ffa53 | 376 | $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id'; |
6a488035 TO |
377 | break; |
378 | ||
379 | case 'Overdue': | |
353ffa53 TO |
380 | $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count'; |
381 | $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0'; | |
6a488035 | 382 | $queryDate = 'scheduled_date'; |
353ffa53 | 383 | $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id'; |
6a488035 TO |
384 | break; |
385 | } | |
386 | ||
387 | if ($startDate) { | |
388 | $where[] = " $queryDate >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'"; | |
389 | } | |
390 | if ($endDate) { | |
391 | $where[] = " $queryDate <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'"; | |
392 | } | |
393 | ||
394 | $whereCond = implode(' AND ', $where); | |
395 | ||
396 | $query = " | |
397 | SELECT $select, cp.currency | |
398 | FROM $from | |
399 | WHERE $whereCond | |
400 | GROUP BY cp.currency | |
401 | "; | |
402 | if ($select) { | |
9d2678f4 | 403 | $dao = CRM_Core_DAO::executeQuery($query); |
affcc9d2 | 404 | $amount = []; |
353ffa53 | 405 | $count = 0; |
6a488035 TO |
406 | |
407 | while ($dao->fetch()) { | |
408 | $count += $dao->received_count; | |
409 | $amount[] = CRM_Utils_Money::format($dao->received_pledge, $dao->currency); | |
410 | } | |
411 | ||
412 | if ($count) { | |
6f1bfb6d | 413 | return array_merge($pledge_amount, [ |
353ffa53 TO |
414 | 'received_amount' => implode(', ', $amount), |
415 | 'received_count' => $count, | |
416 | 'url' => CRM_Utils_System::url('civicrm/pledge/search', | |
417 | "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0" | |
418 | ), | |
6f1bfb6d | 419 | ]); |
6a488035 TO |
420 | } |
421 | } | |
422 | else { | |
423 | return $pledge_amount; | |
424 | } | |
425 | return NULL; | |
426 | } | |
427 | ||
428 | /** | |
fe482240 | 429 | * Get list of pledges In Honor of contact Ids. |
6a488035 | 430 | * |
3a1617b6 TO |
431 | * @param int $honorId |
432 | * In Honor of Contact ID. | |
6a488035 | 433 | * |
a6c01b45 CW |
434 | * @return array |
435 | * return the list of pledge fields | |
6a488035 | 436 | */ |
00be9182 | 437 | public static function getHonorContacts($honorId) { |
affcc9d2 | 438 | $params = []; |
8381af80 | 439 | $honorDAO = new CRM_Contribute_DAO_ContributionSoft(); |
440 | $honorDAO->contact_id = $honorId; | |
6a488035 TO |
441 | $honorDAO->find(); |
442 | ||
cc28438b | 443 | // get all status. |
6a488035 | 444 | while ($honorDAO->fetch()) { |
8381af80 | 445 | $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment(); |
446 | $pledgePaymentDAO->contribution_id = $honorDAO->contribution_id; | |
447 | if ($pledgePaymentDAO->find(TRUE)) { | |
448 | $pledgeDAO = new CRM_Pledge_DAO_Pledge(); | |
449 | $pledgeDAO->id = $pledgePaymentDAO->pledge_id; | |
450 | if ($pledgeDAO->find(TRUE)) { | |
6f1bfb6d | 451 | $params[$pledgeDAO->id] = [ |
b7617307 | 452 | 'honor_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id), |
8381af80 | 453 | 'honorId' => $pledgeDAO->contact_id, |
454 | 'amount' => $pledgeDAO->amount, | |
01dac399 | 455 | 'status' => CRM_Core_PseudoConstant::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id), |
8381af80 | 456 | 'create_date' => $pledgeDAO->create_date, |
457 | 'acknowledge_date' => $pledgeDAO->acknowledge_date, | |
458 | 'type' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', | |
459 | $pledgeDAO->financial_type_id, 'name' | |
460 | ), | |
461 | 'display_name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', | |
462 | $pledgeDAO->contact_id, 'display_name' | |
463 | ), | |
6f1bfb6d | 464 | ]; |
8381af80 | 465 | } |
466 | } | |
6a488035 | 467 | } |
8381af80 | 468 | |
6a488035 TO |
469 | return $params; |
470 | } | |
471 | ||
472 | /** | |
100fef9d | 473 | * Send Acknowledgment and create activity. |
6a488035 | 474 | * |
3a1617b6 TO |
475 | * @param CRM_Core_Form $form |
476 | * Form object. | |
477 | * @param array $params | |
478 | * An assoc array of name/value pairs. | |
6a488035 | 479 | */ |
00be9182 | 480 | public static function sendAcknowledgment(&$form, $params) { |
6a488035 | 481 | //handle Acknowledgment. |
affcc9d2 | 482 | $allPayments = $payments = []; |
6a488035 | 483 | |
cc28438b | 484 | // get All Payments status types. |
6a488035 | 485 | $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
6f1bfb6d | 486 | $returnProperties = [ |
487 | 'status_id', | |
488 | 'scheduled_amount', | |
489 | 'scheduled_date', | |
490 | 'contribution_id', | |
491 | ]; | |
cc28438b | 492 | // get all paymnets details. |
6a488035 TO |
493 | CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties); |
494 | ||
495 | if (!empty($allPayments)) { | |
496 | foreach ($allPayments as $payID => $values) { | |
affcc9d2 | 497 | $contributionValue = $contributionStatus = []; |
6a488035 | 498 | if (isset($values['contribution_id'])) { |
6f1bfb6d | 499 | $contributionParams = ['id' => $values['contribution_id']]; |
500 | $returnProperties = ['contribution_status_id', 'receive_date']; | |
6a488035 TO |
501 | CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_Contribution', |
502 | $contributionParams, $contributionStatus, $returnProperties | |
503 | ); | |
6f1bfb6d | 504 | $contributionValue = [ |
6b409353 CW |
505 | 'status' => $contributionStatus['contribution_status_id'] ?? NULL, |
506 | 'receive_date' => $contributionStatus['receive_date'] ?? NULL, | |
6f1bfb6d | 507 | ]; |
6a488035 TO |
508 | } |
509 | $payments[$payID] = array_merge($contributionValue, | |
6f1bfb6d | 510 | [ |
6b409353 CW |
511 | 'amount' => $values['scheduled_amount'] ?? NULL, |
512 | 'due_date' => $values['scheduled_date'] ?? NULL, | |
d1c42570 | 513 | 'status' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'), |
6f1bfb6d | 514 | ] |
6a488035 TO |
515 | ); |
516 | ||
cc28438b | 517 | // get the first valid payment id. |
6a488035 TO |
518 | if (!isset($form->paymentId) && ($paymentStatusTypes[$values['status_id']] == 'Pending' || |
519 | $paymentStatusTypes[$values['status_id']] == 'Overdue' | |
353ffa53 TO |
520 | ) |
521 | ) { | |
6a488035 TO |
522 | $form->paymentId = $values['id']; |
523 | } | |
524 | } | |
525 | } | |
6a488035 | 526 | |
cc28438b | 527 | // assign pledge fields value to template. |
6f1bfb6d | 528 | $pledgeFields = [ |
353ffa53 TO |
529 | 'create_date', |
530 | 'total_pledge_amount', | |
531 | 'frequency_interval', | |
532 | 'frequency_unit', | |
533 | 'installments', | |
534 | 'frequency_day', | |
535 | 'scheduled_amount', | |
536 | 'currency', | |
6f1bfb6d | 537 | ]; |
6a488035 | 538 | foreach ($pledgeFields as $field) { |
a7488080 | 539 | if (!empty($params[$field])) { |
6a488035 TO |
540 | $form->assign($field, $params[$field]); |
541 | } | |
542 | } | |
543 | ||
cc28438b | 544 | // assign all payments details. |
6a488035 TO |
545 | if ($payments) { |
546 | $form->assign('payments', $payments); | |
547 | } | |
548 | ||
cc28438b | 549 | // handle custom data. |
d1c42570 | 550 | $customGroup = []; |
a7488080 | 551 | if (!empty($params['hidden_custom'])) { |
0b330e6d | 552 | $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', NULL, $params['id']); |
6f1bfb6d | 553 | $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]]; |
6a488035 TO |
554 | // retrieve custom data |
555 | foreach ($groupTree as $groupID => $group) { | |
affcc9d2 | 556 | $customFields = $customValues = []; |
6a488035 TO |
557 | if ($groupID == 'info') { |
558 | continue; | |
559 | } | |
560 | foreach ($group['fields'] as $k => $field) { | |
561 | $field['title'] = $field['label']; | |
562 | $customFields["custom_{$k}"] = $field; | |
563 | } | |
564 | ||
cc28438b | 565 | // to build array of customgroup & customfields in it |
6a488035 TO |
566 | CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams); |
567 | $customGroup[$group['title']] = $customValues; | |
568 | } | |
569 | ||
6a488035 | 570 | } |
d1c42570 | 571 | $form->assign('customGroup', $customGroup); |
6a488035 | 572 | |
cc28438b | 573 | // handle acknowledgment email stuff. |
6f1bfb6d | 574 | [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']); |
6a488035 | 575 | |
cc28438b | 576 | // check for online pledge. |
a7488080 | 577 | if (!empty($params['receipt_from_email'])) { |
9c1bc317 CW |
578 | $userName = $params['receipt_from_name'] ?? NULL; |
579 | $userEmail = $params['receipt_from_email'] ?? NULL; | |
6a488035 | 580 | } |
a7488080 | 581 | elseif (!empty($params['from_email_id'])) { |
6a488035 TO |
582 | $receiptFrom = $params['from_email_id']; |
583 | } | |
bb06e9ed | 584 | elseif ($userID = CRM_Core_Session::singleton()->get('userID')) { |
cc28438b | 585 | // check for logged in user. |
6f1bfb6d | 586 | [ |
587 | $userName, | |
588 | $userEmail, | |
589 | ] = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); | |
6a488035 TO |
590 | } |
591 | else { | |
cc28438b | 592 | // set the domain values. |
aa7dd30f | 593 | [$userName, $userEmail] = CRM_Core_BAO_Domain::getNameAndEmail(); |
6a488035 TO |
594 | } |
595 | ||
596 | if (!isset($receiptFrom)) { | |
597 | $receiptFrom = "$userName <$userEmail>"; | |
598 | } | |
599 | ||
6f1bfb6d | 600 | [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate::sendTemplate( |
601 | [ | |
6a488035 TO |
602 | 'groupName' => 'msg_tpl_workflow_pledge', |
603 | 'valueName' => 'pledge_acknowledge', | |
604 | 'contactId' => $params['contact_id'], | |
605 | 'from' => $receiptFrom, | |
606 | 'toName' => $pledgerDisplayName, | |
607 | 'toEmail' => $pledgerEmail, | |
6f1bfb6d | 608 | ] |
6a488035 TO |
609 | ); |
610 | ||
cc28438b SB |
611 | // check if activity record exist for this pledge |
612 | // Acknowledgment, if exist do not add activity. | |
6a488035 TO |
613 | $activityType = 'Pledge Acknowledgment'; |
614 | $activity = new CRM_Activity_DAO_Activity(); | |
615 | $activity->source_record_id = $params['id']; | |
363b8345 PN |
616 | $activity->activity_type_id = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', |
617 | 'activity_type_id', | |
618 | $activityType | |
6a488035 | 619 | ); |
6a488035 | 620 | |
6c68db9f | 621 | // FIXME: Translate |
6a488035 TO |
622 | $details = 'Total Amount ' . CRM_Utils_Money::format($params['total_pledge_amount'], CRM_Utils_Array::value('currency', $params)) . ' To be paid in ' . $params['installments'] . ' installments of ' . CRM_Utils_Money::format($params['scheduled_amount'], CRM_Utils_Array::value('currency', $params)) . ' every ' . $params['frequency_interval'] . ' ' . $params['frequency_unit'] . '(s)'; |
623 | ||
624 | if (!$activity->find()) { | |
6f1bfb6d | 625 | $activityParams = [ |
6a488035 TO |
626 | 'subject' => $subject, |
627 | 'source_contact_id' => $params['contact_id'], | |
628 | 'source_record_id' => $params['id'], | |
363b8345 PN |
629 | 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', |
630 | 'activity_type_id', | |
631 | $activityType | |
6a488035 TO |
632 | ), |
633 | 'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']), | |
634 | 'is_test' => $params['is_test'], | |
635 | 'status_id' => 2, | |
636 | 'details' => $details, | |
6b409353 | 637 | 'campaign_id' => $params['campaign_id'] ?? NULL, |
6f1bfb6d | 638 | ]; |
6a488035 | 639 | |
cc28438b | 640 | // lets insert assignee record. |
a7488080 | 641 | if (!empty($params['contact_id'])) { |
6a488035 TO |
642 | $activityParams['assignee_contact_id'] = $params['contact_id']; |
643 | } | |
644 | ||
645 | if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) { | |
ba968e38 | 646 | throw new CRM_Core_Exception('Failed creating Activity for acknowledgment'); |
6a488035 TO |
647 | } |
648 | } | |
649 | } | |
650 | ||
651 | /** | |
fe482240 | 652 | * Combine all the exportable fields from the lower levels object. |
6a488035 | 653 | * |
e9ff5391 | 654 | * @param bool $checkPermission |
655 | * | |
a6c01b45 CW |
656 | * @return array |
657 | * array of exportable Fields | |
6a488035 | 658 | */ |
b3460c23 | 659 | public static function exportableFields($checkPermission = TRUE) { |
6a488035 TO |
660 | if (!self::$_exportableFields) { |
661 | if (!self::$_exportableFields) { | |
affcc9d2 | 662 | self::$_exportableFields = []; |
6a488035 TO |
663 | } |
664 | ||
665 | $fields = CRM_Pledge_DAO_Pledge::export(); | |
666 | ||
6a488035 TO |
667 | $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment::export()); |
668 | ||
cc28438b | 669 | // set title to calculated fields |
6f1bfb6d | 670 | $calculatedFields = [ |
671 | 'pledge_total_paid' => ['title' => ts('Total Paid')], | |
672 | 'pledge_balance_amount' => ['title' => ts('Balance Amount')], | |
673 | 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')], | |
674 | 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')], | |
675 | 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')], | |
676 | 'pledge_payment_paid_date' => ['title' => ts('Paid Date')], | |
677 | 'pledge_payment_status' => [ | |
353ffa53 | 678 | 'title' => ts('Pledge Payment Status'), |
6a488035 TO |
679 | 'name' => 'pledge_payment_status', |
680 | 'data_type' => CRM_Utils_Type::T_STRING, | |
6f1bfb6d | 681 | ], |
682 | ]; | |
6a488035 | 683 | |
6f1bfb6d | 684 | $pledgeFields = [ |
685 | 'pledge_status' => [ | |
e300cf31 | 686 | 'title' => ts('Pledge Status'), |
6a488035 TO |
687 | 'name' => 'pledge_status', |
688 | 'data_type' => CRM_Utils_Type::T_STRING, | |
6f1bfb6d | 689 | ], |
690 | 'pledge_frequency_unit' => [ | |
e300cf31 | 691 | 'title' => ts('Pledge Frequency Unit'), |
6a488035 TO |
692 | 'name' => 'pledge_frequency_unit', |
693 | 'data_type' => CRM_Utils_Type::T_ENUM, | |
6f1bfb6d | 694 | ], |
695 | 'pledge_frequency_interval' => [ | |
e300cf31 | 696 | 'title' => ts('Pledge Frequency Interval'), |
6a488035 TO |
697 | 'name' => 'pledge_frequency_interval', |
698 | 'data_type' => CRM_Utils_Type::T_INT, | |
6f1bfb6d | 699 | ], |
700 | 'pledge_contribution_page_id' => [ | |
e300cf31 | 701 | 'title' => ts('Pledge Contribution Page Id'), |
6a488035 TO |
702 | 'name' => 'pledge_contribution_page_id', |
703 | 'data_type' => CRM_Utils_Type::T_INT, | |
6f1bfb6d | 704 | ], |
705 | ]; | |
6a488035 TO |
706 | |
707 | $fields = array_merge($fields, $pledgeFields, $calculatedFields); | |
708 | ||
709 | // add custom data | |
e9ff5391 | 710 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission)); |
6a488035 TO |
711 | self::$_exportableFields = $fields; |
712 | } | |
713 | ||
714 | return self::$_exportableFields; | |
715 | } | |
716 | ||
717 | /** | |
fe482240 | 718 | * Get pending or in progress pledges. |
6a488035 | 719 | * |
3a1617b6 TO |
720 | * @param int $contactID |
721 | * Contact id. | |
6a488035 | 722 | * |
a6c01b45 CW |
723 | * @return array |
724 | * associated array of pledge id(s) | |
6a488035 | 725 | */ |
00be9182 | 726 | public static function getContactPledges($contactID) { |
affcc9d2 | 727 | $pledgeDetails = []; |
01dac399 JP |
728 | $pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status', |
729 | FALSE, FALSE, FALSE, NULL, 'name' | |
730 | ); | |
6a488035 | 731 | |
affcc9d2 | 732 | $status = []; |
6a488035 | 733 | |
cc28438b | 734 | // get pending and in progress status |
6f1bfb6d | 735 | foreach (['Pending', 'In Progress', 'Overdue'] as $name) { |
6a488035 TO |
736 | if ($statusId = array_search($name, $pledgeStatuses)) { |
737 | $status[] = $statusId; | |
738 | } | |
739 | } | |
740 | if (empty($status)) { | |
741 | return $pledgeDetails; | |
742 | } | |
743 | ||
744 | $statusClause = " IN (" . implode(',', $status) . ")"; | |
745 | ||
746 | $query = " | |
747 | SELECT civicrm_pledge.id id | |
748 | FROM civicrm_pledge | |
749 | WHERE civicrm_pledge.status_id {$statusClause} | |
750 | AND civicrm_pledge.contact_id = %1 | |
751 | "; | |
752 | ||
6f1bfb6d | 753 | $params[1] = [$contactID, 'Integer']; |
6a488035 TO |
754 | $pledge = CRM_Core_DAO::executeQuery($query, $params); |
755 | ||
756 | while ($pledge->fetch()) { | |
757 | $pledgeDetails[] = $pledge->id; | |
758 | } | |
759 | ||
760 | return $pledgeDetails; | |
761 | } | |
762 | ||
763 | /** | |
fe482240 | 764 | * Get pledge record count for a Contact. |
6a488035 | 765 | * |
100fef9d | 766 | * @param int $contactID |
2a6da8d7 | 767 | * |
a6c01b45 CW |
768 | * @return int |
769 | * count of pledge records | |
6a488035 | 770 | */ |
00be9182 | 771 | public static function getContactPledgeCount($contactID) { |
6a488035 TO |
772 | $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0"; |
773 | return CRM_Core_DAO::singleValueQuery($query); | |
774 | } | |
775 | ||
ffd93213 | 776 | /** |
c490a46a | 777 | * @param array $params |
ffd93213 EM |
778 | * |
779 | * @return array | |
21585345 EM |
780 | * @throws \API_Exception |
781 | * @throws \CRM_Core_Exception | |
782 | * @throws \CiviCRM_API3_Exception | |
ffd93213 | 783 | */ |
21585345 | 784 | public static function updatePledgeStatus($params): array { |
6a488035 | 785 | |
affcc9d2 | 786 | $returnMessages = []; |
6a488035 TO |
787 | |
788 | $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE); | |
789 | ||
e7212d86 JP |
790 | $allStatus = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')); |
791 | $allPledgeStatus = CRM_Core_OptionGroup::values('pledge_status', | |
792 | TRUE, FALSE, FALSE, NULL, 'name', TRUE | |
793 | ); | |
794 | unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']); | |
795 | unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']); | |
6a488035 | 796 | |
e7212d86 JP |
797 | $statusIds = implode(',', $allStatus); |
798 | $pledgeStatusIds = implode(',', $allPledgeStatus); | |
6a488035 TO |
799 | $updateCnt = 0; |
800 | ||
801 | $query = " | |
802 | SELECT pledge.contact_id as contact_id, | |
803 | pledge.id as pledge_id, | |
804 | pledge.amount as amount, | |
805 | payment.scheduled_date as scheduled_date, | |
806 | pledge.create_date as create_date, | |
807 | payment.id as payment_id, | |
808 | pledge.currency as currency, | |
809 | pledge.contribution_page_id as contribution_page_id, | |
810 | payment.reminder_count as reminder_count, | |
811 | pledge.max_reminders as max_reminders, | |
812 | payment.reminder_date as reminder_date, | |
813 | pledge.initial_reminder_day as initial_reminder_day, | |
814 | pledge.additional_reminder_day as additional_reminder_day, | |
815 | pledge.status_id as pledge_status, | |
816 | payment.status_id as payment_status, | |
817 | pledge.is_test as is_test, | |
818 | pledge.campaign_id as campaign_id, | |
819 | SUM(payment.scheduled_amount) as amount_due, | |
820 | ( SELECT sum(civicrm_pledge_payment.actual_amount) | |
821 | FROM civicrm_pledge_payment | |
822 | WHERE civicrm_pledge_payment.status_id = 1 | |
823 | AND civicrm_pledge_payment.pledge_id = pledge.id | |
824 | ) as amount_paid | |
825 | FROM civicrm_pledge pledge, civicrm_pledge_payment payment | |
826 | WHERE pledge.id = payment.pledge_id | |
e7212d86 | 827 | AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} ) |
6a488035 TO |
828 | GROUP By payment.id |
829 | "; | |
830 | ||
831 | $dao = CRM_Core_DAO::executeQuery($query); | |
832 | ||
833 | $now = date('Ymd'); | |
affcc9d2 | 834 | $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = []; |
6a488035 TO |
835 | while ($dao->fetch()) { |
836 | $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id); | |
837 | ||
6f1bfb6d | 838 | $pledgeDetails[$dao->payment_id] = [ |
6a488035 TO |
839 | 'scheduled_date' => $dao->scheduled_date, |
840 | 'amount_due' => $dao->amount_due, | |
841 | 'amount' => $dao->amount, | |
842 | 'amount_paid' => $dao->amount_paid, | |
843 | 'create_date' => $dao->create_date, | |
844 | 'contact_id' => $dao->contact_id, | |
845 | 'pledge_id' => $dao->pledge_id, | |
846 | 'checksumValue' => $checksumValue, | |
847 | 'contribution_page_id' => $dao->contribution_page_id, | |
848 | 'reminder_count' => $dao->reminder_count, | |
849 | 'max_reminders' => $dao->max_reminders, | |
850 | 'reminder_date' => $dao->reminder_date, | |
851 | 'initial_reminder_day' => $dao->initial_reminder_day, | |
852 | 'additional_reminder_day' => $dao->additional_reminder_day, | |
853 | 'pledge_status' => $dao->pledge_status, | |
854 | 'payment_status' => $dao->payment_status, | |
855 | 'is_test' => $dao->is_test, | |
856 | 'currency' => $dao->currency, | |
857 | 'campaign_id' => $dao->campaign_id, | |
6f1bfb6d | 858 | ]; |
6a488035 TO |
859 | |
860 | $contactIds[$dao->contact_id] = $dao->contact_id; | |
861 | $pledgeStatus[$dao->pledge_id] = $dao->pledge_status; | |
862 | ||
863 | if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'), | |
864 | $now | |
e7212d86 | 865 | ) && $dao->payment_status != $allStatus['Overdue'] |
353ffa53 | 866 | ) { |
6a488035 TO |
867 | $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id; |
868 | } | |
869 | } | |
e7212d86 | 870 | $allPledgeStatus = array_flip($allPledgeStatus); |
6a488035 TO |
871 | |
872 | // process the updating script... | |
6a488035 TO |
873 | foreach ($pledgePayments as $pledgeId => $paymentIds) { |
874 | // 1. update the pledge /pledge payment status. returns new status when an update happens | |
e7212d86 | 875 | $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})"; |
6a488035 TO |
876 | |
877 | $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds, | |
e7212d86 | 878 | $allStatus['Overdue'], NULL, 0, FALSE, TRUE |
6a488035 TO |
879 | ); |
880 | if ($newStatus != $pledgeStatus[$pledgeId]) { | |
e7212d86 | 881 | $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}"; |
6a488035 TO |
882 | $updateCnt += 1; |
883 | } | |
884 | } | |
885 | ||
886 | if ($sendReminders) { | |
887 | // retrieve domain tokens | |
6f1bfb6d | 888 | $tokens = [ |
889 | 'domain' => ['name', 'phone', 'address', 'email'], | |
6a488035 | 890 | 'contact' => CRM_Core_SelectValues::contactTokens(), |
6f1bfb6d | 891 | ]; |
6a488035 | 892 | |
6a488035 TO |
893 | // retrieve contact tokens |
894 | ||
895 | // this function does NOT return Deceased contacts since we don't want to send them email | |
21585345 EM |
896 | $contactDetails = civicrm_api3('Contact', 'get', [ |
897 | 'is_deceased' => 0, | |
898 | 'id' => ['IN' => $contactIds], | |
899 | 'return' => ['id', 'display_name', 'email', 'do_not_email', 'email', 'on_hold'], | |
900 | ])['values']; | |
6a488035 TO |
901 | |
902 | // assign domain values to template | |
903 | $template = CRM_Core_Smarty::singleton(); | |
6a488035 | 904 | |
cc28438b | 905 | // set receipt from |
21585345 EM |
906 | $receiptFrom = CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE); |
907 | $receiptFrom = reset($receiptFrom); | |
6a488035 TO |
908 | |
909 | foreach ($pledgeDetails as $paymentId => $details) { | |
910 | if (array_key_exists($details['contact_id'], $contactDetails)) { | |
911 | $contactId = $details['contact_id']; | |
912 | $pledgerName = $contactDetails[$contactId]['display_name']; | |
913 | } | |
914 | else { | |
915 | continue; | |
916 | } | |
917 | ||
918 | if (empty($details['reminder_date'])) { | |
919 | $nextReminderDate = new DateTime($details['scheduled_date']); | |
64b4078f | 920 | $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ? 0 : $details['initial_reminder_day']; |
6a488035 TO |
921 | $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day"); |
922 | $nextReminderDate = $nextReminderDate->format("Ymd"); | |
923 | } | |
924 | else { | |
925 | $nextReminderDate = new DateTime($details['reminder_date']); | |
64b4078f | 926 | $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ? 0 : $details['additional_reminder_day']; |
6a488035 TO |
927 | $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day"); |
928 | $nextReminderDate = $nextReminderDate->format("Ymd"); | |
929 | } | |
930 | if (($details['reminder_count'] < $details['max_reminders']) | |
931 | && ($nextReminderDate <= $now) | |
932 | ) { | |
933 | ||
934 | $toEmail = $doNotEmail = $onHold = NULL; | |
935 | ||
936 | if (!empty($contactDetails[$contactId]['email'])) { | |
937 | $toEmail = $contactDetails[$contactId]['email']; | |
938 | } | |
939 | ||
940 | if (!empty($contactDetails[$contactId]['do_not_email'])) { | |
941 | $doNotEmail = $contactDetails[$contactId]['do_not_email']; | |
942 | } | |
943 | ||
944 | if (!empty($contactDetails[$contactId]['on_hold'])) { | |
945 | $onHold = $contactDetails[$contactId]['on_hold']; | |
946 | } | |
947 | ||
948 | // 2. send acknowledgement mail | |
949 | if ($toEmail && !($doNotEmail || $onHold)) { | |
cc28438b | 950 | // assign value to template |
6a488035 | 951 | $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0); |
6a488035 TO |
952 | $template->assign('next_payment', $details['scheduled_date']); |
953 | $template->assign('amount_due', $details['amount_due']); | |
954 | $template->assign('checksumValue', $details['checksumValue']); | |
955 | $template->assign('contribution_page_id', $details['contribution_page_id']); | |
956 | $template->assign('pledge_id', $details['pledge_id']); | |
957 | $template->assign('scheduled_payment_date', $details['scheduled_date']); | |
958 | $template->assign('amount', $details['amount']); | |
959 | $template->assign('create_date', $details['create_date']); | |
960 | $template->assign('currency', $details['currency']); | |
6f1bfb6d | 961 | [ |
962 | $mailSent, | |
963 | $subject, | |
964 | $message, | |
965 | $html, | |
966 | ] = CRM_Core_BAO_MessageTemplate::sendTemplate( | |
967 | [ | |
6a488035 TO |
968 | 'groupName' => 'msg_tpl_workflow_pledge', |
969 | 'valueName' => 'pledge_reminder', | |
970 | 'contactId' => $contactId, | |
971 | 'from' => $receiptFrom, | |
972 | 'toName' => $pledgerName, | |
973 | 'toEmail' => $toEmail, | |
6f1bfb6d | 974 | ] |
6a488035 TO |
975 | ); |
976 | ||
977 | // 3. update pledge payment details | |
978 | if ($mailSent) { | |
979 | CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId); | |
980 | $activityType = 'Pledge Reminder'; | |
6f1bfb6d | 981 | $activityParams = [ |
6a488035 TO |
982 | 'subject' => $subject, |
983 | 'source_contact_id' => $contactId, | |
984 | 'source_record_id' => $paymentId, | |
985 | 'assignee_contact_id' => $contactId, | |
363b8345 PN |
986 | 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', |
987 | 'activity_type_id', | |
988 | $activityType | |
6a488035 | 989 | ), |
6a488035 TO |
990 | 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']), |
991 | 'is_test' => $details['is_test'], | |
992 | 'status_id' => 2, | |
993 | 'campaign_id' => $details['campaign_id'], | |
6f1bfb6d | 994 | ]; |
c06e1e95 MW |
995 | try { |
996 | civicrm_api3('activity', 'create', $activityParams); | |
997 | } | |
998 | catch (CiviCRM_API3_Exception $e) { | |
999 | $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage(); | |
6f1bfb6d | 1000 | return ['is_error' => 1, 'message' => $returnMessages]; |
6a488035 TO |
1001 | } |
1002 | $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}"; | |
1003 | } | |
1004 | } | |
1005 | } | |
1006 | } | |
1007 | // end foreach on $pledgeDetails | |
1008 | } | |
1009 | // end if ( $sendReminders ) | |
1010 | $returnMessages[] = "{$updateCnt} records updated."; | |
1011 | ||
6f1bfb6d | 1012 | return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)]; |
6a488035 TO |
1013 | } |
1014 | ||
1015 | /** | |
1016 | * Mark a pledge (and any outstanding payments) as cancelled. | |
1017 | * | |
1018 | * @param int $pledgeID | |
1019 | */ | |
1020 | public static function cancel($pledgeID) { | |
6a488035 | 1021 | $paymentIDs = self::findCancelablePayments($pledgeID); |
10874ecc | 1022 | $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
1023 | $cancelled = array_search('Cancelled', $status); | |
6a488035 | 1024 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL, |
10874ecc | 1025 | $cancelled, 0, FALSE, TRUE |
6a488035 TO |
1026 | ); |
1027 | } | |
1028 | ||
1029 | /** | |
1030 | * Find payments which can be safely canceled. | |
1031 | * | |
1032 | * @param int $pledgeID | |
6f1bfb6d | 1033 | * |
a6c01b45 | 1034 | * @return array |
16b10e64 | 1035 | * Array of int (civicrm_pledge_payment.id) |
6a488035 TO |
1036 | */ |
1037 | public static function findCancelablePayments($pledgeID) { | |
c3b82060 | 1038 | $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label')); |
6a488035 TO |
1039 | |
1040 | $paymentDAO = new CRM_Pledge_DAO_PledgePayment(); | |
1041 | $paymentDAO->pledge_id = $pledgeID; | |
1042 | $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)", | |
1043 | $statuses['Overdue'], | |
1044 | $statuses['Pending'] | |
1045 | )); | |
1046 | $paymentDAO->find(); | |
1047 | ||
affcc9d2 | 1048 | $paymentIDs = []; |
6a488035 TO |
1049 | while ($paymentDAO->fetch()) { |
1050 | $paymentIDs[] = $paymentDAO->id; | |
1051 | } | |
1052 | return $paymentIDs; | |
1053 | } | |
edb4c74d E |
1054 | |
1055 | /** | |
6f1bfb6d | 1056 | * Is this pledge free from financial transactions (this is important to know |
1057 | * as we allow editing when no transactions have taken place - the editing | |
1058 | * process currently involves deleting all pledge payments & contributions | |
cc28438b | 1059 | * & recreating so we want to block that if appropriate). |
edb4c74d | 1060 | * |
3a1617b6 TO |
1061 | * @param int $pledgeID |
1062 | * @param int $pledgeStatusID | |
6f1bfb6d | 1063 | * |
a6c01b45 CW |
1064 | * @return bool |
1065 | * do financial transactions exist for this pledge? | |
edb4c74d | 1066 | */ |
098201d8 | 1067 | public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) { |
edb4c74d | 1068 | if (empty($pledgeStatusID)) { |
cc28438b SB |
1069 | // why would this happen? If we can see where it does then we can see if we should look it up. |
1070 | // but assuming from form code it CAN be empty. | |
edb4c74d E |
1071 | return TRUE; |
1072 | } | |
1073 | if (self::isTransactedStatus($pledgeStatusID)) { | |
1074 | return TRUE; | |
1075 | } | |
1076 | ||
6f1bfb6d | 1077 | return civicrm_api3('pledge_payment', 'getcount', [ |
e2a918bf | 1078 | 'pledge_id' => $pledgeID, |
6f1bfb6d | 1079 | 'contribution_id' => ['IS NOT NULL' => TRUE], |
1080 | ]); | |
098201d8 | 1081 | } |
edb4c74d E |
1082 | |
1083 | /** | |
6f1bfb6d | 1084 | * Does this pledge / pledge payment status mean that a financial transaction |
1085 | * has taken place? | |
1086 | * | |
3a1617b6 TO |
1087 | * @param int $statusID |
1088 | * Pledge status id. | |
edb4c74d | 1089 | * |
a6c01b45 CW |
1090 | * @return bool |
1091 | * is it a transactional status? | |
edb4c74d E |
1092 | */ |
1093 | protected static function isTransactedStatus($statusID) { | |
1094 | if (!in_array($statusID, self::getNonTransactionalStatus())) { | |
1095 | return TRUE; | |
1096 | } | |
b55cf2b2 | 1097 | return FALSE; |
edb4c74d E |
1098 | } |
1099 | ||
1100 | /** | |
fe482240 | 1101 | * Get array of non transactional statuses. |
6f1bfb6d | 1102 | * |
a6c01b45 CW |
1103 | * @return array |
1104 | * non transactional status ids | |
edb4c74d E |
1105 | */ |
1106 | protected static function getNonTransactionalStatus() { | |
1107 | $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
6f1bfb6d | 1108 | return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending'])); |
edb4c74d E |
1109 | } |
1110 | ||
dccd9f4f ERL |
1111 | /** |
1112 | * Create array for recur record for pledge. | |
6f1bfb6d | 1113 | * |
dccd9f4f ERL |
1114 | * @return array |
1115 | * params for recur record | |
1116 | */ | |
1117 | public static function buildRecurParams($params) { | |
6f1bfb6d | 1118 | $recurParams = [ |
dccd9f4f ERL |
1119 | 'is_recur' => TRUE, |
1120 | 'auto_renew' => TRUE, | |
1121 | 'frequency_unit' => $params['pledge_frequency_unit'], | |
1122 | 'frequency_interval' => $params['pledge_frequency_interval'], | |
1123 | 'installments' => $params['pledge_installments'], | |
1124 | 'start_date' => $params['receive_date'], | |
6f1bfb6d | 1125 | ]; |
dccd9f4f ERL |
1126 | return $recurParams; |
1127 | } | |
1128 | ||
1129 | /** | |
1130 | * Get pledge start date. | |
1131 | * | |
1132 | * @return string | |
1133 | * start date | |
1134 | */ | |
1135 | public static function getPledgeStartDate($date, $pledgeBlock) { | |
1136 | $startDate = (array) json_decode($pledgeBlock['pledge_start_date']); | |
9de112cd | 1137 | foreach ($startDate as $field => $value) { |
de6c59ca | 1138 | if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) { |
9de112cd SL |
1139 | return $date; |
1140 | } | |
1141 | if (empty($date)) { | |
1142 | $date = $value; | |
1143 | } | |
1144 | switch ($field) { | |
1145 | case 'contribution_date': | |
1146 | if (empty($date)) { | |
1147 | $date = date('Ymd'); | |
1148 | } | |
1149 | break; | |
dccd9f4f | 1150 | |
9de112cd SL |
1151 | case 'calendar_date': |
1152 | $date = date('Ymd', strtotime($date)); | |
1153 | break; | |
dccd9f4f | 1154 | |
9de112cd SL |
1155 | case 'calendar_month': |
1156 | $date = self::getPaymentDate($date); | |
1157 | $date = date('Ymd', strtotime($date)); | |
1158 | break; | |
dccd9f4f | 1159 | |
9de112cd SL |
1160 | default: |
1161 | break; | |
dccd9f4f | 1162 | |
9de112cd | 1163 | } |
dccd9f4f ERL |
1164 | } |
1165 | return $date; | |
1166 | } | |
1167 | ||
1168 | /** | |
1169 | * Get first payment date for pledge. | |
1170 | * | |
bf48aa29 | 1171 | * @param int $day |
1172 | * | |
1173 | * @return bool|string | |
dccd9f4f ERL |
1174 | */ |
1175 | public static function getPaymentDate($day) { | |
1176 | if ($day == 31) { | |
1177 | // Find out if current month has 31 days, if not, set it to 30 (last day). | |
1178 | $t = date('t'); | |
1179 | if ($t != $day) { | |
1180 | $day = $t; | |
1181 | } | |
1182 | } | |
1183 | $current = date('d'); | |
1184 | switch (TRUE) { | |
1185 | case ($day == $current): | |
1186 | $date = date('m/d/Y'); | |
1187 | break; | |
1188 | ||
1189 | case ($day > $current): | |
1190 | $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y'))); | |
1191 | break; | |
1192 | ||
1193 | case ($day < $current): | |
1194 | $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y'))); | |
1195 | break; | |
1196 | ||
1197 | default: | |
1198 | break; | |
1199 | ||
1200 | } | |
1201 | return $date; | |
1202 | } | |
1203 | ||
ab6ba136 | 1204 | /** |
1205 | * Override buildOptions to hack out some statuses. | |
1206 | * | |
ab6ba136 | 1207 | * @param string $fieldName |
1208 | * @param string $context | |
1209 | * @param array $props | |
1210 | * | |
1211 | * @return array|bool | |
6f1bfb6d | 1212 | * @todo instead of using & hacking the shared optionGroup |
1213 | * contribution_status use a separate one. | |
1214 | * | |
ab6ba136 | 1215 | */ |
affcc9d2 | 1216 | public static function buildOptions($fieldName, $context = NULL, $props = []) { |
ab6ba136 | 1217 | $result = parent::buildOptions($fieldName, $context, $props); |
1218 | if ($fieldName == 'status_id') { | |
6f1bfb6d | 1219 | $result = array_diff($result, ['Failed']); |
ab6ba136 | 1220 | } |
1221 | return $result; | |
1222 | } | |
1223 | ||
6a488035 | 1224 | } |