VAT-417 Record an activity Downloaded Invoice and Emailed Invoice on Print Invoice...
[civicrm-core.git] / CRM / Contribute / Form / Task / Invoice.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 *
33 */
34
35 /**
36 * This class provides the functionality to email a group of
37 * contacts.
38 */
39 class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
40 /**
41 * Are we operating in "single mode", i.e. updating the task of only
42 * one specific contribution?
43 *
44 * @var boolean
45 */
46 public $_single = FALSE;
47
48 /**
49 * gives all the statues for conribution
50 *
51 * @access public
52 */
53 public $_contributionStatusId;
54
55 /**
56 * gives the HTML template of PDF Invoice
57 *
58 * @access public
59 */
60 public $_messageInvoice;
61
62 /**
63 * This variable is used to assign parameters for HTML template of PDF Invoice
64 *
65 * @access public
66 */
67 public $_invoiceTemplate;
68 /**
69 * build all the data structures needed to build the form
70 *
71 * @return void
72 * @access public
73 */
74 function preProcess() {
75 $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
76 if ($id) {
77 $this->_contributionIds = array($id);
78 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
79 $this->_single = TRUE;
80 $this->assign('totalSelectedContributions', 1);
81 }
82 else {
83 parent::preProcess();
84 }
85
86 // check that all the contribution ids have status Completed, Pending, Refunded.
87 $this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
88 $status = array('Completed', 'Pending', 'Refunded');
89 $statusId = array();
90 foreach ($this->_contributionStatusId as $key => $value) {
91 if (in_array($value, $status)) {
92 $statusId[] = $key;
93 }
94 }
95 $Id = implode(",", $statusId);
96 $query = "SELECT count(*) FROM civicrm_contribution WHERE contribution_status_id NOT IN ($Id) AND {$this->_componentClause}";
97 $count = CRM_Core_DAO::singleValueQuery($query);
98 if ($count != 0) {
99 CRM_Core_Error::statusBounce(ts('Please select only contributions with Completed, Pending, Refunded status.'));
100 }
101
102 // we have all the contribution ids, so now we get the contact ids
103 parent::setContactIDs();
104 $this->assign('single', $this->_single);
105
106 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
107 $urlParams = 'force=1';
108 if (CRM_Utils_Rule::qfKey($qfKey)) {
109 $urlParams .= "&qfKey=$qfKey";
110 }
111
112 $url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
113 $breadCrumb = array(
114 array('url' => $url,
115 'title' => ts('Search Results'),
116 ));
117
118 CRM_Utils_System::appendBreadCrumb($breadCrumb);
119 if (in_array("email", $this->urlPath)) {
120 CRM_Utils_System::setTitle(ts('Email Invoice'));
121 } else {
122 CRM_Utils_System::setTitle(ts('Print Contribution Invoice'));
123 }
124 }
125
126 /**
127 * Build the form
128 *
129 * @access public
130 *
131 * @return void
132 */
133 public function buildQuickForm() {
134 $session = CRM_Core_Session::singleton();
135 $config = CRM_Core_Config::singleton();
136 $options = array();
137 $session->getVars($options,
138 "CRM_Mailing_Controller_Send_{$this->controller->_key}"
139 );
140 if (CRM_Core_Permission::check('administer CiviCRM')) {
141 $this->assign('isAdmin', 1);
142 }
143 $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
144 if (empty($fromEmailAddress)) {
145 //redirect user to enter from email address.
146 $url = CRM_Utils_System::url('civicrm/admin/options/from_email_address', 'action=add&reset=1');
147 $status = ts("There is no valid from email address present. You can add here <a href='%1'>Add From Email Address.</a>", array(1 => $url));
148 $session->setStatus($status, ts('Notice'));
149 }
150 else {
151 foreach ($fromEmailAddress as $key => $email) {
152 $fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
153 }
154 }
155 $this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
156 $this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
157 $this->add('select', 'from_email_address',
158 ts('From Email Address'), array(
159 '' => '- select -') + $fromEmailAddress
160 );
161
162 // Validation of From Email Address
163 if (in_array("email", $this->urlPath)) {
164 $this->addRule('from_email_address', ts('From Email Address is required'), 'required');
165 }
166 else {
167 $this->addRule('output', ts('Selection required'), 'required');
168 if (!empty($this->_submitValues['output']) && $this->_submitValues['output'] == 'email_invoice') {
169 $this->addRule('from_email_address', ts('From Email Address is required'), 'required');
170 }
171 }
172
173 $this->addWysiwyg('email_comment', ts('If you would like to add personal message to email please add it here. (The same messages will sent to all receipients.)'), array('rows' => 2, 'cols' => 40));
174
175 if (in_array("email", $this->urlPath)) {
176 $this->addButtons(array(
177 array(
178 'type' => 'next',
179 'name' => ts('Email Invoice'),
180 'isDefault' => TRUE,
181 ),
182 array(
183 'type' => 'back',
184 'name' => ts('Cancel'),
185 ),
186 )
187 );
188 } else {
189 $this->addButtons(array(
190 array(
191 'type' => 'next',
192 'name' => ts('Process Invoice(s)'),
193 'isDefault' => TRUE,
194 ),
195 array(
196 'type' => 'back',
197 'name' => ts('Cancel'),
198 ),
199 )
200 );
201 }
202 }
203
204 /**
205 * process the form after the input has been submitted and validated
206 *
207 * @access public
208 *
209 * @return void
210 */
211 public function postProcess() {
212 $params = $this->controller->exportValues($this->_name);
213 $this->printPDF($this->_contributionIds, $params, $this->_contactIds);
214 }
215
216 /**
217 *
218 * process the PDf and email with activity and attachment
219 * on click of Print Invoices
220 *
221 * @param array $contribIDs Contribution Id
222 * @param array $params for pdf or email invoices
223 * @param array $contactIds Contact Id
224 * @static
225 *
226 */
227 static function printPDF($contribIDs, $params, $contactIds) {
228 // get all the details needed to generate a invoice
229 $messageInvoice = array();
230
231 $invoiceTemplate = CRM_Core_Smarty::singleton();
232
233 $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
234
235 // gives the status id when contribution status is 'Refunded'
236 $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
237 $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
238
239 // getting data from admin page
240 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
241
242 foreach ($invoiceElements['details'] as $contribID => $detail) {
243 $input = $ids = $objects = array();
244
245 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
246 continue;
247 }
248
249 $input['component'] = $detail['component'];
250
251 $ids['contact'] = $detail['contact'];
252 $ids['contribution'] = $contribID;
253 $ids['contributionRecur'] = NULL;
254 $ids['contributionPage'] = NULL;
255 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
256 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
257 $ids['event'] = CRM_Utils_Array::value('event', $detail);
258
259 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
260 CRM_Core_Error::fatal();
261 }
262
263 $contribution = &$objects['contribution'];
264
265 $input['amount'] = $contribution->total_amount;
266 $input['invoice_id'] = $contribution->invoice_id;
267 $input['receive_date'] = $contribution->receive_date;
268 $input['contribution_status_id'] = $contribution->contribution_status_id;
269 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
270
271 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
272
273 $addressParams = array('contact_id' => $contribution->contact_id);
274 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
275
276 // to get billing address if present
277 $billingAddress = array();
278 foreach ($addressDetails as $key => $address) {
279 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
280 $billingAddress[$address['contact_id']] = $address;
281 break;
282 }
283 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
284 $billingAddress[$address['contact_id']] = $address;
285 }
286 }
287
288 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
289 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
290 }
291 else {
292 $stateProvinceAbbreviation = '';
293 }
294
295 if ($contribution->contribution_status_id == $refundedStatusId) {
296 $invoiceId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue). "" .$contribution->id;
297 }
298 else {
299 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue). "" .$contribution->id;
300 }
301
302 //to obtain due date for PDF invoice
303 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
304 $invoiceDate = date("F j, Y");
305 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate. "+" .$prefixValue['due_date']. "" .$prefixValue['due_date_period']));
306
307 if ($input['component'] == 'contribute') {
308 $eid = $contribID;
309 $etable = 'contribution';
310 }
311 else {
312 $eid = $contribution->_relatedObjects['participant']->id;
313 $etable = 'participant';
314 }
315
316 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
317 $amountDue = ($input['amount'] - $input['amount']);
318
319 // retreiving the subtotal and sum of same tax_rate
320 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable);
321 $dataArray = array();
322 $subTotal = 0;
323 foreach ($lineItem as $entity_id => $taxRate) {
324 if (isset($dataArray[$taxRate['tax_rate']])) {
325 $dataArray[$taxRate['tax_rate']] = $dataArray[$taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
326 }
327 else {
328 $dataArray[$taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
329 }
330 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
331 }
332
333 // to email the invoice
334 $mailDetails = array();
335 $values = array();
336 if ($contribution->_component == 'event') {
337 $daoName = 'CRM_Event_DAO_Event';
338 $pageId = $contribution->_relatedObjects['event']->id;
339 $mailElements = array(
340 'title',
341 'confirm_from_name',
342 'confirm_from_email',
343 'cc_confirm',
344 'bcc_confirm',
345 );
346 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
347 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
348 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
349 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
350 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
351 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
352
353 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
354 }
355 elseif ($contribution->_component == 'contribute') {
356 $daoName = 'CRM_Contribute_DAO_ContributionPage';
357 $pageId = $contribution->contribution_page_id;
358 $mailElements = array(
359 'title',
360 'receipt_from_name',
361 'receipt_from_email',
362 'cc_receipt',
363 'bcc_receipt',
364 );
365 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
366
367 $values['title'] = CRM_Utils_Array::value('title',CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
368 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
369 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
370 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
371 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
372
373 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
374 }
375
376 $config = CRM_Core_Config::singleton();
377 $config->doNotAttachPDFReceipt = 1;
378
379 // parameters to be assign for template
380 $tplParams = array(
381 'title' => $title,
382 'component' => $input['component'],
383 'id' => $contribution->id,
384 'invoice_id' => $invoiceId,
385 'imageUploadURL' => $config->imageUploadURL,
386 'defaultCurrency' => $config->defaultCurrency,
387 'amount' => $contribution->total_amount,
388 'amountDue' => $amountDue,
389 'invoice_date' => $invoiceDate,
390 'dueDate' => $dueDate,
391 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
392 'display_name' => $contribution->_relatedObjects['contact']->display_name,
393 'lineItem' => $lineItem,
394 'dataArray' => $dataArray,
395 'refundedStatusId' => $refundedStatusId,
396 'contribution_status_id' => $contribution->contribution_status_id,
397 'subTotal' => $subTotal,
398 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
399 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
400 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
401 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
402 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
403 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
404 'is_pay_later' => $contribution->is_pay_later,
405 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
406 );
407
408 $sendTemplateParams = array(
409 'groupName' => 'msg_tpl_workflow_contribution',
410 'valueName' => 'contribution_invoice_receipt',
411 'contactId' => $contribution->contact_id,
412 'tplParams' => $tplParams,
413 'PDFFilename' => 'Invoice.pdf',
414 );
415
416
417 // from email address
418 if (isset($params['from_email_address'])) {
419 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'],
420 CRM_Core_OptionGroup::values('from_email_address')
421 );
422 }
423 // condition to check for download PDF Invoice or email Invoice
424 if ($invoiceElements['createPdf']) {
425 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
426 $mail = array(
427 'subject' => $subject,
428 'body' => $message,
429 'html' => $html,
430 );
431
432 if ($mail['html']) {
433 $messageInvoice[] = $mail['html'];
434 }
435 else {
436 $messageInvoice[] = nl2br($mail['body']);
437 }
438 }
439 elseif ($contribution->_component == 'contribute') {
440 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
441
442 $sendTemplateParams['tplParams'] = array_merge($tplParams,array('email_comment' => $invoiceElements['params']['email_comment']));
443 $sendTemplateParams['from'] = $fromEmailAddress;
444 $sendTemplateParams['toEmail'] = $email;
445 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
446 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
447
448 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
449 // functions call for adding activity with attachment
450 $fileName = self::putFile($html);
451 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
452 }
453 elseif ($contribution->_component == 'event') {
454 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
455
456 $sendTemplateParams['tplParams'] = array_merge($tplParams,array('email_comment' => $invoiceElements['params']['email_comment']));
457 $sendTemplateParams['from'] = $fromEmailAddress;
458 $sendTemplateParams['toEmail'] = $email;
459 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
460 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
461
462 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
463 // functions call for adding activity with attachment
464 $fileName = self::putFile($html);
465 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
466 }
467
468 $updateInvoiceId = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
469 $invoiceTemplate->clearTemplateVars();
470 }
471
472 if ($invoiceElements['createPdf']) {
473 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE);
474
475 // functions call for adding activity with attachment
476 $fileName = self::putFile($html);
477 self::addActivities($subject, $contactIds, $fileName, $params['output']);
478
479 CRM_Utils_System::civiExit();
480 }
481 else {
482 if ($invoiceElements['suppressedEmails']) {
483 $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails']));
484 $msgTitle = ts('Email Error');
485 $msgType = 'error';
486 }
487 else {
488 $status = ts('Your mail has been sent.');
489 $msgTitle = ts('Sent');
490 $msgType = 'success';
491 }
492 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
493 }
494 }
495
496 /**
497 *
498 * This function is use for adding activity for
499 * Email Invoice and the PDF Invoice
500 *
501 * @param string $subject Activity subject
502 * @param array $contactIds Contact Id
503 * @param string $fileName gives the location with name of the file
504 * @param array $output for invoices
505 *
506 */
507 public function addActivities($subject, $contactIds, $fileName, $output) {
508 $session = CRM_Core_Session::singleton();
509 $userID = $session->get('userID');
510 $config = CRM_Core_Config::singleton();
511 $config->doNotAttachPDFReceipt = 1;
512 if ($output['output'] == 'email_invoice' || (is_array($output) && array_key_exists("from_email_address", $output))) {
513 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
514 'Emailed Invoice',
515 'name'
516 );
517 } else {
518 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
519 'Downloaded Invoice',
520 'name'
521 );
522 }
523 $activityParams = array(
524 'subject' => $subject,
525 'source_contact_id' => $userID,
526 'target_contact_id' => $contactIds,
527 'activity_type_id' => $activityTypeID,
528 'activity_date_time' => date('YmdHis'),
529 'attachFile_1' => array ('uri' => $fileName,
530 'type' => 'application/pdf',
531 'location' => $fileName,
532 'upload_date' => date('YmdHis'),
533 ),
534 );
535 $activity = CRM_Activity_BAO_Activity::create($activityParams);
536 }
537
538 /**
539 *
540 * This function is use for creating the Invoice file in upload folder
541 * for attachment
542 *
543 * @param $html content for pdf in html format
544 *
545 * return $fileName of file which is in pdf format
546 *
547 */
548 public function putFile($html) {
549 require_once("packages/dompdf/dompdf_config.inc.php");
550 spl_autoload_register('DOMPDF_autoload');
551 $doc = new DOMPDF();
552 $doc->load_html($html);
553 $doc->render();
554 $html = $doc->output();
555 $config = CRM_Core_Config::singleton();
556 $fileName = $config->uploadDir.'Invoice.pdf';
557 $file = file_put_contents($fileName, $html);
558 return $fileName;
559 }
560
561 }
562