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