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