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