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