From 0aaf8fe9d7ee462bfdfcf92c0c5e853cf26e8c13 Mon Sep 17 00:00:00 2001 From: Pratik Joshi Date: Tue, 21 Jan 2014 18:09:41 +0530 Subject: [PATCH] CRM-13973 : post process handling --- CRM/Contribute/BAO/Contribution.php | 3 +- CRM/Event/BAO/Participant.php | 182 ++++++++++++++++++++- CRM/Event/Form/ParticipantFeeSelection.php | 144 +++++++++++++++- CRM/Financial/BAO/FinancialItem.php | 3 +- 4 files changed, 322 insertions(+), 10 deletions(-) diff --git a/CRM/Contribute/BAO/Contribution.php b/CRM/Contribute/BAO/Contribution.php index b8aca464da..5c4588aa23 100644 --- a/CRM/Contribute/BAO/Contribution.php +++ b/CRM/Contribute/BAO/Contribution.php @@ -182,7 +182,7 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution { //add Account details $params['contribution'] = $contribution; - self::recordFinancialAccounts($params, $ids); + self::recordFinancialAccounts($params); // reset the group contact cache for this group CRM_Contact_BAO_GroupContactCache::remove(); @@ -3100,7 +3100,6 @@ WHERE eft.financial_trxn_id = {$trxnId} $total = $total['total_amount']; } $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total); - $info['total'] = $total; $info['paid'] = $total - $paymentBalance; $info['balance'] = $paymentBalance; diff --git a/CRM/Event/BAO/Participant.php b/CRM/Event/BAO/Participant.php index 407c15c30c..9b6d28d180 100644 --- a/CRM/Event/BAO/Participant.php +++ b/CRM/Event/BAO/Participant.php @@ -1773,5 +1773,185 @@ WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2"; self::deleteParticipant($participant->id); } } -} + static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) { + $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); + $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses); + $pendngRefundStatusId = array_search('Pending refund', $contributionStatuses); + $fetchCon = array('id' => $contributionId); + $contributionObj = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); + + $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant'); + CRM_Price_BAO_PriceSet::processAmount($feeBlock, + $params, $lineItems + ); + + // get the submitted + foreach ($feeBlock as $id => $values) { + CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems); + $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id'); + } + $insertLines = $submittedLineItems; + $submittedFieldValueIds = array_keys($submittedLineItems); + + foreach ($previousLineItems as $id => $previousLineItem) { + // check through the submitted items if the previousItem exists, + // if found in submitted items, do not use it for new item creations + if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) { + unset($insertLines[$previousLineItem['price_field_value_id']]); + } + } + + $submittedFields = implode(', ', $submittedFieldId); + $submittedFieldValues = implode(', ', $submittedFieldValueIds); + if (!empty($submittedFields) && !empty($submittedFieldValues)) { + // if previous line item is not submitted in selection, update the line total and QTY to '0' + $updateLineItem = " +UPDATE civicrm_line_item li +INNER JOIN civicrm_financial_item fi + ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item') +INNER JOIN civicrm_entity_financial_trxn eft + ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item') +SET li.qty = 0, + li.line_total = 0.00, + fi.amount = 0.00, + eft.amount = 0.00 +WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND + (price_field_value_id NOT IN ({$submittedFieldValues}) OR price_field_id NOT IN ({$submittedFields})) +"; + CRM_Core_DAO::executeQuery($updateLineItem); + } + + // insert new line items + foreach ($insertLines as $valueId => $lineParams) { + $lineParams['entity_table'] = 'civicrm_participant'; + $lineParams['entity_id'] = $participantId; + $lineObj = CRM_Price_BAO_LineItem::create($lineParams); + // insert financial items + // ensure entity_financial_trxn table has a linking of it. + $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $contributionObj); + } + // insert new 'adjusted amount' transaction entry and update contribution entry. + // ensure entity_financial_trxn table has a linking of it. + $updatedAmount = $params['amount']; + $balanceAmt = $updatedAmount - $paidAmount; + + if ($balanceAmt) { + if ($balanceAmt > 0) { + $contributionStatusVal = $partiallyPaidStatusId; + } + elseif ($balanceAmt < 0) { + $contributionStatusVal = $pendngRefundStatusId; + } + + // update contribution status and total amount without trigger financial code + // as this is handled in current BAO function used for change selection + $updatedContributionDAO = new CRM_Contribute_BAO_Contribution(); + $updatedContributionDAO->id = $contributionId; + $updatedContributionDAO->contribution_status_id = $contributionStatusVal; + $updatedContributionDAO->total_amount = $updatedAmount; + $updatedContributionDAO->save(); + /* + * adjusted amount financial_trxn creation, + * adjusted amount line_item creation, + * adjusted amount financial_item creations, + * adjusted amount enitity_financial_trxn creation + */ + $updatedContribution = + CRM_Contribute_BAO_Contribution::getValues(array('id' => $contributionId), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); + $prevTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); + $fetchPrevTrxn['id'] = $prevTrxnId['financialTrxnId']; + $prevTrxnToFinancialId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_FinancialTrxn', $prevTrxnId['financialTrxnId'], 'to_financial_account_id'); + + $adjustedTrxnValues = array( + 'from_financial_account_id' => NULL, + 'to_financial_account_id' => $prevTrxnToFinancialId, + 'trxn_date' => date('YmdHis'), + 'total_amount' => $balanceAmt, + 'currency' => $updatedContribution->currency, + 'status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'), + 'payment_instrument_id' => $updatedContribution->payment_instrument_id, + 'contribution_id' => $updatedContribution->id, + ); + $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues); + + // record line item + $adjustPaymentLineParams = array( + 'total_amount' => $updatedAmount, + 'financial_type_id' => $updatedContribution->financial_type_id + ); + $setId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name'); + CRM_Price_BAO_LineItem::getLineItemArray($adjustPaymentLineParams); + $defaultPriceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($setId)); + $fieldID = key($defaultPriceSet['fields']); + $adjustPaymentLineParams['line_item'][$setId][$fieldID]['entity_id'] = $updatedContribution->id; + $adjustPaymentLineParams['line_item'][$setId][$fieldID]['entity_table'] = 'civicrm_contribution'; + $adjustPaymentLine = CRM_Price_BAO_LineItem::create($adjustPaymentLineParams['line_item'][$setId][$fieldID]); + + // record financial item + $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); + $itemStatus = NULL; + if ($updatedContribution->contribution_status_id == array_search('Completed', $contributionStatuses)) { + $itemStatus = array_search('Paid', $financialItemStatus); + } + elseif ($updatedContribution->contribution_status_id == array_search('Pending', $contributionStatuses)) { + $itemStatus = array_search('Unpaid', $financialItemStatus); + } + elseif ($updatedContribution->contribution_status_id == array_search('Partially paid', $contributionStatuses)) { + $itemStatus = array_search('Partially paid', $financialItemStatus); + } + $params = array( + 'transaction_date' => CRM_Utils_Date::isoToMysql($updatedContribution->receive_date), + 'contact_id' => $updatedContribution->contact_id, + 'amount' => $balanceAmt, + 'currency' => $updatedContribution->currency, + 'entity_table' => 'civicrm_line_item', + 'entity_id' => $adjustPaymentLine->id, + 'description' => ( $adjustPaymentLine->qty != 1 ? $lineItem->qty . ' of ' : ''). ' ' . $adjustPaymentLine->label, + 'status_id' => $itemStatus, + 'financial_account_id' => $prevItem->financial_account_id + ); + CRM_Financial_BAO_FinancialItem::create($params, NULL, array('id' => $adjustedTrxn->id)); + } + //activity creation + self::addActivityForSelection($participantId, 'Change Registration'); + } + + static function addActivityForSelection($participantId, $activityType) { + $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'event_id'); + $contactId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantId, 'contact_id'); + + $date = CRM_Utils_Date::currentDBDate(); + $event = CRM_Event_BAO_Event::getEvents(0, $eventId); + $eventTitle = $event[$eventId]; + $subject = "Registration selections changed for $eventTitle"; + $targetCid = $contactId; + $srcRecId = $participantId; + + // activity params + $activityParams = array( + 'source_contact_id' => $targetCid, + 'source_record_id' => $srcRecId, + 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', + $activityType, + 'name' + ), + 'subject' => $subject, + 'activity_date_time' => $date, + 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', + 'Completed', + 'name' + ), + 'skipRecentView' => TRUE, + ); + + // create activity with target contacts + $session = CRM_Core_Session::singleton(); + $id = $session->get('userID'); + if ($id) { + $activityParams['source_contact_id'] = $id; + $activityParams['target_contact_id'][] = $targetCid; + } + CRM_Activity_BAO_Activity::create($activityParams); + } +} \ No newline at end of file diff --git a/CRM/Event/Form/ParticipantFeeSelection.php b/CRM/Event/Form/ParticipantFeeSelection.php index 4928b7e6f7..c5eb229956 100644 --- a/CRM/Event/Form/ParticipantFeeSelection.php +++ b/CRM/Event/Form/ParticipantFeeSelection.php @@ -62,6 +62,12 @@ class CRM_Event_Form_ParticipantFeeSelection extends CRM_Core_Form { protected $_participantStatus = NULL; + protected $_paidAmount = NULL; + + public $_isPaidEvent = NULL; + + protected $contributionAmt = NULL; + public function preProcess() { $this->_participantId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE); $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE); @@ -86,8 +92,9 @@ class CRM_Event_Form_ParticipantFeeSelection extends CRM_Core_Form { $this->assign('id', $this->_participantId); $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_participantId, 'event'); + $this->_paidAmount = $paymentInfo['paid']; $this->assign('paymentInfo', $paymentInfo); - CRM_Core_Resources::singleton()->addSetting(array('feePaid' => $paymentInfo['paid'])); + CRM_Core_Resources::singleton()->addSetting(array('feePaid' => $this->_paidAmount)); $title = "Change selections for {$this->_contributorDisplayName}"; if ($title) { @@ -195,16 +202,143 @@ class CRM_Event_Form_ParticipantFeeSelection extends CRM_Core_Form { public function postProcess() { $params = $this->controller->exportValues($this->_name); - $session = CRM_Core_Session::singleton(); + + $feeBlock = $this->_values['fee']; + $lineItems = $this->_values['line_items']; + CRM_Event_BAO_Participant::changeFeeSelections($params, $this->_participantId, $this->_contributionId, $feeBlock, $lineItems, $this->_paidAmount, $params['priceSetId']); + $this->contributionAmt = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $this->_contributionId, 'total_amount'); + // email sending + if (CRM_Utils_Array::value('send_receipt', $params)){ + $fetchParticipantVals = array('id' => $this->_participantId); + CRM_Event_BAO_Participant::getValues($fetchParticipantVals, $participantDetails, CRM_Core_DAO::$_nullArray); + $participantParams = array_merge($params, $participantDetails[$this->_participantId]); + $mailSent = $this->emailReceipt($participantParams); + } + + // update participant + CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $this->_participantId, 'status_id', $params['status_id']); + if(!empty($params['note'])) { + $noteParams = array( + 'entity_table' => 'civicrm_participant', + 'note' => $params['note'], + 'entity_id' => $this->_participantId, + 'contact_id' => $this->_contactId, + 'modified_date' => date('Ymd'), + ); + CRM_Core_BAO_Note::add($noteParams); + } + CRM_Core_Session::setStatus(ts("The fee selection has been changed for this participant"), ts('Saved'), 'success'); + $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->getButtonName('upload', 'new')) { + $session = CRM_Core_Session::singleton(); $session->replaceUserContext(CRM_Utils_System::url('civicrm/payment/add', "reset=1&action=add&component=event&id={$this->_participantId}&cid={$this->_contactId}" )); } - } + } + + function emailReceipt(&$params) { + // offline receipt sending + if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) { + $receiptFrom = $params['from_email_address']; + } + + $this->assign('module', 'Event Registration'); + //use of the message template below requires variables in different format + $event = $events = array(); + $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title'); + + //get all event details. + CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties); + $event = $events[$params['event_id']]; + unset($event['start_date']); + unset($event['end_date']); + + $role = CRM_Event_PseudoConstant::participantRole(); + $participantRoles = CRM_Utils_Array::value('role_id', $params); + if (is_array($participantRoles)) { + $selectedRoles = array(); + foreach (array_keys($participantRoles) as $roleId) { + $selectedRoles[] = $role[$roleId]; + } + $event['participant_role'] = implode(', ', $selectedRoles); + } + else { + $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role); + } + $event['is_monetary'] = $this->_isPaidEvent; + + if ($params['receipt_text']) { + $event['confirm_email_text'] = $params['receipt_text']; + } + + $this->assign('isAmountzero', 1); + $this->assign('event', $event); + + $this->assign('isShowLocation', $event['is_show_location']); + if (CRM_Utils_Array::value('is_show_location', $event) == 1) { + $locationParams = array( + 'entity_id' => $params['event_id'], + 'entity_table' => 'civicrm_event', + ); + $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE); + $this->assign('location', $location); + } + + $status = CRM_Event_PseudoConstant::participantStatus(); + if ($this->_isPaidEvent) { + $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); + if (!$this->_mode) { + if (isset($params['payment_instrument_id'])) { + $this->assign('paidBy', + CRM_Utils_Array::value($params['payment_instrument_id'], + $paymentInstrument + ) + ); + } + } + + $this->assign('totalAmount', $this->contributionAmt); + + $this->assign('isPrimary', 1); + $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params)); + } + + $this->assign('register_date', $params['register_date']); + $template = CRM_Core_Smarty::singleton(); + + // Retrieve the name and email of the contact - this will be the TO for receipt email + list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId); + + $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName; + + $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'"); + if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) { + $this->assign('isOnWaitlist', TRUE); + } + $this->assign('contactID', $this->_contactId); + $this->assign('participantID', $this->_participantId); + + $sendTemplateParams = array( + 'groupName' => 'msg_tpl_workflow_event', + 'valueName' => 'event_offline_receipt', + 'contactId' => $this->_contactId, + 'isTest' => FALSE, + 'PDFFilename' => ts('confirmation').'.pdf', + ); + + // try to send emails only if email id is present + // and the do-not-email option is not checked for that contact + if ($this->_contributorEmail && !$this->_toDoNotEmail) { + $sendTemplateParams['from'] = $receiptFrom; + $sendTemplateParams['toName'] = $this->_contributorDisplayName; + $sendTemplateParams['toEmail'] = $this->_contributorEmail; + $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails); + $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails); + } - static function emailReceipt(&$form, &$params) { - // email receipt sending + list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); + return $mailSent; } } \ No newline at end of file diff --git a/CRM/Financial/BAO/FinancialItem.php b/CRM/Financial/BAO/FinancialItem.php index 84a5d33064..323e3ae844 100644 --- a/CRM/Financial/BAO/FinancialItem.php +++ b/CRM/Financial/BAO/FinancialItem.php @@ -113,8 +113,7 @@ class CRM_Financial_BAO_FinancialItem extends CRM_Financial_DAO_FinancialItem { $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution->id, 'ASC', TRUE); $trxnId['id'] = $trxn['financialTrxnId']; - - self::create($params, NULL, $trxnId); + return self::create($params, NULL, $trxnId); } /** -- 2.25.1