Civixero.php 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
<?php

require_once 'Civixero.civix.php';

/**
 * Implementation of hook_civicrm_config
 */
function civixero_civicrm_config(&$config) {
  _civixero_civix_civicrm_config($config);
}

/**
 * Implementation of hook_civicrm_xmlMenu
 *
 * @param $files array(string)
 */
function civixero_civicrm_xmlMenu(&$files) {
  _civixero_civix_civicrm_xmlMenu($files);
}

/**
 * Implementation of hook_civicrm_install
 */
function civixero_civicrm_install() {
  return _civixero_civix_civicrm_install();
}

/**
 * Implementation of hook_civicrm_uninstall
 */
function civixero_civicrm_uninstall() {
  return _civixero_civix_civicrm_uninstall();
}

/**
 * Implementation of hook_civicrm_enable
 */
function civixero_civicrm_enable() {
  return _civixero_civix_civicrm_enable();
}

/**
 * Implementation of hook_civicrm_disable
 */
function civixero_civicrm_disable() {
  return _civixero_civix_civicrm_disable();
}

/**
 * Implementation of hook_civicrm_upgrade
 *
 * @param $op string, the type of operation being performed; 'check' or 'enqueue'
 * @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks
 *
 * @return mixed  based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending)
 *                for 'enqueue', returns void
 */
function civixero_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
  return _civixero_civix_civicrm_upgrade($op, $queue);
}

/**
 * Implements hook_civicrm_managed().
 *
 * Generate a list of entities to create/deactivate/delete when this module
 * is installed, disabled, uninstalled.
 *
 * @param array $entities
 *   Existing entity array
 */
function civixero_civicrm_managed(&$entities) {
  if (civixero_is_extension_installed('nz.co.fuzion.connectors')) {
    $entities[] = array(
      'name' => 'CiviXero connector Type',
      'entity' => 'ConnectorType',
      'module' => 'nz.co.fuzion.civixero',
      'params' => array(
        'name' => 'CiviXero',
        'description' => 'CiviXero connector information',
        'module' => 'accountsync',
        'function' => 'credentials',
        'plugin' => 'xero',
        'field1_label' => 'Xero Key',
        'field2_label' => 'Xero Secret',
        'field3_label' => 'Xero Public Certificate Path',
        'field4_label' => 'Xero Private Key Path',
        'field5_label' => 'Settings',
        'version' => 3,
      ),
    );
  }
  return _civixero_civix_civicrm_managed($entities);
}

/**
 * Is a given extension installed.
 *
 * Currently adding very roughly just to support checking if connectors is installed.
 *
 * I like to snaffle hacks into their own function for easy later fixing :-)
 *
 * @todo - test using CRM_Extension_System::singleton()->getManager()->getStatus($key)
 *
 * @param string $extension
 *
 * @return bool
 */
