Merge branch 4.5 into master
[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 public static function deletePledge($id) {
268 CRM_Utils_Hook::pre('delete', 'Pledge', $id, CRM_Core_DAO::$_nullArray);
269
270 $transaction = new CRM_Core_Transaction();
271
272 //check for no Completed Payment records with the pledge
273 $payment = new CRM_Pledge_DAO_PledgePayment();
274 $payment->pledge_id = $id;
275 $payment->find();
276
277 while ($payment->fetch()) {
278 //also delete associated contribution.
279 if ($payment->contribution_id) {
280 CRM_Contribute_BAO_Contribution::deleteContribution($payment->contribution_id);
281 }
282 $payment->delete();
283 }
284
285 $dao = new CRM_Pledge_DAO_Pledge();
286 $dao->id = $id;
287 $results = $dao->delete();
288
289 $transaction->commit();
290
291 CRM_Utils_Hook::post('delete', 'Pledge', $dao->id, $dao);
292
293 // delete the recently created Pledge
294 $pledgeRecent = array(
295 'id' => $id,
296 'type' => 'Pledge',
297 );
298 CRM_Utils_Recent::del($pledgeRecent);
299
300 return $results;
301 }
302
303 /**
304 * Get the amount details date wise.
305 *
306 * @param string $status
307 * @param string $startDate
308 * @param string $endDate
309 *
310 * @return array|null
311 */
312 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
313 $where = array();
314 $select = $from = $queryDate = NULL;
315 //get all status
316 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
317 $statusId = array_search($status, $allStatus);
318
319 switch ($status) {
320 case 'Completed':
321 $statusId = array_search('Cancelled', $allStatus);
322 $where[] = 'status_id != ' . $statusId;
323 break;
324
325 case 'Cancelled':
326 $where[] = 'status_id = ' . $statusId;
327 break;
328
329 case 'In Progress':
330 $where[] = 'status_id = ' . $statusId;
331 break;
332
333 case 'Pending':
334 $where[] = 'status_id = ' . $statusId;
335 break;
336
337 case 'Overdue':
338 $where[] = 'status_id = ' . $statusId;
339 break;
340 }
341
342 if ($startDate) {
343 $where[] = "create_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
344 }
345 if ($endDate) {
346 $where[] = "create_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
347 }
348
349 $whereCond = implode(' AND ', $where);
350
351 $query = "
352 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
353 FROM civicrm_pledge
354 WHERE $whereCond AND is_test=0
355 GROUP BY currency
356 ";
357 $start = substr($startDate, 0, 8);
358 $end = substr($endDate, 0, 8);
359 $pCount = 0;
360 $pamount = array();
361 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
362 while ($dao->fetch()) {
363 $pCount += $dao->pledge_count;
364 $pamount[] = CRM_Utils_Money::format($dao->pledge_amount, $dao->currency);
365 }
366
367 $pledge_amount = array(
368 'pledge_amount' => implode(', ', $pamount),
369 'pledge_count' => $pCount,
370 'purl' => CRM_Utils_System::url('civicrm/pledge/search',
371 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
372 ),
373 );
374
375 $where = array();
376 $statusId = array_search($status, $allStatus);
377 switch ($status) {
378 case 'Completed':
379 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
380 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
381 $queryDate = 'receive_date';
382 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
383 break;
384
385 case 'Cancelled':
386 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
387 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
388 $queryDate = 'receive_date';
389 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
390 break;
391
392 case 'Pending':
393 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
394 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
395 $queryDate = 'scheduled_date';
396 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
397 break;
398
399 case 'Overdue':
400 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
401 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
402 $queryDate = 'scheduled_date';
403 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
404 break;
405 }
406
407 if ($startDate) {
408 $where[] = " $queryDate >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
409 }
410 if ($endDate) {
411 $where[] = " $queryDate <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
412 }
413
414 $whereCond = implode(' AND ', $where);
415
416 $query = "
417 SELECT $select, cp.currency
418 FROM $from
419 WHERE $whereCond
420 GROUP BY cp.currency
421 ";
422 if ($select) {
423 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
424 $amount = array();
425 $count = 0;
426
427 while ($dao->fetch()) {
428 $count += $dao->received_count;
429 $amount[] = CRM_Utils_Money::format($dao->received_pledge, $dao->currency);
430 }
431
432 if ($count) {
433 return array_merge($pledge_amount, array(
434 'received_amount' => implode(', ', $amount),
435 'received_count' => $count,
436 'url' => CRM_Utils_System::url('civicrm/pledge/search',
437 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
438 ),
439 ));
440 }
441 }
442 else {
443 return $pledge_amount;
444 }
445 return NULL;
446 }
447
448 /**
449 * Get list of pledges In Honor of contact Ids
450 *
451 * @param int $honorId
452 * In Honor of Contact ID.
453 *
454 * @return array
455 * return the list of pledge fields
456 *
457 * @static
458 */
459 public static function getHonorContacts($honorId) {
460 $params = array();
461 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
462 $honorDAO->contact_id = $honorId;
463 $honorDAO->find();
464
465 //get all status.
466 while ($honorDAO->fetch()) {
467 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
468 $pledgePaymentDAO->contribution_id = $honorDAO->contribution_id;
469 if ($pledgePaymentDAO->find(TRUE)) {
470 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
471 $pledgeDAO->id = $pledgePaymentDAO->pledge_id;
472 if ($pledgeDAO->find(TRUE)) {
473 $params[$pledgeDAO->id] = array(
474 'honor_type' => CRM_Core_OptionGroup::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id, 'value'),
475 'honorId' => $pledgeDAO->contact_id,
476 'amount' => $pledgeDAO->amount,
477 'status' => CRM_Contribute_PseudoConstant::contributionStatus($pledgeDAO->status_id),
478 'create_date' => $pledgeDAO->create_date,
479 'acknowledge_date' => $pledgeDAO->acknowledge_date,
480 'type' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
481 $pledgeDAO->financial_type_id, 'name'
482 ),
483 'display_name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
484 $pledgeDAO->contact_id, 'display_name'
485 ),
486 );
487 }
488 }
489 }
490
491 return $params;
492 }
493
494 /**
495 * Send Acknowledgment and create activity.
496 *
497 * @param CRM_Core_Form $form
498 * Form object.
499 * @param array $params
500 * An assoc array of name/value pairs.
501 *
502 * @return void
503 */
504 public static function sendAcknowledgment(&$form, $params) {
505 //handle Acknowledgment.
506 $allPayments = $payments = array();
507
508 //get All Payments status types.
509 $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
510 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
511 //get all paymnets details.
512 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
513
514 if (!empty($allPayments)) {
515 foreach ($allPayments as $payID => $values) {
516 $contributionValue = $contributionStatus = array();
517 if (isset($values['contribution_id'])) {
518 $contributionParams = array('id' => $values['contribution_id']);
519 $returnProperties = array('contribution_status_id', 'receive_date');
520 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_Contribution',
521 $contributionParams, $contributionStatus, $returnProperties
522 );
523 $contributionValue = array(
524 'status' => CRM_Utils_Array::value('contribution_status_id', $contributionStatus),
525 'receive_date' => CRM_Utils_Array::value('receive_date', $contributionStatus),
526 );
527 }
528 $payments[$payID] = array_merge($contributionValue,
529 array(
530 'amount' => CRM_Utils_Array::value('scheduled_amount', $values),
531 'due_date' => CRM_Utils_Array::value('scheduled_date', $values),
532 )
533 );
534
535 //get the first valid payment id.
536 if (!isset($form->paymentId) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
537 $paymentStatusTypes[$values['status_id']] == 'Overdue'
538 )) {
539 $form->paymentId = $values['id'];
540 }
541 }
542 }
543
544 //assign pledge fields value to template.
545 $pledgeFields = array(
546 'create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit',
547 'installments', 'frequency_day', 'scheduled_amount', 'currency',
548 );
549 foreach ($pledgeFields as $field) {
550 if (!empty($params[$field])) {
551 $form->assign($field, $params[$field]);
552 }
553 }
554
555 //assign all payments details.
556 if ($payments) {
557 $form->assign('payments', $payments);
558 }
559
560 //handle domain token values
561 $domain = CRM_Core_BAO_Domain::getDomain();
562 $tokens = array(
563 'domain' => array('name', 'phone', 'address', 'email'),
564 'contact' => CRM_Core_SelectValues::contactTokens(),
565 );
566 $domainValues = array();
567 foreach ($tokens['domain'] as $token) {
568 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
569 }
570 $form->assign('domain', $domainValues);
571
572 //handle contact token values.
573 $ids = array($params['contact_id']);
574 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::importableFields()),
575 array('display_name', 'checksum', 'contact_id')
576 );
577 foreach ($fields as $key => $val) {
578 $returnProperties[$val] = TRUE;
579 }
580 $details = CRM_Utils_Token::getTokenDetails($ids,
581 $returnProperties,
582 TRUE, TRUE, NULL,
583 $tokens,
584 get_class($form)
585 );
586 $form->assign('contact', $details[0][$params['contact_id']]);
587
588 //handle custom data.
589 if (!empty($params['hidden_custom'])) {
590 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', CRM_Core_DAO::$_nullObject, $params['id']);
591 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
592 $customGroup = array();
593 // retrieve custom data
594 foreach ($groupTree as $groupID => $group) {
595 $customFields = $customValues = array();
596 if ($groupID == 'info') {
597 continue;
598 }
599 foreach ($group['fields'] as $k => $field) {
600 $field['title'] = $field['label'];
601 $customFields["custom_{$k}"] = $field;
602 }
603
604 //to build array of customgroup & customfields in it
605 CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
606 $customGroup[$group['title']] = $customValues;
607 }
608
609 $form->assign('customGroup', $customGroup);
610 }
611
612 //handle acknowledgment email stuff.
613 list($pledgerDisplayName,
614 $pledgerEmail
615 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
616
617 //check for online pledge.
618 $session = CRM_Core_Session::singleton();
619 if (!empty($params['receipt_from_email'])) {
620 $userName = CRM_Utils_Array::value('receipt_from_name', $params);
621 $userEmail = CRM_Utils_Array::value('receipt_from_email', $params);
622 }
623 elseif (!empty($params['from_email_id'])) {
624 $receiptFrom = $params['from_email_id'];
625 }
626 elseif ($userID = $session->get('userID')) {
627 //check for logged in user.
628 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
629 }
630 else {
631 //set the domain values.
632 $userName = CRM_Utils_Array::value('name', $domainValues);
633 $userEmail = CRM_Utils_Array::value('email', $domainValues);
634 }
635
636 if (!isset($receiptFrom)) {
637 $receiptFrom = "$userName <$userEmail>";
638 }
639
640 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
641 array(
642 'groupName' => 'msg_tpl_workflow_pledge',
643 'valueName' => 'pledge_acknowledge',
644 'contactId' => $params['contact_id'],
645 'from' => $receiptFrom,
646 'toName' => $pledgerDisplayName,
647 'toEmail' => $pledgerEmail,
648 )
649 );
650
651 //check if activity record exist for this pledge
652 //Acknowledgment, if exist do not add activity.
653 $activityType = 'Pledge Acknowledgment';
654 $activity = new CRM_Activity_DAO_Activity();
655 $activity->source_record_id = $params['id'];
656 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
657 $activityType,
658 'name'
659 );
660 $config = CRM_Core_Config::singleton();
661
662 // FIXME: Translate
663 $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)';
664
665 if (!$activity->find()) {
666 $activityParams = array(
667 'subject' => $subject,
668 'source_contact_id' => $params['contact_id'],
669 'source_record_id' => $params['id'],
670 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
671 $activityType,
672 'name'
673 ),
674 'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']),
675 'is_test' => $params['is_test'],
676 'status_id' => 2,
677 'details' => $details,
678 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
679 );
680
681 //lets insert assignee record.
682 if (!empty($params['contact_id'])) {
683 $activityParams['assignee_contact_id'] = $params['contact_id'];
684 }
685
686 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
687 CRM_Core_Error::fatal("Failed creating Activity for acknowledgment");
688 }
689 }
690 }
691
692 /**
693 * Combine all the exportable fields from the lower levels object
694 *
695 * @return array
696 * array of exportable Fields
697 * @static
698 */
699 public static function &exportableFields() {
700 if (!self::$_exportableFields) {
701 if (!self::$_exportableFields) {
702 self::$_exportableFields = array();
703 }
704
705 $fields = CRM_Pledge_DAO_Pledge::export();
706
707 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment::export());
708
709 //set title to calculated fields
710 $calculatedFields = array(
711 'pledge_total_paid' => array('title' => ts('Total Paid')),
712 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
713 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
714 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
715 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
716 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
717 'pledge_payment_status' => array(
718 'title' => ts('Pledge Payment Status'),
719 'name' => 'pledge_payment_status',
720 'data_type' => CRM_Utils_Type::T_STRING,
721 ),
722 );
723
724 $pledgeFields = array(
725 'pledge_status' => array(
726 'title' => 'Pledge Status',
727 'name' => 'pledge_status',
728 'data_type' => CRM_Utils_Type::T_STRING,
729 ),
730 'pledge_frequency_unit' => array(
731 'title' => 'Pledge Frequency Unit',
732 'name' => 'pledge_frequency_unit',
733 'data_type' => CRM_Utils_Type::T_ENUM,
734 ),
735 'pledge_frequency_interval' => array(
736 'title' => 'Pledge Frequency Interval',
737 'name' => 'pledge_frequency_interval',
738 'data_type' => CRM_Utils_Type::T_INT,
739 ),
740 'pledge_contribution_page_id' => array(
741 'title' => 'Pledge Contribution Page Id',
742 'name' => 'pledge_contribution_page_id',
743 'data_type' => CRM_Utils_Type::T_INT,
744 ),
745 );
746
747 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
748
749 // add custom data
750 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge'));
751 self::$_exportableFields = $fields;
752 }
753
754 return self::$_exportableFields;
755 }
756
757 /**
758 * Get pending or in progress pledges
759 *
760 * @param int $contactID
761 * Contact id.
762 *
763 * @return array
764 * associated array of pledge id(s)
765 * @static
766 */
767 public static function getContactPledges($contactID) {
768 $pledgeDetails = array();
769 $pledgeStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
770
771 $status = array();
772
773 //get pending and in progress status
774 foreach (array(
775 'Pending', 'In Progress', 'Overdue') as $name) {
776 if ($statusId = array_search($name, $pledgeStatuses)) {
777 $status[] = $statusId;
778 }
779 }
780 if (empty($status)) {
781 return $pledgeDetails;
782 }
783
784 $statusClause = " IN (" . implode(',', $status) . ")";
785
786 $query = "
787 SELECT civicrm_pledge.id id
788 FROM civicrm_pledge
789 WHERE civicrm_pledge.status_id {$statusClause}
790 AND civicrm_pledge.contact_id = %1
791 ";
792
793 $params[1] = array($contactID, 'Integer');
794 $pledge = CRM_Core_DAO::executeQuery($query, $params);
795
796 while ($pledge->fetch()) {
797 $pledgeDetails[] = $pledge->id;
798 }
799
800 return $pledgeDetails;
801 }
802
803 /**
804 * Get pledge record count for a Contact
805 *
806 * @param int $contactID
807 *
808 * @return int
809 * count of pledge records
810 * @static
811 */
812 public static function getContactPledgeCount($contactID) {
813 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
814 return CRM_Core_DAO::singleValueQuery($query);
815 }
816
817 /**
818 * @param array $params
819 *
820 * @return array
821 */
822 public static function updatePledgeStatus($params) {
823
824 $returnMessages = array();
825
826 $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE);
827
828 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
829
830 //unset statues that we never use for pledges
831 foreach (array(
832 'Completed', 'Cancelled', 'Failed') as $statusKey) {
833 if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) {
834 unset($allStatus[$key]);
835 }
836 }
837
838 $statusIds = implode(',', array_keys($allStatus));
839 $updateCnt = 0;
840
841 $query = "
842 SELECT pledge.contact_id as contact_id,
843 pledge.id as pledge_id,
844 pledge.amount as amount,
845 payment.scheduled_date as scheduled_date,
846 pledge.create_date as create_date,
847 payment.id as payment_id,
848 pledge.currency as currency,
849 pledge.contribution_page_id as contribution_page_id,
850 payment.reminder_count as reminder_count,
851 pledge.max_reminders as max_reminders,
852 payment.reminder_date as reminder_date,
853 pledge.initial_reminder_day as initial_reminder_day,
854 pledge.additional_reminder_day as additional_reminder_day,
855 pledge.status_id as pledge_status,
856 payment.status_id as payment_status,
857 pledge.is_test as is_test,
858 pledge.campaign_id as campaign_id,
859 SUM(payment.scheduled_amount) as amount_due,
860 ( SELECT sum(civicrm_pledge_payment.actual_amount)
861 FROM civicrm_pledge_payment
862 WHERE civicrm_pledge_payment.status_id = 1
863 AND civicrm_pledge_payment.pledge_id = pledge.id
864 ) as amount_paid
865 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
866 WHERE pledge.id = payment.pledge_id
867 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
868 GROUP By payment.id
869 ";
870
871 $dao = CRM_Core_DAO::executeQuery($query);
872
873 $now = date('Ymd');
874 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
875 while ($dao->fetch()) {
876 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
877
878 $pledgeDetails[$dao->payment_id] = array(
879 'scheduled_date' => $dao->scheduled_date,
880 'amount_due' => $dao->amount_due,
881 'amount' => $dao->amount,
882 'amount_paid' => $dao->amount_paid,
883 'create_date' => $dao->create_date,
884 'contact_id' => $dao->contact_id,
885 'pledge_id' => $dao->pledge_id,
886 'checksumValue' => $checksumValue,
887 'contribution_page_id' => $dao->contribution_page_id,
888 'reminder_count' => $dao->reminder_count,
889 'max_reminders' => $dao->max_reminders,
890 'reminder_date' => $dao->reminder_date,
891 'initial_reminder_day' => $dao->initial_reminder_day,
892 'additional_reminder_day' => $dao->additional_reminder_day,
893 'pledge_status' => $dao->pledge_status,
894 'payment_status' => $dao->payment_status,
895 'is_test' => $dao->is_test,
896 'currency' => $dao->currency,
897 'campaign_id' => $dao->campaign_id,
898 );
899
900 $contactIds[$dao->contact_id] = $dao->contact_id;
901 $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
902
903 if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'),
904 $now
905 ) && $dao->payment_status != array_search('Overdue', $allStatus)) {
906 $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
907 }
908 }
909
910 // process the updating script...
911
912 foreach ($pledgePayments as $pledgeId => $paymentIds) {
913 // 1. update the pledge /pledge payment status. returns new status when an update happens
914 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
915
916 $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds,
917 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
918 );
919 if ($newStatus != $pledgeStatus[$pledgeId]) {
920 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
921 $updateCnt += 1;
922 }
923 }
924
925 if ($sendReminders) {
926 // retrieve domain tokens
927 $domain = CRM_Core_BAO_Domain::getDomain();
928 $tokens = array(
929 'domain' => array('name', 'phone', 'address', 'email'),
930 'contact' => CRM_Core_SelectValues::contactTokens(),
931 );
932
933 $domainValues = array();
934 foreach ($tokens['domain'] as $token) {
935 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
936 }
937
938 //get the domain email address, since we don't carry w/ object.
939 $domainValue = CRM_Core_BAO_Domain::getNameAndEmail();
940 $domainValues['email'] = $domainValue[1];
941
942 // retrieve contact tokens
943
944 // this function does NOT return Deceased contacts since we don't want to send them email
945 list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
946 NULL,
947 FALSE, FALSE, NULL,
948 $tokens, 'CRM_UpdatePledgeRecord'
949 );
950
951 // assign domain values to template
952 $template = CRM_Core_Smarty::singleton();
953 $template->assign('domain', $domainValues);
954
955 //set receipt from
956 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
957
958 foreach ($pledgeDetails as $paymentId => $details) {
959 if (array_key_exists($details['contact_id'], $contactDetails)) {
960 $contactId = $details['contact_id'];
961 $pledgerName = $contactDetails[$contactId]['display_name'];
962 }
963 else {
964 continue;
965 }
966
967 if (empty($details['reminder_date'])) {
968 $nextReminderDate = new DateTime($details['scheduled_date']);
969 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
970 $nextReminderDate = $nextReminderDate->format("Ymd");
971 }
972 else {
973 $nextReminderDate = new DateTime($details['reminder_date']);
974 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
975 $nextReminderDate = $nextReminderDate->format("Ymd");
976 }
977 if (($details['reminder_count'] < $details['max_reminders'])
978 && ($nextReminderDate <= $now)
979 ) {
980
981 $toEmail = $doNotEmail = $onHold = NULL;
982
983 if (!empty($contactDetails[$contactId]['email'])) {
984 $toEmail = $contactDetails[$contactId]['email'];
985 }
986
987 if (!empty($contactDetails[$contactId]['do_not_email'])) {
988 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
989 }
990
991 if (!empty($contactDetails[$contactId]['on_hold'])) {
992 $onHold = $contactDetails[$contactId]['on_hold'];
993 }
994
995 // 2. send acknowledgement mail
996 if ($toEmail && !($doNotEmail || $onHold)) {
997 //assign value to template
998 $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
999 $template->assign('contact', $contactDetails[$contactId]);
1000 $template->assign('next_payment', $details['scheduled_date']);
1001 $template->assign('amount_due', $details['amount_due']);
1002 $template->assign('checksumValue', $details['checksumValue']);
1003 $template->assign('contribution_page_id', $details['contribution_page_id']);
1004 $template->assign('pledge_id', $details['pledge_id']);
1005 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1006 $template->assign('amount', $details['amount']);
1007 $template->assign('create_date', $details['create_date']);
1008 $template->assign('currency', $details['currency']);
1009 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1010 array(
1011 'groupName' => 'msg_tpl_workflow_pledge',
1012 'valueName' => 'pledge_reminder',
1013 'contactId' => $contactId,
1014 'from' => $receiptFrom,
1015 'toName' => $pledgerName,
1016 'toEmail' => $toEmail,
1017 )
1018 );
1019
1020 // 3. update pledge payment details
1021 if ($mailSent) {
1022 CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
1023 $activityType = 'Pledge Reminder';
1024 $activityParams = array(
1025 'subject' => $subject,
1026 'source_contact_id' => $contactId,
1027 'source_record_id' => $paymentId,
1028 'assignee_contact_id' => $contactId,
1029 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1030 $activityType,
1031 'name'
1032 ),
1033 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1034 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']),
1035 'is_test' => $details['is_test'],
1036 'status_id' => 2,
1037 'campaign_id' => $details['campaign_id'],
1038 );
1039 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1040 $returnMessages[] = "Failed creating Activity for acknowledgment";
1041 return array('is_error' => 1, 'message' => $returnMessages);
1042 }
1043 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1044 }
1045 }
1046 }
1047 }
1048 // end foreach on $pledgeDetails
1049 }
1050 // end if ( $sendReminders )
1051 $returnMessages[] = "{$updateCnt} records updated.";
1052
1053 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1054 }
1055
1056 /**
1057 * Mark a pledge (and any outstanding payments) as cancelled.
1058 *
1059 * @param int $pledgeID
1060 */
1061 public static function cancel($pledgeID) {
1062 $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus());
1063 $paymentIDs = self::findCancelablePayments($pledgeID);
1064 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1065 $statuses['Cancelled'], 0, FALSE, TRUE
1066 );
1067 }
1068
1069 /**
1070 * Find payments which can be safely canceled.
1071 *
1072 * @param int $pledgeID
1073 * @return array
1074 * of int (civicrm_pledge_payment.id)
1075 */
1076 public static function findCancelablePayments($pledgeID) {
1077 $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus());
1078
1079 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1080 $paymentDAO->pledge_id = $pledgeID;
1081 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1082 $statuses['Overdue'],
1083 $statuses['Pending']
1084 ));
1085 $paymentDAO->find();
1086
1087 $paymentIDs = array();
1088 while ($paymentDAO->fetch()) {
1089 $paymentIDs[] = $paymentDAO->id;
1090 }
1091 return $paymentIDs;
1092 }
1093
1094 /**
1095 * Is this pledge free from financial transactions (this is important to know as we allow editing
1096 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1097 * & recreating so we want to block that if appropriate
1098 *
1099 * @param int $pledgeID
1100 * @param int $pledgeStatusID
1101 * @return bool
1102 * do financial transactions exist for this pledge?
1103 */
1104 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1105 if (empty($pledgeStatusID)) {
1106 //why would this happen? If we can see where it does then we can see if we should look it up
1107 //but assuming from form code it CAN be empty
1108 return TRUE;
1109 }
1110 if (self::isTransactedStatus($pledgeStatusID)) {
1111 return TRUE;
1112 }
1113
1114 return civicrm_api3('pledge_payment', 'getcount', array('pledge_id' => $pledgeID, 'status_id' => array('IN' => self::getTransactionalStatus())));
1115 }
1116
1117 /**
1118 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1119 * @param int $statusID
1120 * Pledge status id.
1121 *
1122 * @return bool
1123 * is it a transactional status?
1124 */
1125 protected static function isTransactedStatus($statusID) {
1126 if (!in_array($statusID, self::getNonTransactionalStatus())) {
1127 return TRUE;
1128 }
1129 return FALSE;
1130 }
1131
1132 /**
1133 * Get array of non transactional statuses
1134 * @return array
1135 * non transactional status ids
1136 */
1137 protected static function getNonTransactionalStatus() {
1138 $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1139 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1140 }
1141
1142 /**
1143 * Get array of non transactional statuses
1144 * @return array
1145 * non transactional status ids
1146 */
1147 protected static function getTransactionalStatus() {
1148 $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1149 return array_diff(array_flip($paymentStatus), self::getNonTransactionalStatus());
1150 }
1151 }