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