function civixero_is_extension_installed($extension) {
  if ($extension == 'nz.co.fuzion.connectors') {
    if (function_exists('connectors_civicrm_entityTypes')) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Implements hook_civicrm_caseTypes().
 *
 * Generate a list of case-types
 *
 * Note: This hook only runs in CiviCRM 4.4+.
 *
 * @param array $caseTypes
 */
function civixero_civicrm_caseTypes(&$caseTypes) {
  _civixero_civix_civicrm_caseTypes($caseTypes);
}

/**
 * Implements hook_civicrm_config().
 *
 * @param $metaDataFolders
 */
function civixero_civicrm_alterSettingsFolders(&$metaDataFolders){
  static $configured = FALSE;
  if ($configured) return;
  $configured = TRUE;

  $extRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
  $extDir = $extRoot . 'settings';
  if(!in_array($extDir, $metaDataFolders)){
    $metaDataFolders[] = $extDir;
  }
}

/**
 * Implements hook_civicrm_navigationMenu().
 *
 * Adds entries to the navigation menu.
 *
 * @param array $menu
 */
function civixero_civicrm_navigationMenu(&$menu) {
  _Civixero_civix_insert_navigation_menu($menu, 'Administer', [
    'label' => 'Xero',
    'name' => 'Xero',
    'url' => NULL,
    'permission' => 'administer CiviCRM',
    'operator' => NULL,
    'separator' => NULL,
  ]);
  _Civixero_civix_insert_navigation_menu($menu, 'Administer/Xero', [
    'label' => 'Xero Settings',
    'name' => 'Xero Settings',
    'url' => 'civicrm/xero/settings',
    'permission' => 'administer CiviCRM',
    'operator' => NULL,
    'separator' => 0,
  ]);

  _Civixero_civix_insert_navigation_menu($menu, 'Administer/Xero', [
    'label' => 'Xero Error Logs',
    'name' => 'XeroErrorLogs',
    'url' => NULL,
    'permission' => 'administer CiviCRM',
    'operator' => NULL,
    'separator' => 1,
  ]);

  _Civixero_civix_insert_navigation_menu($menu, 'Administer/Xero', [
    'label' => 'Synchronize contacts',
    'name' => 'Contact Sync',
    'url' => 'civicrm/a/#/accounts/contact/sync',
    'permission' => 'administer CiviCRM',
    'operator' => null,
    'separator' => 1,
  ]);

  _Civixero_civix_insert_navigation_menu($menu, 'Administer/Xero/XeroErrorLogs', [
    'label' => 'Contact Errors',
    'name' => 'Contact Errors',
    'url' => 'civicrm/xero/errorlog',
    'permission' => 'administer CiviCRM',
    'operator' => null,
    'separator' => 0,
  ]);

  _Civixero_civix_insert_navigation_menu($menu, 'Administer/Xero/XeroErrorLogs', [
    'label' => 'Invoice Errors',
    'name' => 'Invoice Errors',
    'url' => 'civicrm/xero/errorlog?for=invoice',
    'permission' => 'administer CiviCRM',
    'operator' => null,
    'separator' => 0,
  ]);
}

/**
 * Gettings contributions of sinlge contact
 *
 * @param $contactid
 */
function getContactContributions($contactid) {
    $contributions = civicrm_api3("Contribution","get",array(
        "contact_id" => $contactid,
        "return"     => array("contribution_id"),
        "sequential" => TRUE
    ));
    $contributions = array_column($contributions["values"], "id");
    return $contributions;
}

/**
 * Gettings errored invoices of given contributions
 *
 * @param $contributions
 */
function getErroredInvoicesOfContributions($contributions) {
    $invoices = civicrm_api3("AccountInvoice","get",array(
        "plugin"          => "xero",
        "sequential"      => TRUE,
        "contribution_id" => array("IN" => $contributions),
        "error_data"      => array("<>" => "")
    ));
    return $invoices;
}

function _civixero_append_sync_errors(&$xeroBlock, $account_contact) {
    if(empty($account_contact['accounts_needs_update']) && !empty($account_contact["error_data"])) {
        $xeroBlock .= "<p class='xeroerror'> Contact <span class='error'>sync error</span> with Xero <a href='#' class='helpicon error xeroerror-info' data-xeroerrorid='".$account_contact["id"]."'></a></p>";
    }

    if (!empty($account_contact['accounts_contact_id'])) {
        $contributions = getContactContributions($account_contact["contact_id"]);
        if(count($contributions)) {
            $invoices = getErroredInvoicesOfContributions($contributions);
            if($invoices["count"]) {
                $xeroBlock .= "<p class='xeroerror second'> ".$invoices["count"]." Contribution".(($invoices["count"] > 1)? 's' : '')." <span class='error'>not synced</span> with Xero <a href='#' class='helpicon error xeroerror-invoice-info' data-xeroerrorid='".$account_contact["contact_id"]."'></a></p>";
            }
        }
    }
}

/**
 * Implementation of hook_civicrm_check.
 *
 * Add a check to the status page. Check if there are any account contact or invoice sync errors.
 *
 * @param $page
 */
function civixero_civicrm_check(&$messages) {

    $accountContactErrors = civicrm_api3("AccountContact","getcount",array(
        "error_data"  =>  array("NOT LIKE" => "%error_cleared%"),
        "plugin"      => "xero"
    ));
    $accountInvoiceErrors = civicrm_api3("AccountInvoice","getcount",array(
        "error_data"  =>  array("NOT LIKE" => "%error_cleared%"),
        "plugin"      => "xero"
    ));
    $errorMessage = "";
    $errorsPageUrl = CRM_Utils_System::url('civicrm/xero/errorlog');

    if($accountContactErrors > 0) {
        $errorMessage .= 'Found '.$accountContactErrors.' contact sync errors. <a href="'.$errorsPageUrl.'" target="_blank">Click here</a> to resolve them.';
        if($accountInvoiceErrors > 0) {
            $errorMessage .= "<br><br>";
        }
    }
    if($accountInvoiceErrors > 0) {
        $errorMessage .= 'Found '.$accountInvoiceErrors.' invoice sync errors. <a href="'.$errorsPageUrl.'?for=invoice" target="_blank">Click here</a> to resolve them.';
    }

    if($accountInvoiceErrors > 0 || $accountContactErrors >0) {
        $messages[] = new CRM_Utils_Check_Message(
            'civixero_sync_errors',
            $errorMessage,
            'Xero Sync Errors',
            \Psr\Log\LogLevel::ERROR,
            'fa-refresh'
        );
    }
  $xeroKeyPath = Civi::settings()->get('xero_public_certificate');
  if (!CRM_Utils_File::isIncludable($xeroKeyPath)) {
    $messages[] = new CRM_Utils_Check_Message(
      'civixero_keyinvalid',
      ts('Please configure a Xero api key - see https://github.com/eileenmcnaughton/nz.co.fuzion.civixero/blob/master/README.md'),
      ts('No valid Xero api key'),
      \Psr\Log\LogLevel::WARNING,
      'fa-flag'
    );
  }
  elseif ($xeroKeyPath) {
    $certinfo = openssl_x509_parse(file_get_contents($xeroKeyPath));
    if (!empty($certinfo['validTo_time_t'])) {
      $validTo = new DateTime(date('Y-m-d H:i:s', $certinfo['validTo_time_t']));
      $current = new DateTime(date('Y-m-d H:i:s', time()));
      $interval = $validTo->diff($current);
      if ($interval->days < 30) {
        $messages[] = new CRM_Utils_Check_Message(
          'civixero_keyexpiry',
          ts('Your api key is expiring in %1 days. Please renew to let CiviCRM interact with Xero', array(1 => $interval->days)),
          ts('Xero Api Key Expiry'),
          \Psr\Log\LogLevel::WARNING,
          'fa-flag'
        );
      }
    }
  }
}

/**
 * Implements hook pageRun().
 *
 * Add Xero links to contact summary
 *
 * @param $page
 */
function civixero_civicrm_pageRun(&$page) {
  $pageName = get_class($page);
  if ($pageName != 'CRM_Contact_Page_View_Summary' || !CRM_Core_Permission::check('view all contacts')) {
    return;
  }

  if(($contactID = $page->getVar('_contactId')) != FALSE) {
    $connectors = _civixero_get_connectors();
    $xeroBlock = '';
    try{
      $account_contacts = civicrm_api3('account_contact', 'get', array(
        'contact_id' => $contactID,
        'return' => 'accounts_contact_id, accounts_needs_update, connector_id, error_data, id, contact_id',
        'plugin' => 'xero',
        'connector_id' => array('IN' => array_keys($connectors)),
      ));

      if (!$account_contacts['count']) {
        throw new Exception('Contact needs syncing');
      }
      foreach ($account_contacts['values'] as $account_contact) {
        $prefix = _civixero_get_connector_prefix($account_contact['connector_id']);
        if (!empty($account_contact['accounts_contact_id'])) {
          $xeroBlock .= _civixero_get_xero_links_block($account_contact, $prefix);
        }
        elseif (!empty($account_contact['accounts_needs_update'])) {
          $xeroBlock .= _civicrm_get_xero_block_header();
          $xeroBlock .= "<p> Contact is queued for sync with Xero</p></div>";
        } elseif(!empty($account_contact["error_data"])) {
            $xeroBlock .= _civicrm_get_xero_block_header();
            _civixero_append_sync_errors($xeroBlock, $account_contact);
            $xeroBlock .= "</div>";
        }
      }
    }
    catch(Exception $e) {
      $xeroBlock = "<div class='crm-summary-row'>" .
        "<a href='#' id='xero-sync' data-contact-id=$contactID>
        Queue Sync to Xero</a></div>";

      CRM_Core_Region::instance('contact-basic-info-left')->add(array(
        'markup' => $xeroBlock,
        'type' => 'markup',
      ));
      $createString = '';
      if (!empty($account_contact) && !empty($account_contact['id'])) {
        $createString = "'id' : '" . $account_contact['id'] . "',";
      }
      $script = "cj('#xero-sync').click(function( event) {
        event.preventDefault();
        CRM.api('account_contact', 'create',
         {'contact_id' : cj(this).data('contact-id'),
           'plugin' : 'xero',
           $createString
           'accounts_needs_update' : 1
         });
        cj(this).replaceWith('Xero sync is queued');
      });";
      CRM_Core_Region::instance('contact-basic-info-left')->add(array(
        'script' => $script
      ));
      return;
    }
  }
  else {
    return;
  }

  CRM_Core_Region::instance('contact-basic-info-left')->add(array(
    'markup' => $xeroBlock,
    'type' => 'markup',
  ));

  CRM_Core_Resources::singleton()->addStyleFile('nz.co.fuzion.civixero','css/civixero_styles.css');
  CRM_Core_Resources::singleton()->addScriptFile('nz.co.fuzion.civixero','js/civixero_errors.js');

  //https://go.xero.com/AccountsReceivable/View.aspx?InvoiceID=
}

