Merge pull request #21280 from civicrm/5.41
[civicrm-core.git] / CRM / Contribute / Form / AdditionalInfo.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Contribute_Form_AdditionalInfo {
18
19 /**
20 * Build the form object for Premium Information.
21 *
22 * Called from the CRM_Contribute_Form_Contribute function and seemingly nowhere else.
23 *
24 * Probably this should be on the form that uses it since it is not used on multiple forms.
25 *
26 * Putting it on this class doesn't seem to reduce complexity.
27 *
28 * @param CRM_Core_Form $form
29 */
30 public static function buildPremium($form) {
31 //premium section
32 $form->add('hidden', 'hidden_Premium', 1);
33 $sel1 = $sel2 = [];
34
35 $dao = new CRM_Contribute_DAO_Product();
36 $dao->is_active = 1;
37 $dao->find();
38 $min_amount = [];
39 $sel1[0] = ts('-select product-');
40 while ($dao->fetch()) {
41 $sel1[$dao->id] = $dao->name . " ( " . $dao->sku . " )";
42 $min_amount[$dao->id] = $dao->min_contribution;
43 $options = explode(',', $dao->options);
44 foreach ($options as $k => $v) {
45 $options[$k] = trim($v);
46 }
47 if ($options[0] != '') {
48 $sel2[$dao->id] = $options;
49 }
50 $form->assign('premiums', TRUE);
51 }
52 $form->_options = $sel2;
53 $form->assign('mincontribution', $min_amount);
54 $sel = &$form->addElement('hierselect', "product_name", ts('Premium'), 'onclick="showMinContrib();"');
55 $js = "<script type='text/javascript'>\n";
56 $formName = 'document.forms.' . $form->getName();
57
58 for ($k = 1; $k < 2; $k++) {
59 if (!isset($defaults['product_name'][$k]) || (!$defaults['product_name'][$k])) {
60 $js .= "{$formName}['product_name[$k]'].style.display = 'none';\n";
61 }
62 }
63
64 $sel->setOptions([$sel1, $sel2]);
65 $js .= "</script>\n";
66 $form->assign('initHideBoxes', $js);
67
68 $form->add('datepicker', 'fulfilled_date', ts('Fulfilled'), [], FALSE, ['time' => FALSE]);
69 $form->addElement('text', 'min_amount', ts('Minimum Contribution Amount'));
70 }
71
72 /**
73 * Build the form object for Additional Details.
74 *
75 * @param CRM_Core_Form $form
76 */
77 public static function buildAdditionalDetail(&$form) {
78 //Additional information section
79 $form->add('hidden', 'hidden_AdditionalDetail', 1);
80
81 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
82
83 $form->addField('thankyou_date', ['entity' => 'contribution'], FALSE, FALSE);
84
85 // add various amounts
86 $nonDeductAmount = &$form->add('text', 'non_deductible_amount', ts('Non-deductible Amount'),
87 $attributes['non_deductible_amount']
88 );
89 $form->addRule('non_deductible_amount', ts('Please enter a valid monetary value for Non-deductible Amount.'), 'money');
90
91 if ($form->_online) {
92 $nonDeductAmount->freeze();
93 }
94 $feeAmount = &$form->add('text', 'fee_amount', ts('Fee Amount'),
95 $attributes['fee_amount']
96 );
97 $form->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
98 if ($form->_online) {
99 $feeAmount->freeze();
100 }
101
102 $element = &$form->add('text', 'invoice_id', ts('Invoice ID'),
103 $attributes['invoice_id']
104 );
105 if ($form->_online) {
106 $element->freeze();
107 }
108 else {
109 $form->addRule('invoice_id',
110 ts('This Invoice ID already exists in the database.'),
111 'objectExists',
112 ['CRM_Contribute_DAO_Contribution', $form->_id, 'invoice_id']
113 );
114 }
115 $element = $form->add('text', 'creditnote_id', ts('Credit Note ID'),
116 $attributes['creditnote_id']
117 );
118 if ($form->_online) {
119 $element->freeze();
120 }
121 else {
122 $form->addRule('creditnote_id',
123 ts('This Credit Note ID already exists in the database.'),
124 'objectExists',
125 ['CRM_Contribute_DAO_Contribution', $form->_id, 'creditnote_id']
126 );
127 }
128
129 $form->add('select', 'contribution_page_id',
130 ts('Online Contribution Page'),
131 [
132 '' => ts('- select -'),
133 ] +
134 CRM_Contribute_PseudoConstant::contributionPage()
135 );
136
137 $form->add('textarea', 'note', ts('Notes'), ["rows" => 4, "cols" => 60]);
138
139 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
140 if ($form->_id && $form->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
141 $feeAmount->freeze();
142 }
143
144 }
145
146 /**
147 * used by CRM/Pledge/Form/Pledge.php
148 *
149 * Build the form object for PaymentReminders Information.
150 *
151 * @param CRM_Core_Form $form
152 */
153 public static function buildPaymentReminders(&$form) {
154 //PaymentReminders section
155 $form->add('hidden', 'hidden_PaymentReminders', 1);
156 $form->add('text', 'initial_reminder_day', ts('Send Initial Reminder'), ['size' => 3]);
157 $form->addRule('initial_reminder_day', ts('Please enter a valid reminder day.'), 'positiveInteger');
158 $form->add('text', 'max_reminders', ts('Send up to'), ['size' => 3]);
159 $form->addRule('max_reminders', ts('Please enter a valid No. of reminders.'), 'positiveInteger');
160 $form->add('text', 'additional_reminder_day', ts('Send additional reminders'), ['size' => 3]);
161 $form->addRule('additional_reminder_day', ts('Please enter a valid additional reminder day.'), 'positiveInteger');
162 }
163
164 /**
165 * Process the Premium Information.
166 *
167 * @param array $params
168 * @param int $contributionID
169 * @param int $premiumID
170 * @param array $options
171 */
172 public static function processPremium($params, $contributionID, $premiumID = NULL, $options = []) {
173 $selectedProductID = $params['product_name'][0];
174 $selectedProductOptionID = $params['product_name'][1] ?? NULL;
175
176 $dao = new CRM_Contribute_DAO_ContributionProduct();
177 $dao->contribution_id = $contributionID;
178 $dao->product_id = $selectedProductID;
179 $dao->fulfilled_date = $params['fulfilled_date'];
180 $isDeleted = FALSE;
181
182 //CRM-11106
183 $premiumParams = [
184 'id' => $selectedProductID,
185 ];
186
187 $productDetails = [];
188 CRM_Contribute_BAO_Product::retrieve($premiumParams, $productDetails);
189 $dao->financial_type_id = $productDetails['financial_type_id'] ?? NULL;
190 if (!empty($options[$selectedProductID])) {
191 $dao->product_option = $options[$selectedProductID][$selectedProductOptionID];
192 }
193 if ($premiumID) {
194 $ContributionProduct = new CRM_Contribute_DAO_ContributionProduct();
195 $ContributionProduct->id = $premiumID;
196 $ContributionProduct->find(TRUE);
197 if ($ContributionProduct->product_id == $selectedProductID) {
198 $dao->id = $premiumID;
199 }
200 else {
201 $ContributionProduct->delete();
202 $isDeleted = TRUE;
203 }
204 }
205
206 $dao->save();
207 //CRM-11106
208 if ($premiumID == NULL || $isDeleted) {
209 $premiumParams = [
210 'cost' => $productDetails['cost'] ?? NULL,
211 'currency' => $productDetails['currency'] ?? NULL,
212 'financial_type_id' => $productDetails['financial_type_id'] ?? NULL,
213 'contributionId' => $contributionID,
214 ];
215 if ($isDeleted) {
216 $premiumParams['oldPremium']['product_id'] = $ContributionProduct->product_id;
217 $premiumParams['oldPremium']['contribution_id'] = $ContributionProduct->contribution_id;
218 }
219 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($premiumParams);
220 }
221 }
222
223 /**
224 * Process the Note.
225 *
226 *
227 * @param array $params
228 * @param int $contactID
229 * @param int $contributionID
230 * @param int $contributionNoteID
231 */
232 public static function processNote($params, $contactID, $contributionID, $contributionNoteID = NULL) {
233 if (CRM_Utils_System::isNull($params['note']) && $contributionNoteID) {
234 CRM_Core_BAO_Note::deleteRecord(['id' => $contributionNoteID]);
235 $status = ts('Selected Note has been deleted successfully.');
236 CRM_Core_Session::setStatus($status, ts('Deleted'), 'success');
237 return;
238 }
239 //process note
240 $noteParams = [
241 'entity_table' => 'civicrm_contribution',
242 'note' => $params['note'],
243 'entity_id' => $contributionID,
244 'contact_id' => $contactID,
245 ];
246 $noteID = [];
247 if ($contributionNoteID) {
248 $noteID = ["id" => $contributionNoteID];
249 $noteParams['note'] = $noteParams['note'] ? $noteParams['note'] : "null";
250 }
251 CRM_Core_BAO_Note::add($noteParams, $noteID);
252 }
253
254 /**
255 * Process the Common data.
256 *
257 * @param array $params
258 * @param array $formatted
259 * @param CRM_Core_Form $form
260 */
261 public static function postProcessCommon(&$params, &$formatted, &$form) {
262 $fields = [
263 'non_deductible_amount',
264 'total_amount',
265 'fee_amount',
266 'trxn_id',
267 'invoice_id',
268 'creditnote_id',
269 'campaign_id',
270 'contribution_page_id',
271 ];
272 foreach ($fields as $f) {
273 $formatted[$f] = $params[$f] ?? NULL;
274 }
275
276 if (!empty($params['thankyou_date'])) {
277 $formatted['thankyou_date'] = CRM_Utils_Date::processDate($params['thankyou_date']);
278 }
279 else {
280 $formatted['thankyou_date'] = 'null';
281 }
282
283 if (!empty($params['is_email_receipt'])) {
284 $params['receipt_date'] = $formatted['receipt_date'] = date('YmdHis');
285 }
286
287 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
288 $params['id'] ?? NULL,
289 'Contribution'
290 );
291 }
292
293 /**
294 * Send email receipt.
295 *
296 * @param \CRM_Core_Form $form
297 * instance of Contribution form.
298 * @param array $params
299 * (reference ) an assoc array of name/value pairs.
300 * @param bool $ccContribution
301 * is it credit card contribution.
302 *
303 * @return array
304 * @throws \CRM_Core_Exception
305 */
306 public static function emailReceipt(&$form, &$params, $ccContribution = FALSE) {
307 $form->assign('receiptType', 'contribution');
308 // Retrieve Financial Type Name from financial_type_id
309 $params['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
310 $params['financial_type_id']);
311 if (!empty($params['payment_instrument_id'])) {
312 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
313 $params['paidBy'] = $paymentInstrument[$params['payment_instrument_id']];
314 if ($params['paidBy'] != 'Check' && isset($params['check_number'])) {
315 unset($params['check_number']);
316 }
317 }
318
319 // retrieve individual prefix value for honoree
320 if (isset($params['soft_credit'])) {
321 $softCreditTypes = $softCredits = [];
322 foreach ($params['soft_credit'] as $key => $softCredit) {
323 $softCredits[$key] = [
324 'Name' => $softCredit['contact_name'],
325 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
326 ];
327 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
328 }
329 $form->assign('softCreditTypes', $softCreditTypes);
330 $form->assign('softCredits', $softCredits);
331 }
332
333 // retrieve premium product name and assigned fulfilled
334 // date to template
335 if (!empty($params['hidden_Premium'])) {
336 if (isset($params['product_name']) &&
337 is_array($params['product_name']) &&
338 !empty($params['product_name'])
339 ) {
340 $productDAO = new CRM_Contribute_DAO_Product();
341 $productDAO->id = $params['product_name'][0];
342 $productOptionID = $params['product_name'][1];
343 $productDAO->find(TRUE);
344 $params['product_name'] = $productDAO->name;
345 $params['product_sku'] = $productDAO->sku;
346
347 if (empty($params['product_option']) && !empty($form->_options[$productDAO->id])) {
348 $params['product_option'] = $form->_options[$productDAO->id][$productOptionID];
349 }
350 }
351 if (!empty($params['fulfilled_date'])) {
352 $form->assign('fulfilled_date', $params['fulfilled_date']);
353 }
354 }
355
356 $form->assign('ccContribution', $ccContribution);
357 if ($ccContribution) {
358 $form->assignBillingName($params);
359 $form->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
360 $params,
361 $form->_bltID
362 ));
363
364 $valuesForForm = CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params);
365 $form->assignVariables($valuesForForm, ['credit_card_exp_date', 'credit_card_type', 'credit_card_number']);
366 }
367 else {
368 //offline contribution
369 // assigned various dates to the templates
370 $form->assign('receipt_date', CRM_Utils_Date::processDate($params['receipt_date']));
371
372 if (!empty($params['cancel_date'])) {
373 $form->assign('cancel_date', CRM_Utils_Date::processDate($params['cancel_date']));
374 }
375 if (!empty($params['thankyou_date'])) {
376 $form->assign('thankyou_date', CRM_Utils_Date::processDate($params['thankyou_date']));
377 }
378 if ($form->_action & CRM_Core_Action::UPDATE) {
379 $form->assign('lineItem', empty($form->_lineItems) ? FALSE : $form->_lineItems);
380 }
381 }
382
383 //handle custom data
384 if (!empty($params['hidden_custom'])) {
385 $contribParams = [['contribution_id', '=', $params['contribution_id'], 0, 0]];
386 if ($form->_mode == 'test') {
387 $contribParams[] = ['contribution_test', '=', 1, 0, 0];
388 }
389
390 //retrieve custom data
391 $customGroup = [];
392
393 foreach ($form->_groupTree as $groupID => $group) {
394 $customFields = $customValues = [];
395 if ($groupID == 'info') {
396 continue;
397 }
398 foreach ($group['fields'] as $k => $field) {
399 $field['title'] = $field['label'];
400 $customFields["custom_{$k}"] = $field;
401 }
402
403 //build the array of customgroup contain customfields.
404 CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $contribParams);
405 $customGroup[$group['title']] = $customValues;
406 }
407 //assign all custom group and corresponding fields to template.
408 $form->assign('customGroup', $customGroup);
409 }
410
411 $form->assign_by_ref('formValues', $params);
412 list($contributorDisplayName,
413 $contributorEmail
414 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
415 $form->assign('contactID', $params['contact_id']);
416 $form->assign('contributionID', $params['contribution_id']);
417
418 if (!empty($params['currency'])) {
419 $form->assign('currency', $params['currency']);
420 }
421
422 if (!empty($params['receive_date'])) {
423 $form->assign('receive_date', CRM_Utils_Date::processDate($params['receive_date']));
424 }
425
426 [$sendReceipt] = CRM_Core_BAO_MessageTemplate::sendTemplate(
427 [
428 'groupName' => 'msg_tpl_workflow_contribution',
429 'valueName' => 'contribution_offline_receipt',
430 'contactId' => $params['contact_id'],
431 'contributionId' => $params['contribution_id'],
432 'from' => $params['from_email_address'],
433 'toName' => $contributorDisplayName,
434 'toEmail' => $contributorEmail,
435 'isTest' => $form->_mode == 'test',
436 'PDFFilename' => ts('receipt') . '.pdf',
437 'isEmailPdf' => Civi::settings()->get('invoice_is_email_pdf'),
438 ]
439 );
440
441 return $sendReceipt;
442 }
443
444 }