Merge pull request #17833 from totten/master-website-test
[civicrm-core.git] / ext / eventcart / CRM / Event / Cart / Form / Checkout / Payment.php
1 <?php
2
3 /**
4 * Class CRM_Event_Cart_Form_Checkout_Payment
5 */
6 class CRM_Event_Cart_Form_Checkout_Payment extends CRM_Event_Cart_Form_Cart {
7 public $all_participants;
8 public $financial_type_id;
9 public $description;
10 public $line_items;
11 public $_fields = [];
12 public $_paymentProcessor;
13 public $total;
14 public $sub_total;
15 public $payment_required = TRUE;
16 public $payer_contact_id;
17 public $is_pay_later = FALSE;
18 public $pay_later_receipt;
19
20 /**
21 * @var array
22 */
23 protected $_values = [];
24
25 /**
26 * Register a participant.
27 *
28 * @param array $params
29 * @param CRM_Event_BAO_Participant $participant
30 * @param CRM_Event_BAO_Event $event
31 *
32 * @return mixed
33 * @throws \CiviCRM_API3_Exception
34 */
35 public function registerParticipant($params, &$participant, $event) {
36 $participantParams = [
37 'id' => $participant->id,
38 'event_id' => $event->id,
39 'register_date' => date('YmdHis'),
40 'source' => CRM_Utils_Array::value('participant_source', $params, $this->description),
41 'is_pay_later' => $this->is_pay_later,
42 'fee_amount' => CRM_Utils_Array::value('amount', $params, 0),
43 'fee_currency' => $params['currencyID'] ?? NULL,
44 ];
45
46 if ($participant->must_wait) {
47 $participant_status = 'On waitlist';
48 }
49 elseif (!empty($params['is_pay_later'])) {
50 $participant_status = 'Pending from pay later';
51 }
52 else {
53 $participant_status = 'Registered';
54 }
55 $participantParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', $participant_status);
56 $participantParams['participant_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Event_BAO_Participant', 'status_id', $participantParams['status_id']);
57
58 $this->assign('isOnWaitlist', $participant->must_wait);
59
60 $participantParams['is_test'] = 0;
61 if ($this->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
62 $participantParams['is_test'] = 1;
63 }
64
65 $transaction = new CRM_Core_Transaction();
66
67 $participant->copyValues($participantParams);
68 $participant->save();
69
70 if (!empty($params['contributionID'])) {
71 $participantPaymentParams = [
72 'participant_id' => $participant->id,
73 'contribution_id' => $params['contributionID'],
74 ];
75 civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
76 }
77
78 $transaction->commit();
79
80 $event_values = [];
81 CRM_Core_DAO::storeValues($event, $event_values);
82
83 $location = [];
84 if (CRM_Utils_Array::value('is_show_location', $event_values) == 1) {
85 $locationParams = [
86 'entity_id' => $participant->event_id,
87 'entity_table' => 'civicrm_event',
88 ];
89 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
90 CRM_Core_BAO_Address::fixAddress($location['address'][1]);
91 }
92
93 list($pre_id, $post_id) = CRM_Event_Cart_Form_MerParticipant::get_profile_groups($participant->event_id);
94 $payer_values = [
95 'email' => '',
96 'name' => '',
97 ];
98 if ($this->payer_contact_id) {
99 $payer_contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
100 $payer_values = [
101 'email' => $payer_contact_details[1],
102 'name' => $payer_contact_details[0],
103 ];
104 }
105 $values = [
106 'params' => [$participant->id => $participantParams],
107 'event' => $event_values,
108 'location' => $location,
109 'custom_pre_id' => $pre_id,
110 'custom_post_id' => $post_id,
111 'payer' => $payer_values,
112 ];
113 CRM_Event_BAO_Event::sendMail($participant->contact_id, $values, $participant->id);
114
115 return $participant;
116 }
117
118 /**
119 * Build payment fields.
120 */
121 public function buildPaymentFields() {
122 $payment_processor_id = NULL;
123 $can_pay_later = TRUE;
124 $pay_later_text = "";
125 $this->pay_later_receipt = "";
126 foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
127 if ($payment_processor_id === NULL && $event_in_cart->event->payment_processor !== NULL) {
128 $payment_processor_id = $event_in_cart->event->payment_processor;
129 $this->financial_type_id = $event_in_cart->event->financial_type_id;
130 $this->_values['currency'] = $event_in_cart->event->currency;
131 }
132 else {
133 if ($event_in_cart->event->payment_processor !== NULL && $event_in_cart->event->payment_processor !== $payment_processor_id) {
134 CRM_Core_Error::statusBounce(ts('When registering for multiple events all events must use the same payment processor. '));
135 }
136 }
137 if ($payment_processor_id) {
138 $can_pay_later = FALSE;
139 }
140 elseif ($event_in_cart->event->is_pay_later) {
141 //XXX
142 $pay_later_text = $event_in_cart->event->pay_later_text;
143 $this->pay_later_receipt = $event_in_cart->event->pay_later_receipt;
144 }
145 else {
146 CRM_Core_Error::statusBounce(ts('A payment processor must be selected for this event registration page, or the event must be configured to give users the option to pay later (contact the site administrator for assistance).'));
147 }
148 }
149
150 if ($can_pay_later) {
151 $this->addElement('checkbox', 'is_pay_later', $pay_later_text);
152 $this->addElement('checkbox', 'payment_completed', ts('Payment Completed'));
153 $this->assign('pay_later_instructions', $this->pay_later_receipt);
154 }
155 else {
156 $this->_paymentProcessorIDs = [$payment_processor_id];
157 $this->assignPaymentProcessor(FALSE);
158 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, FALSE);
159 }
160 $this->assign('currency', $this->getCurrency());
161 }
162
163 /**
164 * Build QuickForm.
165 */
166 public function buildQuickForm() {
167 $this->line_items = [];
168 $this->sub_total = 0;
169 $this->_price_values = $this->getValuesForPage('ParticipantsAndPrices');
170
171 // iterate over each event in cart
172 foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
173 $this->process_event_line_item($event_in_cart);
174 foreach ($this->cart->get_events_in_carts_by_main_event_id($event_in_cart->event_id) as $subevent) {
175 $this->process_event_line_item($subevent, 'subevent');
176 }
177 }
178
179 $this->total = $this->sub_total;
180 $this->payment_required = ($this->total > 0);
181 $this->assign('payment_required', $this->payment_required);
182 $this->assign('line_items', $this->line_items);
183 $this->assign('sub_total', $this->sub_total);
184 $this->assign('total', $this->total);
185 $buttons = [];
186 $buttons[] = [
187 'name' => ts('Go Back'),
188 'type' => 'back',
189 ];
190 $buttons[] = [
191 'isDefault' => TRUE,
192 'name' => ts('Complete Transaction'),
193 'type' => 'next',
194 ];
195
196 if ($this->total) {
197 $this->add('text', 'billing_contact_email', 'Billing Email', '', TRUE);
198 $this->assign('collect_billing_email', TRUE);
199 }
200
201 $this->addButtons($buttons);
202 $this->addFormRule(['CRM_Event_Cart_Form_Checkout_Payment', 'formRule'], $this);
203
204 if ($this->payment_required) {
205 $this->buildPaymentFields();
206 }
207 }
208
209 /**
210 * Process line item for event.
211 *
212 * @param bool $event_in_cart
213 * @param string $class
214 */
215 public function process_event_line_item(&$event_in_cart, $class = NULL) {
216 $cost = 0;
217 $price_set_id = CRM_Price_BAO_PriceSet::getFor("civicrm_event", $event_in_cart->event_id);
218 $amount_level = NULL;
219 if ($price_set_id) {
220 $event_price_values = [];
221 foreach ($this->_price_values as $key => $value) {
222 if (preg_match("/event_{$event_in_cart->event_id}_(price.*)/", $key, $matches)) {
223 $event_price_values[$matches[1]] = $value;
224 }
225 }
226 $price_sets = CRM_Price_BAO_PriceSet::getSetDetail($price_set_id, TRUE);
227 $price_set = $price_sets[$price_set_id];
228 $price_set_amount = [];
229 CRM_Price_BAO_PriceSet::processAmount($price_set['fields'], $event_price_values, $price_set_amount);
230 if (!empty($this->_price_values['discountcode'])) {
231 $ret = $this->apply_discount($this->_price_values['discountcode'], $price_set_amount, $cost, $event_in_cart->event_id);
232 if ($ret == FALSE) {
233 $cost = $event_price_values['amount'];
234 }
235 }
236 else {
237 $cost = $event_price_values['amount'];
238 }
239 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
240 // function to get correct amount level consistently. Remove setting of the amount level in
241 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
242 // to cover all variants.
243 $amount_level = $event_price_values['amount_level'];
244 $price_details[$price_set_id] = $price_set_amount;
245 }
246
247 // iterate over each participant in event
248 foreach ($event_in_cart->participants as & $participant) {
249 $participant->cost = $cost;
250 $participant->fee_level = $amount_level;
251 $participant->price_details = $price_details;
252 }
253
254 $this->add_line_item($event_in_cart, $class);
255 }
256
257 /**
258 * Add line item.
259 *
260 * @param CRM_Event_BAO_Event $event_in_cart
261 * @param string $class
262 */
263 public function add_line_item($event_in_cart, $class = NULL) {
264 $amount = 0;
265 $cost = 0;
266 $not_waiting_participants = [];
267 foreach ($event_in_cart->not_waiting_participants() as $participant) {
268 $amount += $participant->cost;
269 $cost = max($cost, $participant->cost);
270 $not_waiting_participants[] = [
271 'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
272 ];
273 }
274 $waiting_participants = [];
275 foreach ($event_in_cart->waiting_participants() as $participant) {
276 $waiting_participants[] = [
277 'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
278 ];
279 }
280 $this->line_items[] = [
281 'amount' => $amount,
282 'cost' => $cost,
283 'event' => $event_in_cart->event,
284 'participants' => $not_waiting_participants,
285 'num_participants' => count($not_waiting_participants),
286 'num_waiting_participants' => count($waiting_participants),
287 'waiting_participants' => $waiting_participants,
288 'class' => $class,
289 ];
290
291 $this->sub_total += $amount;
292 }
293
294 /**
295 * Send email receipt.
296 *
297 * @param array $events_in_cart
298 * @param array $params
299 */
300 public function emailReceipt($events_in_cart, $params) {
301 $contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
302 $state_province = new CRM_Core_DAO_StateProvince();
303 $state_province->id = $params["billing_state_province_id-{$this->_bltID}"];
304 $state_province->find();
305 $state_province->fetch();
306 $country = new CRM_Core_DAO_Country();
307 $country->id = $params["billing_country_id-{$this->_bltID}"];
308 $country->find();
309 $country->fetch();
310 foreach ($this->line_items as & $line_item) {
311 $location_params = ['entity_id' => $line_item['event']->id, 'entity_table' => 'civicrm_event'];
312 $line_item['location'] = CRM_Core_BAO_Location::getValues($location_params, TRUE);
313 CRM_Core_BAO_Address::fixAddress($line_item['location']['address'][1]);
314 }
315 $send_template_params = [
316 'table' => 'civicrm_msg_template',
317 'contactId' => $this->payer_contact_id,
318 'from' => current(CRM_Core_BAO_Domain::getNameAndEmail(TRUE, TRUE)),
319 'groupName' => 'msg_tpl_workflow_event',
320 'isTest' => FALSE,
321 'toEmail' => $contact_details[1],
322 'toName' => $contact_details[0],
323 'tplParams' => [
324 'billing_name' => "{$params['billing_first_name']} {$params['billing_last_name']}",
325 'billing_city' => $params["billing_city-{$this->_bltID}"],
326 'billing_country' => $country->name,
327 'billing_postal_code' => $params["billing_postal_code-{$this->_bltID}"],
328 'billing_state' => $state_province->abbreviation,
329 'billing_street_address' => $params["billing_street_address-{$this->_bltID}"],
330 'credit_card_exp_date' => $params['credit_card_exp_date'],
331 'credit_card_type' => $params['credit_card_type'],
332 'credit_card_number' => "************" . substr($params['credit_card_number'], -4, 4),
333 // XXX cart->get_discounts
334 'discounts' => $this->discounts,
335 'email' => $contact_details[1],
336 'events_in_cart' => $events_in_cart,
337 'line_items' => $this->line_items,
338 'name' => $contact_details[0],
339 'transaction_id' => $params['trxn_id'],
340 'transaction_date' => $params['trxn_date'],
341 'is_pay_later' => $this->is_pay_later,
342 'pay_later_receipt' => $this->pay_later_receipt,
343 ],
344 'valueName' => 'event_registration_receipt',
345 'PDFFilename' => ts('confirmation') . '.pdf',
346 ];
347 $template_params_to_copy = [
348 'billing_name',
349 'billing_city',
350 'billing_country',
351 'billing_postal_code',
352 'billing_state',
353 'billing_street_address',
354 'credit_card_exp_date',
355 'credit_card_type',
356 'credit_card_number',
357 ];
358 foreach ($template_params_to_copy as $template_param_to_copy) {
359 $this->set($template_param_to_copy, $send_template_params['tplParams'][$template_param_to_copy]);
360 }
361
362 CRM_Core_BAO_MessageTemplate::sendTemplate($send_template_params);
363 }
364
365 /**
366 * Apply form rules.
367 *
368 * @param array $fields
369 * @param array $files
370 * @param CRM_Core_Form $form
371 *
372 * @return array|bool
373 */
374 public static function formRule($fields, $files, $form) {
375 $errors = [];
376
377 if ($form->payment_required && empty($form->_submitValues['is_pay_later'])) {
378 CRM_Core_Form::validateMandatoryFields($form->_fields, $fields, $errors);
379
380 // validate payment instrument values (e.g. credit card number)
381 CRM_Core_Payment_Form::validatePaymentInstrument($form->_paymentProcessor['id'], $fields, $errors, NULL);
382 }
383
384 return empty($errors) ? TRUE : $errors;
385 }
386
387 /**
388 * Pre-process form.
389 */
390 public function preProcess() {
391 $params = $this->_submitValues;
392 $this->is_pay_later = CRM_Utils_Array::value('is_pay_later', $params, FALSE) && !CRM_Utils_Array::value('payment_completed', $params);
393
394 parent::preProcess();
395 }
396
397 /**
398 * Post process form.
399 */
400 public function postProcess() {
401 $trxnDetails = NULL;
402 $params = $this->_submitValues;
403
404 $main_participants = $this->cart->get_main_event_participants();
405
406 $transaction = new CRM_Core_Transaction();
407
408 foreach ($main_participants as $participant) {
409 $defaults = [];
410 $ids = ['contact_id' => $participant->contact_id];
411 $contact = CRM_Contact_BAO_Contact::retrieve($ids, $defaults);
412 $contact->is_deleted = 0;
413 $contact->save();
414 }
415
416 $trxn_prefix = 'VR';
417 if (array_key_exists('billing_contact_email', $params)) {
418 $this->payer_contact_id = self::find_or_create_contact([
419 'email' => $params['billing_contact_email'],
420 'first_name' => $params['billing_first_name'],
421 'last_name' => $params['billing_last_name'],
422 'is_deleted' => FALSE,
423 ]);
424
425 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
426 $this->payer_contact_id,
427 'contact_type'
428 );
429 $billing_fields = [
430 "billing_first_name" => 1,
431 "billing_middle_name" => 1,
432 "billing_last_name" => 1,
433 "billing_street_address-{$this->_bltID}" => 1,
434 "billing_city-{$this->_bltID}" => 1,
435 "billing_state_province_id-{$this->_bltID}" => 1,
436 "billing_postal_code-{$this->_bltID}" => 1,
437 "billing_country_id-{$this->_bltID}" => 1,
438 "address_name-{$this->_bltID}" => 1,
439 "email-{$this->_bltID}" => 1,
440 ];
441
442 $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
443
444 $params["email-{$this->_bltID}"] = $params['billing_contact_email'];
445 CRM_Contact_BAO_Contact::createProfileContact(
446 $params,
447 $billing_fields,
448 $this->payer_contact_id,
449 NULL,
450 NULL,
451 $ctype,
452 TRUE
453 );
454
455 $params['contact_id'] = $this->payer_contact_id;
456 }
457
458 $params['now'] = date('YmdHis');
459 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
460 $params['amount'] = $this->total;
461 $params['financial_type_id'] = $this->financial_type_id;
462 if ($this->payment_required && empty($params['is_pay_later'])) {
463 $trxnDetails = $this->make_payment($params);
464 $params['trxn_id'] = $trxnDetails['trxn_id'];
465 $params['trxn_date'] = $trxnDetails['trxn_date'];
466 $params['currencyID'] = $trxnDetails['currency'];
467 }
468 $this->cart->completed = TRUE;
469 $this->cart->save();
470 $this->set('last_event_cart_id', $this->cart->id);
471
472 $contribution_statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
473 $params['payment_instrument_id'] = NULL;
474 if (!empty($params['is_pay_later'])) {
475 $params['payment_instrument_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Check');
476 $trxn_prefix = 'CK';
477 }
478 else {
479 $params['payment_instrument_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Credit Card');
480 }
481 if ($this->is_pay_later && empty($params['payment_completed'])) {
482 $params['contribution_status_id'] = array_search('Pending', $contribution_statuses);
483 }
484 else {
485 $params['contribution_status_id'] = array_search('Completed', $contribution_statuses);
486 $params['participant_status'] = 'Registered';
487 $params['is_pay_later'] = 0;
488 }
489 if ($trxnDetails == NULL) {
490 $params['trxn_id'] = $trxn_prefix . strftime("%Y%m%d%H%M%S");
491 $params['trxn_date'] = $params['now'];
492 }
493
494 if ($this->payment_required) {
495 $this->emailReceipt($this->cart->events_in_carts, $params);
496 }
497
498 // n.b. we need to process the subparticipants before main event
499 // participants so that session attendance can be included in the email
500 $main_participants = $this->cart->get_main_event_participants();
501 $this->all_participants = [];
502 foreach ($main_participants as $main_participant) {
503 $this->all_participants = array_merge($this->all_participants, $this->cart->get_subparticipants($main_participant));
504 }
505 $this->all_participants = array_merge($this->all_participants, $main_participants);
506
507 $this->sub_trxn_index = 0;
508 foreach ($this->all_participants as $mer_participant) {
509 $event_in_cart = $this->cart->get_event_in_cart_by_event_id($mer_participant->event_id);
510
511 $this->sub_trxn_index += 1;
512
513 unset($params['contributionID']);
514 if ($mer_participant->must_wait) {
515 $this->registerParticipant($params, $mer_participant, $event_in_cart->event);
516 }
517 else {
518 $params['amount'] = $mer_participant->cost - $mer_participant->discount_amount;
519
520 if ($event_in_cart->event->financial_type_id && $mer_participant->cost) {
521 $params['financial_type_id'] = $event_in_cart->event->financial_type_id;
522 $params['participant_contact_id'] = $mer_participant->contact_id;
523 $contribution = $this->record_contribution($mer_participant, $params, $event_in_cart->event);
524 // Record civicrm_line_item
525 CRM_Price_BAO_LineItem::processPriceSet($mer_participant->id, $mer_participant->price_details, $contribution, $entity_table = 'civicrm_participant');
526 }
527 $this->registerParticipant($params, $mer_participant, $event_in_cart->event);
528 }
529 }
530 $this->trxn_id = $params['trxn_id'];
531 $this->trxn_date = $params['trxn_date'];
532 $this->saveDataToSession();
533 $transaction->commit();
534 }
535
536 /**
537 * Make payment.
538 *
539 * @param array $params
540 *
541 * @return array
542 * @throws Exception
543 */
544 public function make_payment(&$params) {
545 $params = $this->prepareParamsForPaymentProcessor($params);
546 $params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
547
548 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
549 CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, TRUE);
550
551 try {
552 $result = $payment->doPayment($params);
553 }
554 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
555 CRM_Core_Error::displaySessionError($result);
556 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/cart_checkout', "_qf_Payment_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE));
557 }
558
559 $trxnDetails = [
560 'trxn_id' => $result['trxn_id'],
561 'trxn_date' => $result['now'],
562 'currency' => $result['currencyID'] ?? NULL,
563 ];
564 return $trxnDetails;
565 }
566
567 /**
568 * Record contribution.
569 *
570 * @param CRM_Event_BAO_Participant $mer_participant
571 * @param array $params
572 * @param CRM_Event_BAO_Event $event
573 *
574 * @return object
575 * @throws Exception
576 */
577 public function record_contribution(&$mer_participant, &$params, $event) {
578 if ($this->payer_contact_id) {
579 $payer = $this->payer_contact_id;
580 }
581 elseif (self::getContactID()) {
582 $payer = self::getContactID();
583 }
584 else {
585 $payer = $params['participant_contact_id'];
586 }
587
588 $contribParams = [
589 'contact_id' => $payer,
590 'financial_type_id' => $params['financial_type_id'],
591 'receive_date' => $params['now'],
592 'total_amount' => $params['amount'],
593 'amount_level' => $mer_participant->fee_level,
594 'net_amount' => $params['amount'],
595 'invoice_id' => "{$params['invoiceID']}-{$this->sub_trxn_index}",
596 'trxn_id' => "{$params['trxn_id']}-{$this->sub_trxn_index}",
597 'currency' => $params['currencyID'] ?? NULL,
598 'source' => $event->title,
599 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
600 'contribution_status_id' => $params['contribution_status_id'],
601 'payment_instrument_id' => $params['payment_instrument_id'],
602 'check_number' => $params['check_number'] ?? NULL,
603 'skipLineItem' => 1,
604 ];
605
606 if (is_array($this->_paymentProcessor)) {
607 $contribParams['payment_processor'] = $this->_paymentProcessor['id'];
608 }
609
610 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
611 $mer_participant->contribution_id = $contribution->id;
612 $params['contributionID'] = $contribution->id;
613
614 return $contribution;
615 }
616
617 /**
618 * Save data to session.
619 */
620 public function saveDataToSession() {
621 $session_line_items = [];
622 foreach ($this->line_items as $line_item) {
623 $session_line_item = [];
624 $session_line_item['amount'] = $line_item['amount'];
625 $session_line_item['cost'] = $line_item['cost'];
626 $session_line_item['event_id'] = $line_item['event']->id;
627 $session_line_items[] = $session_line_item;
628 }
629 $this->set('line_items', $session_line_items);
630 $this->set('payment_required', $this->payment_required);
631 $this->set('is_pay_later', $this->is_pay_later);
632 $this->set('pay_later_receipt', $this->pay_later_receipt);
633 $this->set('trxn_id', $this->trxn_id);
634 $this->set('trxn_date', $this->trxn_date);
635 $this->set('total', $this->total);
636 }
637
638 /**
639 * Set form default values.
640 *
641 * @return array
642 */
643 public function setDefaultValues() {
644 $defaults = parent::setDefaultValues();
645
646 $default_country = new CRM_Core_DAO_Country();
647 $default_country->iso_code = CRM_Core_BAO_Country::defaultContactCountry();
648 $default_country->find(TRUE);
649 $defaults["billing_country_id-{$this->_bltID}"] = $default_country->id;
650
651 if (self::getContactID()) {
652 $params = ['id' => self::getContactID()];
653 $contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
654
655 foreach ($contact->email as $email) {
656 if ($email['is_billing']) {
657 $defaults["billing_contact_email"] = $email['email'];
658 }
659 }
660 if (empty($defaults['billing_contact_email'])) {
661 foreach ($contact->email as $email) {
662 if ($email['is_primary']) {
663 $defaults["billing_contact_email"] = $email['email'];
664 }
665 }
666 }
667
668 $defaults["billing_first_name"] = $contact->first_name;
669 $defaults["billing_middle_name"] = $contact->middle_name;
670 $defaults["billing_last_name"] = $contact->last_name;
671
672 $billing_address = CRM_Event_Cart_BAO_MerParticipant::billing_address_from_contact($contact);
673
674 if ($billing_address != NULL) {
675 $defaults["billing_street_address-{$this->_bltID}"] = $billing_address['street_address'];
676 $defaults["billing_city-{$this->_bltID}"] = $billing_address['city'];
677 $defaults["billing_postal_code-{$this->_bltID}"] = $billing_address['postal_code'];
678 $defaults["billing_state_province_id-{$this->_bltID}"] = $billing_address['state_province_id'];
679 $defaults["billing_country_id-{$this->_bltID}"] = $billing_address['country_id'];
680 }
681 }
682
683 $defaults["source"] = $this->description;
684
685 return $defaults;
686 }
687
688 /**
689 * Apply discount.
690 *
691 * @param string $discountCode
692 * @param array $price_set_amount
693 * @param float $cost
694 * @param int $event_id
695 *
696 * @return bool
697 * @throws \CiviCRM_API3_Exception
698 */
699 protected function apply_discount($discountCode, &$price_set_amount, &$cost, $event_id) {
700 $extensions = civicrm_api3('Extension', 'get', [
701 'full_name' => 'org.civicrm.module.cividiscount',
702 ]);
703 if (empty($extensions['id']) || ($extensions['values'][$extensions['id']]['status'] !== 'installed')) {
704 return FALSE;
705 }
706
707 $autoDiscount = [];
708
709 $discounted_priceset_ids = _cividiscount_get_discounted_priceset_ids();
710 $discounts = _cividiscount_get_discounts();
711
712 $stat = FALSE;
713 foreach ($discounts as $key => $discountValue) {
714 if ($key == $discountCode) {
715 $events = $discountValue['events'] ?? NULL;
716 $evt_ids = implode(",", $events);
717 if ($evt_ids == "0" || strpos($evt_ids, $event_id)) {
718 $event_match = TRUE;
719 }
720 //check priceset is_active
721 if ($discountValue['active_on'] != NULL) {
722 $today = date('Y-m-d');
723 $diff1 = date_diff(date_create($today), date_create($discountValue['active_on']));
724 if ($diff1->days > 0) {
725 $active1 = TRUE;
726 }
727 }
728 else {
729 $active1 = TRUE;
730 }
731 if ($discountValue['expire_on'] != NULL) {
732 $diff2 = date_diff(date_create($today), date_create($discountValue['expire_on']));
733 if ($diff2->days > 0) {
734 $active2 = TRUE;
735 }
736 }
737 else {
738 $active2 = TRUE;
739 }
740 }
741 if ($discountValue['is_active'] == TRUE && ($discountValue['count_max'] == 0 || ($discountValue['count_max'] > $discountValue['count_use'])) && $active1 == TRUE && $active2 == TRUE && $event_match == TRUE) {
742 foreach ($price_set_amount as $key => $price) {
743 if (array_search($price['price_field_value_id'], $discounted_priceset_ids) != NULL) {
744 $discounted = _cividiscount_calc_discount($price['line_total'], $price['label'], $discountValue, $autoDiscount, $this->getCurrency());
745 $price_set_amount[$key]['line_total'] = $discounted[0];
746 $cost += $discounted[0];
747 $price_set_amount[$key]['label'] = $discounted[1];
748 }
749 else {
750 $cost += $price['line_total'];
751 }
752 }
753 $stat = TRUE;
754 }
755 }
756 return $stat;
757 }
758
759 }