CRM-16367 (Backoffice contribution page) get premium code under unit test
[civicrm-core.git] / CRM / Contribute / Form / AdditionalInfo.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35 class CRM_Contribute_Form_AdditionalInfo {
36
37 /**
38 * Build the form object for Premium Information.
39 *
40 * Called from the CRM_Contribute_Form_Contribute function and seemingly nowhere else.
41 *
42 * Probably this should be on the form that uses it since it is not used on multiple forms.
43 *
44 * Putting it on this class doesn't seem to reduce complexity.
45 *
46 * @param CRM_Core_Form $form
47 */
48 public static function buildPremium(&$form) {
49 //premium section
50 $form->add('hidden', 'hidden_Premium', 1);
51 $sel1 = $sel2 = array();
52
53 $dao = new CRM_Contribute_DAO_Product();
54 $dao->is_active = 1;
55 $dao->find();
56 $min_amount = array();
57 $sel1[0] = '-select product-';
58 while ($dao->fetch()) {
59 $sel1[$dao->id] = $dao->name . " ( " . $dao->sku . " )";
60 $min_amount[$dao->id] = $dao->min_contribution;
61 $options = explode(',', $dao->options);
62 foreach ($options as $k => $v) {
63 $options[$k] = trim($v);
64 }
65 if ($options[0] != '') {
66 $sel2[$dao->id] = $options;
67 }
68 $form->assign('premiums', TRUE);
69 }
70 $form->_options = $sel2;
71 $form->assign('mincontribution', $min_amount);
72 $sel = &$form->addElement('hierselect', "product_name", ts('Premium'), 'onclick="showMinContrib();"');
73 $js = "<script type='text/javascript'>\n";
74 $formName = 'document.forms.' . $form->getName();
75
76 for ($k = 1; $k < 2; $k++) {
77 if (!isset($defaults['product_name'][$k]) || (!$defaults['product_name'][$k])) {
78 $js .= "{$formName}['product_name[$k]'].style.display = 'none';\n";
79 }
80 }
81
82 $sel->setOptions(array($sel1, $sel2));
83 $js .= "</script>\n";
84 $form->assign('initHideBoxes', $js);
85
86 $form->addDate('fulfilled_date', ts('Fulfilled'), FALSE, array('formatType' => 'activityDate'));
87 $form->addElement('text', 'min_amount', ts('Minimum Contribution Amount'));
88 }
89
90 /**
91 * Build the form object for Additional Details.
92 *
93 *
94 * @param CRM_Core_Form $form
95 *
96 * @return void
97 */
98 public static function buildAdditionalDetail(&$form) {
99 //Additional information section
100 $form->add('hidden', 'hidden_AdditionalDetail', 1);
101
102 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
103
104 $form->addDateTime('thankyou_date', ts('Thank-you Sent'), FALSE, array('formatType' => 'activityDateTime'));
105
106 // add various amounts
107 $nonDeductAmount = &$form->add('text', 'non_deductible_amount', ts('Non-deductible Amount'),
108 $attributes['non_deductible_amount']
109 );
110 $form->addRule('non_deductible_amount', ts('Please enter a valid monetary value for Non-deductible Amount.'), 'money');
111
112 if ($form->_online) {
113 $nonDeductAmount->freeze();
114 }
115 $feeAmount = &$form->add('text', 'fee_amount', ts('Fee Amount'),
116 $attributes['fee_amount']
117 );
118 $form->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
119 if ($form->_online) {
120 $feeAmount->freeze();
121 }
122
123 $netAmount = &$form->add('text', 'net_amount', ts('Net Amount'),
124 $attributes['net_amount']
125 );
126 $form->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
127 if ($form->_online) {
128 $netAmount->freeze();
129 }
130 $element = &$form->add('text', 'invoice_id', ts('Invoice ID'),
131 $attributes['invoice_id']
132 );
133 if ($form->_online) {
134 $element->freeze();
135 }
136 else {
137 $form->addRule('invoice_id',
138 ts('This Invoice ID already exists in the database.'),
139 'objectExists',
140 array('CRM_Contribute_DAO_Contribution', $form->_id, 'invoice_id')
141 );
142 }
143 $element = $form->add('text', 'creditnote_id', ts('Credit Note ID'),
144 $attributes['creditnote_id']
145 );
146 if ($form->_online) {
147 $element->freeze();
148 }
149 else {
150 $form->addRule('creditnote_id',
151 ts('This Credit Note ID already exists in the database.'),
152 'objectExists',
153 array('CRM_Contribute_DAO_Contribution', $form->_id, 'creditnote_id')
154 );
155 }
156
157 $form->add('select', 'contribution_page_id',
158 ts('Online Contribution Page'),
159 array(
160 '' => ts('- select -'),
161 ) +
162 CRM_Contribute_PseudoConstant::contributionPage()
163 );
164
165 $form->add('textarea', 'note', ts('Notes'), array("rows" => 4, "cols" => 60));
166
167 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
168 if ($form->_id && $form->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
169 $netAmount->freeze();
170 $feeAmount->freeze();
171 }
172
173 }
174
175 /**
176 * used by CRM/Pledge/Form/Pledge.php
177 *
178 * Build the form object for PaymentReminders Information.
179 *
180 *
181 * @param CRM_Core_Form $form
182 *
183 * @return void
184 */
185 public static function buildPaymentReminders(&$form) {
186 //PaymentReminders section
187 $form->add('hidden', 'hidden_PaymentReminders', 1);
188 $form->add('text', 'initial_reminder_day', ts('Send Initial Reminder'), array('size' => 3));
189 $form->addRule('initial_reminder_day', ts('Please enter a valid reminder day.'), 'positiveInteger');
190 $form->add('text', 'max_reminders', ts('Send up to'), array('size' => 3));
191 $form->addRule('max_reminders', ts('Please enter a valid No. of reminders.'), 'positiveInteger');
192 $form->add('text', 'additional_reminder_day', ts('Send additional reminders'), array('size' => 3));
193 $form->addRule('additional_reminder_day', ts('Please enter a valid additional reminder day.'), 'positiveInteger');
194 }
195
196 /**
197 * Process the Premium Information.
198 *
199 * @param array $params
200 * @param int $contributionID
201 * @param int $premiumID
202 * @param array $options
203 */
204 public static function processPremium($params, $contributionID, $premiumID = NULL, $options = array()) {
205 $selectedProductID = $params['product_name'][0];
206 $selectedProductOptionID = $params['product_name'][1];
207
208 $dao = new CRM_Contribute_DAO_ContributionProduct();
209 $dao->contribution_id = $contributionID;
210 $dao->product_id = $selectedProductID;
211 $dao->fulfilled_date = CRM_Utils_Date::processDate($params['fulfilled_date'], NULL, TRUE);
212 $isDeleted = FALSE;
213
214 //CRM-11106
215 $premiumParams = array(
216 'id' => $selectedProductID,
217 );
218
219 $productDetails = array();
220 CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
221 $dao->financial_type_id = CRM_Utils_Array::value('financial_type_id', $productDetails);
222 if (!empty($options[$selectedProductID])) {
223 $dao->product_option = $options[$selectedProductID][$selectedProductOptionID];
224 }
225 if ($premiumID) {
226 $ContributionProduct = new CRM_Contribute_DAO_ContributionProduct();
227 $ContributionProduct->id = $premiumID;
228 $ContributionProduct->find(TRUE);
229 if ($ContributionProduct->product_id == $selectedProductID) {
230 $dao->id = $premiumID;
231 }
232 else {
233 $ContributionProduct->delete();
234 $isDeleted = TRUE;
235 }
236 }
237
238 $dao->save();
239 //CRM-11106
240 if ($premiumID == NULL || $isDeleted) {
241 $premiumParams = array(
242 'cost' => CRM_Utils_Array::value('cost', $productDetails),
243 'currency' => CRM_Utils_Array::value('currency', $productDetails),
244 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
245 'contributionId' => $contributionID,
246 );
247 if ($isDeleted) {
248 $premiumParams['oldPremium']['product_id'] = $ContributionProduct->product_id;
249 $premiumParams['oldPremium']['contribution_id'] = $ContributionProduct->contribution_id;
250 }
251 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($premiumParams);
252 }
253 }
254
255 /**
256 * Process the Note.
257 *
258 *
259 * @param array $params
260 * @param int $contactID
261 * @param int $contributionID
262 * @param int $contributionNoteID
263 *
264 * @return void
265 */
266 public static function processNote(&$params, $contactID, $contributionID, $contributionNoteID = NULL) {
267 //process note
268 $noteParams = array(
269 'entity_table' => 'civicrm_contribution',
270 'note' => $params['note'],
271 'entity_id' => $contributionID,
272 'contact_id' => $contactID,
273 );
274 $noteID = array();
275 if ($contributionNoteID) {
276 $noteID = array("id" => $contributionNoteID);
277 $noteParams['note'] = $noteParams['note'] ? $noteParams['note'] : "null";
278 }
279 CRM_Core_BAO_Note::add($noteParams, $noteID);
280 }
281
282 /**
283 * Process the Common data.
284 *
285 *
286 * @param array $params
287 * @param $formatted
288 * @param CRM_Core_Form $form
289 * @return void
290 */
291 public static function postProcessCommon(&$params, &$formatted, &$form) {
292 $fields = array(
293 'non_deductible_amount',
294 'total_amount',
295 'fee_amount',
296 'net_amount',
297 'trxn_id',
298 'invoice_id',
299 'creditnote_id',
300 'campaign_id',
301 'contribution_page_id',
302 );
303 foreach ($fields as $f) {
304 $formatted[$f] = CRM_Utils_Array::value($f, $params);
305 }
306
307 if (!empty($params['thankyou_date']) && !CRM_Utils_System::isNull($params['thankyou_date'])) {
308 $formatted['thankyou_date'] = CRM_Utils_Date::processDate($params['thankyou_date'], $params['thankyou_date_time']);
309 }
310 else {
311 $formatted['thankyou_date'] = 'null';
312 }
313
314 if (!empty($params['is_email_receipt'])) {
315 $params['receipt_date'] = $formatted['receipt_date'] = date('YmdHis');
316 }
317
318 //special case to handle if all checkboxes are unchecked
319 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution',
320 FALSE,
321 FALSE,
322 CRM_Utils_Array::value('financial_type_id',
323 $params
324 )
325 );
326 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
327 $customFields,
328 CRM_Utils_Array::value('id', $params, NULL),
329 'Contribution'
330 );
331 }
332
333 /**
334 * Send email receipt.
335 *
336 * @param CRM_Core_Form $form
337 * instance of Contribution form.
338 * @param array $params
339 * (reference ) an assoc array of name/value pairs.
340 * @param bool $ccContribution
341 * is it credit card contribution.
342 *
343 * @return array
344 */
345 public static function emailReceipt(&$form, &$params, $ccContribution = FALSE) {
346 $form->assign('receiptType', 'contribution');
347 // Retrieve Financial Type Name from financial_type_id
348 $params['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
349 $params['financial_type_id']);
350 if (!empty($params['payment_instrument_id'])) {
351 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
352 $params['paidBy'] = $paymentInstrument[$params['payment_instrument_id']];
353 }
354
355 // retrieve individual prefix value for honoree
356 if (isset($params['soft_credit'])) {
357 $softCreditTypes = $softCredits = array();
358 foreach ($params['soft_credit'] as $key => $softCredit) {
359 $softCredits[$key] = array(
360 'Name' => $softCredit['contact_name'],
361 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
362 );
363 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
364 }
365 $form->assign('softCreditTypes', $softCreditTypes);
366 $form->assign('softCredits', $softCredits);
367 }
368
369 // retrieve premium product name and assigned fulfilled
370 // date to template
371 if (!empty($params['hidden_Premium'])) {
372 if (isset($params['product_name']) &&
373 is_array($params['product_name']) &&
374 !empty($params['product_name'])
375 ) {
376 $productDAO = new CRM_Contribute_DAO_Product();
377 $productDAO->id = $params['product_name'][0];
378 $productDAO->find(TRUE);
379 $params['product_name'] = $productDAO->name;
380 $params['product_sku'] = $productDAO->sku;
381
382 if (empty($params['product_option']) && !empty($form->_options[$params['product_name'][0]])) {
383 $params['product_option'] = $form->_options[$params['product_name'][0]][$params['product_name'][1]];
384 }
385 }
386
387 if (!empty($params['fulfilled_date'])) {
388 $form->assign('fulfilled_date', CRM_Utils_Date::processDate($params['fulfilled_date']));
389 }
390 }
391
392 $form->assign('ccContribution', $ccContribution);
393 if ($ccContribution) {
394 //build the name.
395 $name = CRM_Utils_Array::value('billing_first_name', $params);
396 if (!empty($params['billing_middle_name'])) {
397 $name .= " {$params['billing_middle_name']}";
398 }
399 $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $params);
400 $name = trim($name);
401 $form->assign('billingName', $name);
402
403 //assign the address formatted up for display
404 $addressParts = array(
405 "street_address" => "billing_street_address-{$form->_bltID}",
406 "city" => "billing_city-{$form->_bltID}",
407 "postal_code" => "billing_postal_code-{$form->_bltID}",
408 "state_province" => "state_province-{$form->_bltID}",
409 "country" => "country-{$form->_bltID}",
410 );
411
412 $addressFields = array();
413 foreach ($addressParts as $name => $field) {
414 $addressFields[$name] = CRM_Utils_Array::value($field, $params);
415 }
416 $form->assign('address', CRM_Utils_Address::format($addressFields));
417
418 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
419 $date = CRM_Utils_Date::mysqlToIso($date);
420 $form->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params));
421 $form->assign('credit_card_exp_date', $date);
422 $form->assign('credit_card_number',
423 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
424 );
425 }
426 else {
427 //offline contribution
428 // assigned various dates to the templates
429 $form->assign('receipt_date', CRM_Utils_Date::processDate($params['receipt_date']));
430
431 if (!empty($params['cancel_date'])) {
432 $form->assign('cancel_date', CRM_Utils_Date::processDate($params['cancel_date']));
433 }
434 if (!empty($params['thankyou_date'])) {
435 $form->assign('thankyou_date', CRM_Utils_Date::processDate($params['thankyou_date']));
436 }
437 if ($form->_action & CRM_Core_Action::UPDATE) {
438 $form->assign('lineItem', empty($form->_lineItems) ? FALSE : $form->_lineItems);
439 }
440 }
441
442 //handle custom data
443 if (!empty($params['hidden_custom'])) {
444 $contribParams = array(array('contribution_id', '=', $params['contribution_id'], 0, 0));
445 if ($form->_mode == 'test') {
446 $contribParams[] = array('contribution_test', '=', 1, 0, 0);
447 }
448
449 //retrieve custom data
450 $customGroup = array();
451
452 foreach ($form->_groupTree as $groupID => $group) {
453 $customFields = $customValues = array();
454 if ($groupID == 'info') {
455 continue;
456 }
457 foreach ($group['fields'] as $k => $field) {
458 $field['title'] = $field['label'];
459 $customFields["custom_{$k}"] = $field;
460 }
461
462 //build the array of customgroup contain customfields.
463 CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $contribParams);
464 $customGroup[$group['title']] = $customValues;
465 }
466 //assign all custom group and corresponding fields to template.
467 $form->assign('customGroup', $customGroup);
468 }
469
470 $form->assign_by_ref('formValues', $params);
471 list($contributorDisplayName,
472 $contributorEmail
473 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
474 $form->assign('contactID', $params['contact_id']);
475 $form->assign('contributionID', $params['contribution_id']);
476
477 if (!empty($params['currency'])) {
478 $form->assign('currency', $params['currency']);
479 }
480
481 if (!empty($params['receive_date'])) {
482 $form->assign('receive_date', CRM_Utils_Date::processDate($params['receive_date']));
483 }
484
485 $template = CRM_Core_Smarty::singleton();
486 $taxAmt = $template->get_template_vars('dataArray');
487 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
488 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
489 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
490 if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
491 $isEmailPdf = TRUE;
492 }
493 else {
494 $isEmailPdf = FALSE;
495 }
496
497 list($sendReceipt, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
498 array(
499 'groupName' => 'msg_tpl_workflow_contribution',
500 'valueName' => 'contribution_offline_receipt',
501 'contactId' => $params['contact_id'],
502 'contributionId' => $params['contribution_id'],
503 'from' => $params['from_email_address'],
504 'toName' => $contributorDisplayName,
505 'toEmail' => $contributorEmail,
506 'isTest' => $form->_mode == 'test',
507 'PDFFilename' => ts('receipt') . '.pdf',
508 'isEmailPdf' => $isEmailPdf,
509 )
510 );
511
512 return $sendReceipt;
513 }
514
515 }