INFRA-132 - tests/ - PHPStorm cleanup
[civicrm-core.git] / bin / deprecated / UpdatePledgeRecord.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
f5721b07 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26 */
27
28
29/*
30 * This file checks and updates the status of all pledge records for a
31 * given domain using the updatePledgePaymentStatus.
783f84c9 32 *
6a488035
TO
33 * UpdatePledgeRecord.php prior to running this script.
34 */
35
36require_once '../civicrm.config.php';
37require_once 'CRM/Core/Config.php';
4e87860d
EM
38
39/**
40 * Class CRM_UpdatePledgeRecord
41 */
6a488035 42class CRM_UpdatePledgeRecord {
4e87860d 43 /**
4e87860d 44 */
6a488035
TO
45 function __construct() {
46 $config = CRM_Core_Config::singleton();
47 // this does not return on failure
48 require_once 'CRM/Utils/System.php';
49 require_once 'CRM/Utils/Hook.php';
50
51 CRM_Utils_System::authenticateScript(TRUE);
52 $config->cleanURL = 1;
53
54 //log the execution time of script
55 CRM_Core_Error::debug_log_message('UpdatePledgeRecord.php');
56 }
57
4e87860d
EM
58 /**
59 * @param bool $sendReminders
60 *
61 * @throws Exception
62 */
6a488035
TO
63 public function updatePledgeStatus($sendReminders = FALSE) {
64
65 // *** Uncomment the next line if you want automated reminders to be sent
66 // $sendReminders = true;
67
68 require_once 'CRM/Contribute/PseudoConstant.php';
69 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
70
71 //unset statues that we never use for pledges
72 foreach (array(
73 'Completed', 'Cancelled', 'Failed') as $statusKey) {
74 if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) {
75 unset($allStatus[$key]);
76 }
77 }
78
79 $statusIds = implode(',', array_keys($allStatus));
80 $updateCnt = 0;
81
82 $query = "
83SELECT pledge.contact_id as contact_id,
84 pledge.id as pledge_id,
85 pledge.amount as amount,
86 payment.scheduled_date as scheduled_date,
87 pledge.create_date as create_date,
88 payment.id as payment_id,
89 pledge.contribution_page_id as contribution_page_id,
90 payment.reminder_count as reminder_count,
91 pledge.max_reminders as max_reminders,
92 payment.reminder_date as reminder_date,
93 pledge.initial_reminder_day as initial_reminder_day,
94 pledge.additional_reminder_day as additional_reminder_day,
95 pledge.status_id as pledge_status,
96 payment.status_id as payment_status,
97 pledge.is_test as is_test,
98 pledge.campaign_id as campaign_id,
99 SUM(payment.scheduled_amount) as amount_due,
783f84c9 100 ( SELECT sum(civicrm_pledge_payment.actual_amount)
101 FROM civicrm_pledge_payment
6a488035
TO
102 WHERE civicrm_pledge_payment.status_id = 1
103 AND civicrm_pledge_payment.pledge_id = pledge.id
104 ) as amount_paid
783f84c9 105 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
6a488035
TO
106 WHERE pledge.id = payment.pledge_id
107 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
108 GROUP By payment.id
109 ";
110
111 $dao = CRM_Core_DAO::executeQuery($query);
112
113 require_once 'CRM/Contact/BAO/Contact/Utils.php';
114 require_once 'CRM/Utils/Date.php';
115 $now = date('Ymd');
116 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
117 while ($dao->fetch()) {
118 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
119
120 $pledgeDetails[$dao->payment_id] = array(
121 'scheduled_date' => $dao->scheduled_date,
122 'amount_due' => $dao->amount_due,
123 'amount' => $dao->amount,
124 'amount_paid' => $dao->amount_paid,
125 'create_date' => $dao->create_date,
126 'contact_id' => $dao->contact_id,
127 'pledge_id' => $dao->pledge_id,
128 'checksumValue' => $checksumValue,
129 'contribution_page_id' => $dao->contribution_page_id,
130 'reminder_count' => $dao->reminder_count,
131 'max_reminders' => $dao->max_reminders,
132 'reminder_date' => $dao->reminder_date,
133 'initial_reminder_day' => $dao->initial_reminder_day,
134 'additional_reminder_day' => $dao->additional_reminder_day,
135 'pledge_status' => $dao->pledge_status,
136 'payment_status' => $dao->payment_status,
137 'is_test' => $dao->is_test,
138 'campaign_id' => $dao->campaign_id,
139 );
140
141 $contactIds[$dao->contact_id] = $dao->contact_id;
142 $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
143
144 if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'),
145 $now
146 ) && $dao->payment_status != array_search('Overdue', $allStatus)) {
147 $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
148 }
149 }
150
151 require_once 'CRM/Pledge/BAO/PledgePayment.php';
152 // process the updating script...
153
154 foreach ($pledgePayments as $pledgeId => $paymentIds) {
155 // 1. update the pledge /pledge payment status. returns new status when an update happens
156 echo "<br />Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
157
158 $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds,
159 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
160 );
161 if ($newStatus != $pledgeStatus[$pledgeId]) {
162 echo "<br />- status updated to: {$allStatus[$newStatus]}";
163 $updateCnt += 1;
164 }
165 }
166
167 if ($sendReminders) {
168 // retrieve domain tokens
169 require_once 'CRM/Core/BAO/Domain.php';
170 require_once 'CRM/Core/SelectValues.php';
171 $domain = CRM_Core_BAO_Domain::getDomain();
a9e80afc
TO
172 $tokens = array(
173 'domain' => array('name', 'phone', 'address', 'email'),
6a488035
TO
174 'contact' => CRM_Core_SelectValues::contactTokens(),
175 );
176
177 require_once 'CRM/Utils/Token.php';
178 $domainValues = array();
179 foreach ($tokens['domain'] as $token) {
180 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
181 }
182
183 //get the domain email address, since we don't carry w/ object.
184 require_once 'CRM/Core/BAO/Domain.php';
185 $domainValue = CRM_Core_BAO_Domain::getNameAndEmail();
186 $domainValues['email'] = $domainValue[1];
187
188 // retrieve contact tokens
189
190 // this function does NOT return Deceased contacts since we don't want to send them email
191 require_once 'CRM/Utils/Token.php';
192 list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
193 NULL,
194 FALSE, FALSE, NULL,
195 $tokens, 'CRM_UpdatePledgeRecord'
196 );
197
198 // assign domain values to template
199 $template = CRM_Core_Smarty::singleton();
200 $template->assign('domain', $domainValues);
201
202 //set receipt from
203 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
204
205 foreach ($pledgeDetails as $paymentId => $details) {
206 if (array_key_exists($details['contact_id'], $contactDetails)) {
207 $contactId = $details['contact_id'];
208 $pledgerName = $contactDetails[$contactId]['display_name'];
209 }
210 else {
211 continue;
212 }
213
214 if (empty($details['reminder_date'])) {
215 $nextReminderDate = new DateTime($details['scheduled_date']);
216 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
217 $nextReminderDate = $nextReminderDate->format("Ymd");
218 }
219 else {
220 $nextReminderDate = new DateTime($details['reminder_date']);
221 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
222 $nextReminderDate = $nextReminderDate->format("Ymd");
223 }
224 if (($details['reminder_count'] < $details['max_reminders'])
225 && ($nextReminderDate <= $now)
226 ) {
227
228 $toEmail = $doNotEmail = $onHold = NULL;
229
230 if (!empty($contactDetails[$contactId]['email'])) {
231 $toEmail = $contactDetails[$contactId]['email'];
232 }
233
234 if (!empty($contactDetails[$contactId]['do_not_email'])) {
235 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
236 }
237
238 if (!empty($contactDetails[$contactId]['on_hold'])) {
239 $onHold = $contactDetails[$contactId]['on_hold'];
240 }
241
242 // 2. send acknowledgement mail
243 if ($toEmail && !($doNotEmail || $onHold)) {
244 //assign value to template
245 $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
246 $template->assign('contact', $contactDetails[$contactId]);
247 $template->assign('next_payment', $details['scheduled_date']);
248 $template->assign('amount_due', $details['amount_due']);
249 $template->assign('checksumValue', $details['checksumValue']);
250 $template->assign('contribution_page_id', $details['contribution_page_id']);
251 $template->assign('pledge_id', $details['pledge_id']);
252 $template->assign('scheduled_payment_date', $details['scheduled_date']);
253 $template->assign('amount', $details['amount']);
254 $template->assign('create_date', $details['create_date']);
255
c6327d7d
TO
256 require_once 'CRM/Core/BAO/MessageTemplate.php';
257 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
6a488035
TO
258 array(
259 'groupName' => 'msg_tpl_workflow_pledge',
260 'valueName' => 'pledge_reminder',
261 'contactId' => $contactId,
262 'from' => $receiptFrom,
263 'toName' => $pledgerName,
264 'toEmail' => $toEmail,
265 )
266 );
267
268 // 3. update pledge payment details
269 if ($mailSent) {
270 CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
271 $activityType = 'Pledge Reminder';
272 $activityParams = array(
273 'subject' => $subject,
274 'source_contact_id' => $contactId,
275 'source_record_id' => $paymentId,
276 'assignee_contact_id' => $contactId,
277 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
278 $activityType,
279 'name'
280 ),
281 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
282 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']),
283 'is_test' => $details['is_test'],
284 'status_id' => 2,
285 'campaign_id' => $details['campaign_id'],
286 );
287 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
288 CRM_Core_Error::fatal("Failed creating Activity for acknowledgment");
289 }
290 echo "<br />Payment reminder sent to: {$pledgerName} - {$toEmail}";
291 }
292 }
293 }
294 }
295 // end foreach on $pledgeDetails
296 }
297 // end if ( $sendReminders )
298 echo "<br />{$updateCnt} records updated.";
299 }
300}
301
302$obj = new CRM_UpdatePledgeRecord();
303echo "Updating<br />";
304$obj->updatePledgeStatus();
305echo "<br />Pledge records update script finished.";