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