/**
 * Get prefix for the connector.
 *
 * @param int|null $connector_id
 *
 * @return string
 */
function _civixero_get_connector_prefix($connector_id) {
  if (!$connector_id) {
    return '';
  }
  $connectors = _civixero_get_connectors();
  return $connectors[$connector_id]['name'];
}

/**
 * Get available connectors.
 *
 * @return string
 */
function _civixero_get_connectors() {
  static $connectors = array();
  if (empty($connectors)) {
    try {
      $connectors = civicrm_api3('connector', 'get', array('connector_type_id' => 'CiviXero'));
      $connectors = $connectors['values'];
    }
    catch (CiviCRM_API3_Exception $e) {
      $connectors = array(0 => 0);
    }
  }
  return $connectors;
}

/**
 * @param $xeroID
 *
 * @return string
 */
function _civixero_get_xero_links_block($account_contact, $connector_name) {
  $xeroID = $account_contact['accounts_contact_id'];
  $xeroLinks = array(
    'view_transactions' => array(
      'link' => 'https://go.xero.com/Reports/report.aspx?reportId=be392447-762b-444d-9cde-87c6bd185d00&report=TransactionsByContact&invoiceType=INVOICETYPE%2fACCREC&addToReportId=cf6fedeb-2188-493c-96e2-b862198f9b46&addToReportTitle=Income+by+Contact&reportClass=TransactionsByContact&contact=',
      'link_label' => 'Xero Transactions',
    ),
    'view_contact' => array(
      'link' => 'https://go.xero.com/Contacts/View.aspx?contactID=',
      'link_label' => 'Xero Contact',
    )
  );

  $xeroBlock = _civicrm_get_xero_block_header() . $connector_name;
  foreach ($xeroLinks as $link) {
    $xeroBlock .= "<div class='crm-content'><a href='{$link['link']}{$xeroID}'>{$link['link_label']}</a></div>";
  }
  _civixero_append_sync_errors($xeroBlock, $account_contact);
  $xeroBlock .= "</div>";
  return $xeroBlock;
}

/**
 * Get header for Xero block added to summary screen.
 *
 * @return string
 */
function _civicrm_get_xero_block_header() {
  return "<div class='crm-summary-row'>";
}

/**
 * @param $objectName
 * @param array $headers
 * @param $values
 * @param $selector
 */
function civixero_civicrm_searchColumns( $objectName, &$headers,  &$values, &$selector ) {
  if ($objectName == 'contribution') {
    foreach ($values as &$value) {
      try {
        $invoiceID = civicrm_api3('AccountInvoice', 'getvalue', array(
          'plugin' => 'xero',
          'contribution_id' => $value['contribution_id'],
          'return' => 'accounts_invoice_id',
        ));
        $value['contribution_status'] .= "<a href='https://go.xero.com/AccountsReceivable/View.aspx?InvoiceID=" . $invoiceID . "'> <p>Xero</p></a>";
      }
      catch (Exception $e) {
        continue;
      }
    }
  }
}

/**
 * Map xero accounts data to generic data.
 *
 * @param array $accountsData
 * @param string $entity
 * @param string $plugin
 */
function civixero_civicrm_mapAccountsData(&$accountsData, $entity, $plugin) {
  if ($plugin != 'xero' || $entity != 'contact') {
    return;
  }
  $accountsData['civicrm_formatted'] = array();
  $mappedFields = array(
    'Name' => 'display_name',
    'FirstName' => 'first_name',
    'LastName' => 'last_name',
    'EmailAddress' => 'email',
  );
  foreach ($mappedFields as $xeroField => $civicrmField) {
    if (!empty($accountsData[$xeroField])) {
      $accountsData['civicrm_formatted'][$civicrmField] = $accountsData[$xeroField];
    }
  }

  if (is_array($accountsData['Addresses']) && is_array($accountsData['Addresses']['Address'])) {
    foreach ($accountsData['Addresses']['Address'] as $address) {
      if (count($address) > 1) {
        $addressMappedFields = array(
          'AddressLine1' => 'street_address',
          'City' => 'city',
          'PostalCode' => 'postal_code',
        );
        foreach ($addressMappedFields as $xeroField => $civicrmField) {
          if (!empty($address[$xeroField])) {
            $accountsData['civicrm_formatted'][$civicrmField] = $address[$xeroField];
          }
        }
        break;
      }
    }
  }

  if (is_array($accountsData['Phones']) && is_array($accountsData['Phones']['Phone'])) {
    foreach ($accountsData['Phones']['Phone'] as $address) {
      if (count($address) > 1) {
        $addressMappedFields = array(
          'PhoneNumber' => 'phone',
        );
        foreach ($addressMappedFields as $xeroField => $civicrmField) {
          if (!empty($address[$xeroField])) {
            $accountsData['civicrm_formatted'][$civicrmField] = $address[$xeroField];
          }
        }
        break;
      }
    }
  }

}

/**
 * Implements hook_civicrm_accountsync_plugins().
 */
function civixero_civicrm_accountsync_plugins(&$plugins) {
  $plugins[] = 'xero';
}