Commit 7a24aa09 authored by Monish Deb's avatar Monish Deb

AGBU-11: Add error handler and record success/failure response

parent 3b36e685
......@@ -70,16 +70,102 @@ class CRM_Financial_BAO_ExportFormat_SyncIntacctGL extends CRM_Financial_BAO_Exp
* @param array $export
*/
public function makeExport($export) {
$batchEntries = [];
foreach ($export as $batchID) {
$this->_batchIds = $batchID;
CRM_Core_DAO::executeQuery("INSERT IGNORE INTO civicrm_intacct_batches(`batch_id`, `mode`) VALUES ($batchID, 'GL')");
$batchEntries[$batchID] = CRM_Syncintacct_Util::fetchTransactionrecords($batchID, 'civicrm_contribution');
}
// Save the file in the public directory.
$fileName = self::putFile($batchEntries);
$this->output($fileName);
}
/**
* Exports sbatches in $this->_batchIds, and saves to file.
*
* @param string $fileName - use this file name (if applicable)
*/
public function output($fileName = NULL) {
// Default behaviour, override if needed:
self::createActivityExport($this->_batchIds, $fileName);
}
/**
* @param $batchIds
* @param string $fileName
*
* @throws CRM_Core_Exception
*/
public static function createActivityExport($batchIds, $fileName) {
$loggedInContactId = CRM_Core_Session::getLoggedInContactID();
$values = array();
$params = array('id' => $batchIds);
CRM_Batch_BAO_Batch::retrieve($params, $values);
$createdBy = CRM_Contact_BAO_Contact::displayName($values['created_id']);
$modifiedBy = CRM_Contact_BAO_Contact::displayName($values['modified_id']);
$values['payment_instrument_id'] = '';
if (isset($values['payment_instrument_id'])) {
$paymentInstrument = array_flip(CRM_Contribute_PseudoConstant::paymentInstrument('label'));
$values['payment_instrument_id'] = array_search($values['payment_instrument_id'], $paymentInstrument);
}
$details = '<p>' . ts('Record:') . ' ' . $values['title'] . '</p><p>' . ts('Description:') . '</p><p>' . ts('Created By:') . " $createdBy" . '</p><p>' . ts('Created Date:') . ' ' . $values['created_date'] . '</p><p>' . ts('Last Modified By:') . ' ' . $modifiedBy . '</p><p>' . ts('Payment Method:') . ' ' . $values['payment_instrument_id'] . '</p>';
$subject = '';
if (!empty($values['total'])) {
$subject .= ts('Total') . '[' . CRM_Utils_Money::format($values['total']) . '],';
}
if (!empty($values['item_count'])) {
$subject .= ' ' . ts('Count') . '[' . $values['item_count'] . '],';
}
// create activity.
$subject .= ' ' . ts('Batch') . '[' . $values['title'] . ']';
$activityParams = array(
'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Export Accounting Batch'),
'subject' => $subject,
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled'),
'activity_date_time' => date('YmdHis'),
'source_contact_id' => $loggedInContactId,
'source_record_id' => $values['id'],
'target_contact_id' => $loggedInContactId,
'details' => $details,
'attachFile_1' => array(
'uri' => $fileName,
'type' => 'text/plain',
'location' => $fileName,
'upload_date' => date('YmdHis'),
),
);
CRM_Activity_BAO_Activity::create($activityParams);
}
/**
* @param $export
*
* @return string
*/
public function putFile($export) {
$fileName = CRM_Core_Config::singleton()->uploadDir . 'Financial_Transactions_GLEntries_' . date('YmdHis') . '.' . $this->getFileExtension();
$out = fopen($fileName, 'w');
foreach ($export as $batchID => $entries) {
$content = sprintf('Batch ID - %d: %s', $batchID, var_export($entries, TRUE));
file_put_contents($fileName, $content, FILE_APPEND);
}
fclose($out);
return $fileName;
}
/**
* @return void
*/
public function getFileExtension() {
return NULL;
return 'txt';
}
}
......@@ -12,6 +12,7 @@ use Intacct\Functions\GeneralLedger\JournalEntryCreate;
use Intacct\Functions\GeneralLedger\JournalEntryLineCreate;
use Intacct\Functions\GeneralLedger\CustomAllocationSplit;
use Intacct\Functions\GeneralLedger\AccountCreate;
use Intacct\Exception\ResponseException;
/**
* Class to send Moodle API request
......@@ -136,7 +137,24 @@ class CRM_Syncintacct_API {
* @return array
*/
public function sendRequest($query) {
return $this->_client->execute($query)->getResult();
$errorMessage = [];
try {
return $this->_client->execute($query)->getResult()->getData();
} catch (ResponseException $ex) {
$errorMessage = [
'is_error' => TRUE,
get_class($ex) => $ex->getMessage(),
'Errors: ' => $ex->getErrors(),
];
} catch (\Exception $ex) {
$errorMessage = [
'is_error' => TRUE,
get_class($ex) => $ex->getMessage(),
];
}
return $errorMessage;
}
/**
......
......@@ -17,7 +17,10 @@ class CRM_Syncintacct_Form_Setting extends CRM_Core_Form {
if (!CRM_Core_Permission::check('administer CiviCRM')) {
CRM_Core_Error::fatal(ts('You do not permission to access this page, please contact your system administrator.'));
}
$this->_credential = Civi::settings()->get('intacct_credential');
$this->_credential = array_merge(
Civi::settings()->get('intacct_credential'), ['send_error_to_email' => Civi::settings()->get('send_error_to_email')]
);
}
/**
* Set default values.
......@@ -34,7 +37,8 @@ class CRM_Syncintacct_Form_Setting extends CRM_Core_Form {
$this->add('password', 'user_password', ts('User Password'), array('class' => 'huge'), TRUE);
$this->add('text', 'sender_id', ts('Sender ID'), array('class' => 'huge'), TRUE);
$this->add('password', 'sender_password', ts('Sender Password'), array('class' => 'huge'), TRUE);
$this->assign('intacctCredentials', ['company_id', 'user_id', 'user_password', 'sender_id', 'sender_password']);
$this->add('text', 'send_error_to_email', ts('Send error message to'), array('class' => 'huge'), TRUE);
$this->assign('intacctCredentials', ['company_id', 'user_id', 'user_password', 'sender_id', 'sender_password', 'send_error_to_email']);
$this->addButtons(array(
array(
'type' => 'submit',
......@@ -52,6 +56,7 @@ class CRM_Syncintacct_Form_Setting extends CRM_Core_Form {
$credential[$attribute] = $values[$attribute];
}
Civi::settings()->set('intacct_credential', $credential);
Civi::settings()->set('send_error_to_email', CRM_Utils_Array::value('send_error_to_email', $values));
CRM_Core_Session::setStatus(ts("Intacct Web Service credential submitted"), ts('Success'), 'success');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
......
......@@ -112,10 +112,10 @@ class CRM_Syncintacct_Util {
public static function createGLEntries($batchEntries) {
$fetchVendors = CRM_Syncintacct_API::singleton()
->getVendors(array_unique(CRM_Utils_Array::collect('VENDORID', $batchEntries['ENTRIES'])))
->getData();
->getVendors(array_unique(CRM_Utils_Array::collect('VENDORID', $batchEntries['ENTRIES'])));
$displayNames = [];
$result = '';
foreach ($fetchVendors as $vendor) {
$key = (string) $vendor->NAME;
$displayNames[$key] = (string) $vendor->VENDORID;
......@@ -127,13 +127,58 @@ class CRM_Syncintacct_Util {
$entry['VENDORID'] = $vendorID;
}
else {
$batchEntries['ENTRIES'][$key]['VENDORID'] = (string) CRM_Syncintacct_API::singleton()->createVendors($entry['VENDORID'])->getData()[0]->VENDORID;
$result = CRM_Syncintacct_API::singleton()->createVendors($entry['VENDORID']);
if (!empty($result[0])) {
$batchEntries['ENTRIES'][$key]['VENDORID'] = (string) $result[0]->VENDORID;
}
}
$batchEntries['ENTRIES'][$key] = CRM_Syncintacct_API::singleton()->createGLEntry($entry);
}
$response = CRM_Syncintacct_API::singleton()->createGLBatch($batchEntries);
return CRM_Syncintacct_API::singleton()->createGLBatch($batchEntries);
}
public static function processSyncIntacctResponse($batchID, $response) {
$activity = civicrm_api3('Activity', 'getsingle', [
'source_record_id' => $batchID,
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled'),
'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Export Accounting Batch'),
]);
$fileName = CRM_Core_Config::singleton()->uploadDir . 'Financial_Transactions_Response_' . date('YmdHis') . '.txt';
$content = sprintf('Batch ID - %d: %s', $batchID, var_export($response, TRUE));
file_put_contents($fileName, $content, FILE_APPEND);
$activityParams = array(
'id' => $activity['id'],
'attachFile_2' => array(
'uri' => $fileName,
'type' => 'text/plain',
'location' => $fileName,
'upload_date' => date('YmdHis'),
),
);
if (!empty($response['is_error'])) {
$email = Civi::settings()->get('send_error_to_email');
if ($email) {
$params = [
'toEmail' => $email,
'subject' => ts('Intacct response error for Batch ID ' . $batchID),
'text' => $content,
'html' => $content,
];
CRM_Utils_Mail::send($params);
}
}
else {
$activityParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed');
civicrm_api3('Batch', 'create', [
'id' => $batchID,
'data' => 'Synchronization completed at ' . date('Y-m-d H:i:s'),
]);
CRM_Core_DAO::executeQuery("DELETE FROM civicrm_intacct_batches WHERE batch_id = " . $batchID);
}
CRM_Activity_BAO_Activity::create($activityParams);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment