-
Notifications
You must be signed in to change notification settings - Fork 14
/
Civixero.php
executable file
·411 lines (380 loc) · 12.8 KB
/
Civixero.php
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
<?php
use Civi\API\Exception\UnauthorizedException;
use Civi\Api4\AccountContact;
use Civi\Api4\AccountInvoice;
use Psr\Log\LogLevel;
use CRM_Civixero_ExtensionUtil as E;
require_once 'Civixero.civix.php';
/**
* Implementation of hook_civicrm_config
*
* @param \CRM_Core_Config $config
*/
function civixero_civicrm_config(CRM_Core_Config $config) {
_civixero_civix_civicrm_config($config);
\Civi::dispatcher()->addListener('civi.api.prepare', ['CRM_Civixero_Base', 'checkApiRateExceeded']);
require_once __DIR__ . '/vendor/autoload.php';
if (!function_exists('random_bytes')) {
require_once(__DIR__ . '/vendor/paragonie/random_compat/lib/random.php');
}
}
/**
* Implementation of hook_civicrm_install
*/
function civixero_civicrm_install() {
_civixero_civix_civicrm_install();
}
/**
* Implementation of hook_civicrm_enable
*/
function civixero_civicrm_enable() {
_civixero_civix_civicrm_enable();
}
/**
* 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 :-)
*
* @param string $extension
*
* @return bool
* @todo - test using CRM_Extension_System::singleton()->getManager()->getStatus($key)
*
*/
function civixero_is_extension_installed(string $extension): bool {
return ($extension === 'nz.co.fuzion.connectors') && function_exists('connectors_civicrm_entityTypes');
}
/**
* Implements hook_civicrm_alterSettingsMetaData(().
*
* This hook sets the default for each setting to our preferred value.
* It can still be overridden by specifically setting the setting.
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_alterSettingsMetaData/
*/
function civixero_civicrm_alterSettingsMetaData(array &$settingsMetaData): void {
$weight = 100;
foreach ($settingsMetaData as $index => $setting) {
if (($setting['group'] ?? '') === 'accountsync') {
$settingsMetaData[$index]['settings_pages'] = ['xero' => ['weight' => $weight]];
}
$weight++;
}
}
/**
* Get contributions for a single contact.
*
* @param int $contactID
*
* @return array
* @throws \CiviCRM_API3_Exception
*/
function getContactContributions(int $contactID): array {
$contributions = civicrm_api3('Contribution', 'get', [
'contact_id' => $contactID,
'return' => ['contribution_id'],
'sequential' => TRUE,
])['values'];
return array_column($contributions, 'id');
}
/**
* Get AccountInvoice data for contributions with errors.
*
* @param array $contributions
*
* @return array
*
* @throws \CiviCRM_API3_Exception
*/
function getErroredInvoicesOfContributions(array $contributions): array {
return civicrm_api3('AccountInvoice', 'get', [
'plugin' => 'xero',
'sequential' => TRUE,
'contribution_id' => ['IN' => $contributions],
'error_data' => ['<>' => ''],
]);
}
/**
* Implementation of hook_civicrm_check.
*
* Add a check to the status page. Check if there are any account contact or invoice sync errors.
*
* @param array $messages
*
* @throws \CRM_Core_Exception
*/
function civixero_civicrm_check(array &$messages) {
try {
$accountContactErrors = AccountContact::get()
->selectRowCount()
->addWhere('error_data', 'IS NOT NULL')
->addWhere('plugin', '=', 'xero')
->addWhere('is_error_resolved', '=', FALSE)
->execute()->count();
$accountInvoiceErrors = AccountInvoice::get()
->selectRowCount()
->addWhere('error_data', 'IS NOT NULL')
->addWhere('plugin', '=', 'xero')
->addWhere('is_error_resolved', '=', FALSE)
->execute()->count();
$errorMessage = '';
}
catch (UnauthorizedException $e) {
// Fine - skip the check. We want ACLs to apply but not to
// error out if they don't have any permissions
return;
}
if ($accountContactErrors > 0) {
$errorMessage .= 'Found ' . $accountContactErrors . ' contact sync errors. <a href="' . CRM_Utils_System::url('civicrm/accounting/errors/contacts') . '" 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="' . CRM_Utils_System::url('civicrm/accounting/errors/invoices') . '" 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',
LogLevel::ERROR,
'fa-refresh'
);
}
foreach (array_keys(_civixero_get_connectors()) as $connectorID) {
$settings = new CRM_Civixero_Settings($connectorID);
$clientID = $settings->get('xero_client_id');
$clientSecret = $settings->get('xero_client_secret');
$accessTokenData = $settings->get('xero_access_token');
$url = CRM_Utils_System::url('civicrm/xero/authorize', $connectorID ? 'connector_id=' . $connectorID : '');
if (!$clientID || !$clientSecret) {
$messages[] = new CRM_Utils_Check_Message(
'civixero_client_required',
E::ts('Please configure a Client ID and Client Secret from your Xero app.'),
E::ts('Missing Xero App Details'),
LogLevel::WARNING,
'fa-flag'
);
}
elseif (empty($accessTokenData['access_token'])) {
$messages[] = new CRM_Utils_Check_Message(
'civixero_authorization_required',
'<a href = ' . $url . '>' .
E::ts('Please Authorize with Xero to enable a connection.') . '</a>',
E::ts('Xero Authorization Required'),
LogLevel::WARNING,
'fa-flag'
);
}
elseif (isset($accessTokenData['expires']) && ($accessTokenData['expires'] <= time())) {
$messages[] = new CRM_Utils_Check_Message(
'civixero_authorization_required',
'<a href = ' . $url . '>' . E::ts('Xero access token has expired. You need to re-authorize with Xero to re-enable the connection.') . '</a>',
E::ts('Xero Authorization Required'),
LogLevel::CRITICAL,
'fa-flag'
);
}
}
}
/**
* Implements hook pageRun().
*
* Add Xero links to contact summary
*
* @param $page
*/
function civixero_civicrm_pageRun($page) {
$pageName = get_class($page);
switch ($pageName) {
case 'CRM_Contact_Page_View_Summary':
if ($pageName !== 'CRM_Contact_Page_View_Summary' || !CRM_Core_Permission::check('view all contacts')) {
return;
}
if (($contactID = $page->getVar('_contactId')) !== FALSE) {
CRM_Civixero_Page_Inline_ContactSyncStatus::addContactSyncStatusBlock($page, $contactID);
CRM_Civixero_Page_Inline_ContactSyncLink::addContactSyncLinkBlock($page, $contactID);
CRM_Civixero_Page_Inline_ContactSyncErrors::addContactSyncErrorsBlock($page, $contactID);
CRM_Civixero_Page_Inline_InvoiceSyncErrors::addInvoiceSyncErrorsBlock($page, $contactID);
CRM_Core_Region::instance('contact-basic-info-left')->add([
'template' => 'CRM/Civixero/ContactSyncBlock.tpl',
]);
}
break;
case 'CRM_Contribute_Page_Tab':
$contributionID = CRM_Utils_Request::retrieve('id', 'Positive', $page);
if (!empty($contributionID)) {
$accountInvoice = \Civi\Api4\AccountInvoice::get(FALSE)
->addSelect('accounts_status_id:label', 'accounts_invoice_id')
->addWhere('contribution_id', '=', $contributionID)
->addWhere('plugin', '=', 'xero')
->execute()
->first();
if (!empty($accountInvoice)) {
CRM_Core_Region::instance('page-footer')->add(['template' => 'CRM/Civixero/Page/Inline/ContributionInvoiceLink.tpl']);
$page->assign('xero_invoice_label', E::ts('Xero'));
if ($accountInvoice['accounts_status_id'] === (int) CRM_Core_PseudoConstant::getKey('CRM_Accountsync_BAO_AccountInvoice', 'accounts_status_id', 'unknown')) {
$link = $accountInvoice['accounts_status_id:label'];
}
else {
$link = "<a href=\"https://go.xero.com/AccountsReceivable/View.aspx?InvoiceID={$accountInvoice['accounts_invoice_id']}\">{$accountInvoice['accounts_status_id:label']}</a>";
}
$page->assign('xero_invoice_status', $link);
}
}
break;
}
}
/**
* Get available connectors.
*
* @return array
*/
function _civixero_get_connectors(): array {
static $connectors = [];
if (empty($connectors)) {
try {
$entities = civicrm_api3('Entity', 'get')['values'];
if (!in_array('ConnectorType', $entities, TRUE)) {
return [0 => ['id' => 0, 'name' => '']];
}
$connectors = civicrm_api3('connector', 'get', ['connector_type_id' => 'CiviXero']);
$connectors = $connectors['values'];
}
catch (CRM_Core_Exception $e) {
$connectors = [0 => ['id' => 0, 'name' => '']];
}
}
return $connectors;
}
/**
* @param string $objectName
* @param array $headers
* @param array|null $values
*
* @noinspection PhpUnusedParameterInspection
*/
function civixero_civicrm_searchColumns(string $objectName, array &$headers, ?array &$values) {
if ($objectName === 'contribution') {
foreach ($values as &$value) {
try {
$invoiceID = civicrm_api3('AccountInvoice', 'getvalue', [
'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(array &$accountsData, string $entity, string $plugin) {
if ($plugin !== 'xero' || $entity !== 'contact') {
return;
}
$accountsData['civicrm_formatted'] = [];
$mappedFields = [
'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 = [
'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 = [
'PhoneNumber' => 'phone',
];
foreach ($addressMappedFields as $xeroField => $civicrmField) {
if (!empty($address[$xeroField])) {
$accountsData['civicrm_formatted'][$civicrmField] = $address[$xeroField];
}
}
break;
}
}
}
}
/**
* Implements hook_civicrm_accountsync_plugins().
*
* @param $plugins
*/
function civixero_civicrm_accountsync_plugins(&$plugins) {
$plugins[] = 'xero';
}
/**
* Implements hook_civicrm_contactSummaryBlocks().
*
* @link https://github.com/civicrm/org.civicrm.contactlayout
*
* @param $blocks
*/
function civixero_civicrm_contactSummaryBlocks(&$blocks) {
$blocks += [
'civixeroblock' => [
'title' => E::ts('Civi Xero'),
'blocks' => [],
],
];
$blocks['civixeroblock']['blocks']['contactsyncstatus'] = [
'title' => E::ts('Contact Sync Status'),
'tpl_file' => 'CRM/Civixero/Page/Inline/ContactSyncStatus.tpl',
'edit' => FALSE,
];
$blocks['civixeroblock']['blocks']['contactsyncerrors'] = [
'title' => E::ts('Contact Sync Errors'),
'tpl_file' => 'CRM/Civixero/Page/Inline/ContactSyncErrors.tpl',
'edit' => FALSE,
];
$blocks['civixeroblock']['blocks']['invoicesyncerrors'] = [
'title' => E::ts('Invoice Sync Errors'),
'tpl_file' => 'CRM/Civixero/Page/Inline/InvoiceSyncErrors.tpl',
'edit' => FALSE,
];
$blocks['civixeroblock']['blocks']['invoicesynclink'] = [
'title' => E::ts('Invoice Sync Link'),
'tpl_file' => 'CRM/Civixero/Page/Inline/InvoiceSyncLink.tpl',
'edit' => FALSE,
];
$blocks['civixeroblock']['blocks']['contactsynclink'] = [
'title' => E::ts('Contact Sync Link'),
'tpl_file' => 'CRM/Civixero/Page/Inline/ContactSyncLink.tpl',
'edit' => FALSE,
];
}