|
|
@@ -21,12 +21,20 @@ use App\Service\Core\AddressPostalUtils;
|
|
|
use App\Service\Rest\Operation\BaseRestOperation;
|
|
|
use App\Service\Rest\Operation\CreateOperation;
|
|
|
use App\Service\Rest\Operation\UpdateOperation;
|
|
|
+use App\Service\Utils\ArrayUtils;
|
|
|
use Exception;
|
|
|
-use HttpException;
|
|
|
use libphonenumber\PhoneNumber;
|
|
|
use libphonenumber\PhoneNumberFormat;
|
|
|
use libphonenumber\PhoneNumberUtil;
|
|
|
use Psr\Log\LoggerInterface;
|
|
|
+use RuntimeException;
|
|
|
+use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
|
+use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
|
|
|
+use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
|
|
|
+use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
|
|
|
+use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
|
|
|
+use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
|
|
+use Symfony\Contracts\HttpClient\ResponseInterface;
|
|
|
use Symfony\Contracts\Translation\TranslatorInterface;
|
|
|
|
|
|
/**
|
|
|
@@ -91,7 +99,7 @@ class DolibarrSyncService
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
- // Populate the expectedContacts array
|
|
|
+ // Populate the expected contacts array
|
|
|
$organizationMembers = $membersIndex[$organization->getId()] ?? [];
|
|
|
|
|
|
// ===== Update Society =====
|
|
|
@@ -148,99 +156,119 @@ class DolibarrSyncService
|
|
|
$newSocietyData['array_options'] = $dolibarrSociety["array_options"];
|
|
|
$newSocietyData['array_options']['options_2iopeninfoopentalent'] = implode("\n", $infos);
|
|
|
|
|
|
- // Only update the fields that are different
|
|
|
- $newSocietyData = self::filterDiff($dolibarrSociety, $newSocietyData);
|
|
|
+ // Set the society as active (warning: use the field 'status' for societies, and not 'statut'!)
|
|
|
+ $newSocietyData['status'] = '1';
|
|
|
+
|
|
|
+ // Only update the fields that are different (it's important to let it non-recursive, the subarray have to be passed entirely)
|
|
|
+ $newSocietyData = ArrayUtils::getChanges(
|
|
|
+ $dolibarrSociety,
|
|
|
+ $newSocietyData,
|
|
|
+ false,
|
|
|
+ static function ($v1, $v2) { return ($v1 ?? '') === ($v2 ?? ''); }
|
|
|
+ );
|
|
|
|
|
|
// Add an update operation if some data has to be updated
|
|
|
if (!empty($newSocietyData)) {
|
|
|
$operations[] = new UpdateOperation(
|
|
|
'Update society : ' . $organization->getName() . ' (' . $organization->getId() . ')',
|
|
|
'thirdparties',
|
|
|
- $dolibarrSociety,
|
|
|
- $newSocietyData
|
|
|
+ (int)$dolibarrSociety['id'],
|
|
|
+ $newSocietyData,
|
|
|
+ $dolibarrSociety
|
|
|
);
|
|
|
}
|
|
|
|
|
|
// ===== Update Contacts =====
|
|
|
- $dolibarrContactsIndex = $this->getDolibarrContactsIndex((int)$dolibarrSociety['id']);
|
|
|
+ $dolibarrSocietyContacts = $this->dolibarrApiService->getContacts((int)$dolibarrSociety['id']);
|
|
|
$contactsProcessed = [];
|
|
|
|
|
|
foreach ($organizationMembers as $accessId => $missions) {
|
|
|
- foreach ($missions as $mission) {
|
|
|
- if (in_array($mission, FunctionEnum::getOfficeMissions(), true)) {
|
|
|
- $access = $this->accessRepository->find($accessId);
|
|
|
- if ($access === null) {
|
|
|
- continue;
|
|
|
- }
|
|
|
-
|
|
|
- $person = $access->getPerson();
|
|
|
- if ($person === null) {
|
|
|
- continue;
|
|
|
- }
|
|
|
-
|
|
|
- // Keep track of the contacts seen
|
|
|
- if (in_array($person->getId(), $contactsProcessed, true)) {
|
|
|
- // already updated from another mission
|
|
|
- continue;
|
|
|
- }
|
|
|
- $contactsProcessed[] = $person->getId();
|
|
|
-
|
|
|
- // special: if the contact has no name, ignore it
|
|
|
- if (!$person->getName()) {
|
|
|
- continue;
|
|
|
- }
|
|
|
-
|
|
|
- // Build parameters for the query (if a query is needed
|
|
|
- $dolibarrContact = $dolibarrContactsIndex[$person->getId()] ?? null;
|
|
|
- $dolibarrContact = self::sanitizeDolibarrData($dolibarrContact);
|
|
|
-
|
|
|
- $contact = $this->getPersonContact($person);
|
|
|
-
|
|
|
- $newContactData = [
|
|
|
- 'civility_code' => $person->getGender() ? $this->translator->trans($person->getGender()) : null,
|
|
|
- 'lastname' => trim($person->getName()),
|
|
|
- 'firstname' => trim($person->getGivenName()),
|
|
|
- 'email' => $contact?->getEmail(),
|
|
|
- 'phone_pro' => $contact?->getTelphone() ? self::formatPhoneNumber($contact?->getTelphone()) : null,
|
|
|
- 'phone_mobile' => $contact?->getMobilPhone() ? self::formatPhoneNumber($contact?->getMobilPhone()): null,
|
|
|
- 'poste' => $this->formatContactPosition($missions, $person->getGender())
|
|
|
- ];
|
|
|
-
|
|
|
- if ($dolibarrContact === null) {
|
|
|
- // New contact
|
|
|
- $newContactData['socid'] = (int)$dolibarrSociety['id'];
|
|
|
- $newContactData['array_options'] = [
|
|
|
- 'options_2iopen_person_id' => $person->getId()
|
|
|
- ];
|
|
|
-
|
|
|
- $operations[] = new CreateOperation(
|
|
|
- 'New contact: ' . $person->getName() . ' ' . $person->getGivenName() . ' (' . $person->getId() . ')',
|
|
|
- 'contacts',
|
|
|
- $newContactData
|
|
|
- );
|
|
|
- } else {
|
|
|
- // Only update the fields that are different
|
|
|
- $newContactData = self::filterDiff($dolibarrContact, $newContactData);
|
|
|
-
|
|
|
- // add an update operation if some data has to be updated
|
|
|
- if (!empty($newContactData)) {
|
|
|
- $operations[] = new UpdateOperation(
|
|
|
- 'Update contact: ' . $person->getName() . ' ' . $person->getGivenName() . ' (' . $person->getId() . ')' .
|
|
|
- ' in ' . $organization->getName() . ' (' . $organization->getId() . ')',
|
|
|
- 'contacts',
|
|
|
- $dolibarrContact,
|
|
|
- $newContactData,
|
|
|
- );
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- // No need to test the other missions of this access
|
|
|
- break;
|
|
|
+ // Check if member has office missions, skip if it doesn't
|
|
|
+ if (empty(array_intersect($missions, FunctionEnum::getOfficeMissions()))) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ $access = $this->accessRepository->find($accessId);
|
|
|
+ $person = $access?->getPerson();
|
|
|
+
|
|
|
+ if ($person === null) // this should not happen, but is expected by code inspection...
|
|
|
+ { throw new \Exception('Access or person not found'); }
|
|
|
+
|
|
|
+ // Keep track of the contacts seen
|
|
|
+ if (in_array($person->getId(), $contactsProcessed, true)) {
|
|
|
+ // already updated from another mission
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ $contactsProcessed[] = $person->getId();
|
|
|
+
|
|
|
+ // special: if the contact has no name, ignore it
|
|
|
+ if (!$person->getName() || !$person->getGivenName()) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ // Get the matching dolibarr contact
|
|
|
+ $dolibarrContact = self::findDolibarrContactFor($dolibarrSocietyContacts, $person);
|
|
|
+ $dolibarrContact = self::sanitizeDolibarrData($dolibarrContact);
|
|
|
+
|
|
|
+ $contact = $this->getPersonContact($person);
|
|
|
+
|
|
|
+ // Build parameters for the query (we'll see later if a query is needed)
|
|
|
+ $newContactData = [
|
|
|
+ 'civility_code' => $person->getGender() ? $this->translator->trans($person->getGender()) : null,
|
|
|
+ 'lastname' => trim($person->getName()),
|
|
|
+ 'firstname' => trim($person->getGivenName()),
|
|
|
+ 'email' => $contact?->getEmail(),
|
|
|
+ 'phone_pro' => $contact?->getTelphone() ? self::formatPhoneNumber($contact?->getTelphone()) : null,
|
|
|
+ 'phone_mobile' => $contact?->getMobilPhone() ? self::formatPhoneNumber($contact?->getMobilPhone()): null,
|
|
|
+ 'poste' => $this->formatContactPosition($missions, $person->getGender()),
|
|
|
+ 'statut' => '1'
|
|
|
+ ];
|
|
|
+
|
|
|
+ // The person's id may be missing if the contact is new or if it was found through its name
|
|
|
+ if ($dolibarrContact !== null && !(empty($dolibarrContact["array_options"] ?? []))) {
|
|
|
+ $newContactData["array_options"] = $dolibarrContact["array_options"];
|
|
|
+ } else {
|
|
|
+ $newContactData["array_options"] = [];
|
|
|
+ }
|
|
|
+ $newContactData["array_options"]["options_2iopen_person_id"] = (string)$person->getId();
|
|
|
+
|
|
|
+ if ($dolibarrContact === null) {
|
|
|
+ // New contact
|
|
|
+ $newContactData['socid'] = (int)$dolibarrSociety['id'];
|
|
|
+
|
|
|
+ $operations[] = new CreateOperation(
|
|
|
+ 'New contact: ' . $person->getName() . ' ' . $person->getGivenName() . ' (' . $person->getId() . ')',
|
|
|
+ 'contacts',
|
|
|
+ $newContactData
|
|
|
+ );
|
|
|
+ } else {
|
|
|
+ // Only update the fields that are different (it's important to let it non-recursive, the subarray have to be passed entirely)
|
|
|
+ $newContactData = ArrayUtils::getChanges(
|
|
|
+ $dolibarrContact,
|
|
|
+ $newContactData,
|
|
|
+ false,
|
|
|
+ static function ($v1, $v2) { return ($v1 ?? '') === ($v2 ?? ''); }
|
|
|
+ );
|
|
|
+
|
|
|
+ // add an update operation if some data has to be updated
|
|
|
+ if (!empty($newContactData)) {
|
|
|
+ $operations[] = new UpdateOperation(
|
|
|
+ 'Update contact: ' . $person->getName() . ' ' . $person->getGivenName() . ' (' . $person->getId() . ')' .
|
|
|
+ ' in ' . $organization->getName() . ' (' . $organization->getId() . ')',
|
|
|
+ 'contacts',
|
|
|
+ (int)$dolibarrContact['id'],
|
|
|
+ $newContactData,
|
|
|
+ $dolibarrContact
|
|
|
+ );
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- foreach ($dolibarrContactsIndex as $personId => $contactData) {
|
|
|
+ foreach ($dolibarrSocietyContacts as $contactData) {
|
|
|
+ if (empty($contactData["array_options"]["options_2iopen_person_id"])) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ $personId = (int)$contactData["array_options"]["options_2iopen_person_id"];
|
|
|
if ((int)$contactData['statut'] === 0) {
|
|
|
// contact is already disabled
|
|
|
continue;
|
|
|
@@ -251,8 +279,9 @@ class DolibarrSyncService
|
|
|
'Disable contact: ' . $contactData['lastname'] . ' ' . $contactData['firstname'] . ' (' . $personId . ')' .
|
|
|
' from ' . $organization->getName() . ' (' . $organization->getId() . ')',
|
|
|
'contacts',
|
|
|
- $contactData,
|
|
|
- ['statut' => 0]
|
|
|
+ (int)$contactData['id'],
|
|
|
+ ['statut' => '0'],
|
|
|
+ $contactData
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
@@ -265,14 +294,6 @@ class DolibarrSyncService
|
|
|
}
|
|
|
|
|
|
$this->logger->info('Scan done, ' . count($operations) . ' required operations listed');
|
|
|
- foreach ($operations as $operation) {
|
|
|
- $this->logger->debug($operation->getLabel());
|
|
|
- foreach ($operation->getChangeLog() as $message) {
|
|
|
- $this->logger->debug(' ' . $message);
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- $this->logger->info('Scan ended');
|
|
|
return $operations;
|
|
|
}
|
|
|
|
|
|
@@ -295,23 +316,42 @@ class DolibarrSyncService
|
|
|
|
|
|
$i = 0; $total = count($operations);
|
|
|
foreach ($operations as $operation) {
|
|
|
- if ($operation->getStatus() !== BaseRestOperation::STATUS_READY) {
|
|
|
+ if ($operation->getStatus() !== $operation::STATUS_READY) {
|
|
|
// operation has already been treated
|
|
|
$this->logger->warning('Tried to execute an operation that was not marked as ready : ' . $operation);
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
- $operation->execute($this->dolibarrApiService);
|
|
|
+ $this->logger->debug($operation->getLabel());
|
|
|
+ foreach ($operation->getChangeLog() as $message) {
|
|
|
+ $this->logger->debug(' ' . $message);
|
|
|
+ }
|
|
|
+
|
|
|
+ try {
|
|
|
+ // Execute the request
|
|
|
+ $response = $operation->execute($this->dolibarrApiService);
|
|
|
|
|
|
- if ($operation->getStatus() === BaseRestOperation::STATUS_ERROR) {
|
|
|
+ // Check the status
|
|
|
+ if ($operation->getStatus() !== $operation::STATUS_DONE) {
|
|
|
+ $unknown++;
|
|
|
+ throw new RuntimeException('Operation has an inconsistent status : ' . $operation->getStatus());
|
|
|
+ }
|
|
|
+
|
|
|
+ // If this is an update operation, validate the result
|
|
|
+ if ($operation instanceof UpdateOperation) {
|
|
|
+ try {
|
|
|
+ $this->validateResponse($response, $operation);
|
|
|
+ } catch (RuntimeException $e) {
|
|
|
+ $this->logger->warning($e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ $done++;
|
|
|
+ } catch (RuntimeException $e) {
|
|
|
$this->logger->error('Error while executing operation : ' . $operation);
|
|
|
$this->logger->error(implode("\n", $operation->getChangeLog()));
|
|
|
- $this->logger->error($operation->getErrorMessage());
|
|
|
+ $this->logger->error($e);
|
|
|
$errors++;
|
|
|
- } elseif ($operation->getStatus() === BaseRestOperation::STATUS_DONE) {
|
|
|
- $done++;
|
|
|
- } else {
|
|
|
- $unknown++;
|
|
|
}
|
|
|
|
|
|
$i++;
|
|
|
@@ -357,6 +397,13 @@ class DolibarrSyncService
|
|
|
foreach ($this->dolibarrApiService->getAllClients() as $clientData) {
|
|
|
$organizationId = $clientData["array_options"]["options_2iopen_organization_id"] ?? null;
|
|
|
if (!($organizationId > 0)) {
|
|
|
+
|
|
|
+ // Ignoring clients without contract
|
|
|
+ $contract = $this->dolibarrApiService->getActiveContract((int)$clientData['id']);
|
|
|
+ if (empty($contract)) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
$this->logger->warning(
|
|
|
'Dolibarr client has no organization id: ' .
|
|
|
$clientData['name'] . ' (' . $clientData['id'] . ')'
|
|
|
@@ -369,21 +416,6 @@ class DolibarrSyncService
|
|
|
return $index;
|
|
|
}
|
|
|
|
|
|
- /**
|
|
|
- * Get the dolibarr contacts of the society and index them by person_id
|
|
|
- *
|
|
|
- * @return array An index of the form [$personId => $dolibarrData]
|
|
|
- */
|
|
|
- protected function getDolibarrContactsIndex(int $socId): array {
|
|
|
- $index = [];
|
|
|
- $contacts = $this->dolibarrApiService->getOpentalentContacts($socId);
|
|
|
- foreach ($contacts as $contactData) {
|
|
|
- $personId = (int)$contactData["array_options"]["options_2iopen_person_id"];
|
|
|
- $index[$personId] = $contactData;
|
|
|
- }
|
|
|
- return $index;
|
|
|
- }
|
|
|
-
|
|
|
/**
|
|
|
* Returns an index of all the active members with their current mission(s)
|
|
|
*
|
|
|
@@ -410,6 +442,38 @@ class DolibarrSyncService
|
|
|
return $index;
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * Get the first contact that has the same person id.
|
|
|
+ *
|
|
|
+ * If none are found with the person id, try to find one with the same full name and no person id
|
|
|
+ *
|
|
|
+ * @param array $dolibarrContacts
|
|
|
+ * @param Person $person
|
|
|
+ * @return array|null
|
|
|
+ */
|
|
|
+ protected static function findDolibarrContactFor(array $dolibarrContacts, Person $person): ?array {
|
|
|
+ foreach ($dolibarrContacts as $contactData) {
|
|
|
+ if (!empty($contactData["array_options"]["options_2iopen_person_id"])) {
|
|
|
+ $id = (int)$contactData["array_options"]["options_2iopen_person_id"];
|
|
|
+
|
|
|
+ if ($id === $person->getId()) {
|
|
|
+ return $contactData;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ foreach ($dolibarrContacts as $contactData) {
|
|
|
+ if (
|
|
|
+ !($contactData["array_options"]["options_2iopen_person_id"] ?? null) &&
|
|
|
+ $person->getName() === $contactData["lastname"] &&
|
|
|
+ $person->getGivenName() === $contactData["firstname"]
|
|
|
+ ) {
|
|
|
+ return $contactData;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* Because for some fields the dolibarr api returns empty strings even when field is null in DB,
|
|
|
* we have to post-process it to avoid unnecessary and endless update operations
|
|
|
@@ -615,30 +679,43 @@ class DolibarrSyncService
|
|
|
);
|
|
|
}
|
|
|
|
|
|
+
|
|
|
/**
|
|
|
- * Returns an array containing the keys/values from the newData array
|
|
|
- * which are absent or different from $initialData
|
|
|
- *
|
|
|
- * /!\ Sub-arrays shall stay complete and must not be filtered
|
|
|
- *
|
|
|
- * Because for some fields the dolibarr api returns empty strings even when field is null in DB,
|
|
|
- * we have to consider null and empty-string as equals. As far as we know, this causes no loss of information.
|
|
|
+ * Post-validation of the execution of the operation.
|
|
|
+ * In the case of a validation error, throw an HttpException
|
|
|
*
|
|
|
- * @param array $initialData
|
|
|
- * @param array $newData
|
|
|
- * @return array
|
|
|
+ * @param ResponseInterface $response
|
|
|
+ * @param BaseRestOperation $operation
|
|
|
+ * @throws RuntimeException
|
|
|
*/
|
|
|
- protected static function filterDiff(array $initialData, array $newData): array
|
|
|
+ protected function validateResponse(ResponseInterface $response, BaseRestOperation $operation): void
|
|
|
{
|
|
|
- $result = [];
|
|
|
- foreach ($newData as $field => $value) {
|
|
|
- if (
|
|
|
- ($value ?? '') !== ($initialData[$field] ?? '') ||
|
|
|
- !array_key_exists($field, $initialData)
|
|
|
- ) {
|
|
|
- $result[$field] = $value;
|
|
|
- }
|
|
|
+ $updated = $operation->getData();
|
|
|
+ if ($updated === null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ try {
|
|
|
+ $responseData = $response->toArray();
|
|
|
+ } catch (ClientExceptionInterface | DecodingExceptionInterface | RedirectionExceptionInterface | ServerExceptionInterface | TransportExceptionInterface $e) {
|
|
|
+ throw new RuntimeException(
|
|
|
+ "Couldn't read the content of the response : " . $e
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ // Sanitize to get rid of the null / empty strings transformations of the API
|
|
|
+ $updated = self::sanitizeDolibarrData($updated);
|
|
|
+ $responseData = self::sanitizeDolibarrData($responseData);
|
|
|
+
|
|
|
+ $diffs = ArrayUtils::getChanges($responseData, $updated, true);
|
|
|
+
|
|
|
+ if (!empty($diffs)) {
|
|
|
+ /** @noinspection JsonEncodingApiUsageInspection */
|
|
|
+ throw new RuntimeException(
|
|
|
+ "The " . $operation->getMethod() . " request had an unexpected result.\n" .
|
|
|
+ "Expected content: " . json_encode($updated) . "\n" .
|
|
|
+ "Actual content : " . json_encode($responseData)
|
|
|
+ );
|
|
|
}
|
|
|
- return $result;
|
|
|
}
|
|
|
}
|