I am trying to create a simple hook_cron to connect with an external API, return some data and update some fields in some entities. I'm creating like this to understand better how cron works, so I will upgrade it later to a queue.
The problem is that the cron is running, but even without errors the entity is not saving or updating. If I copy the code and try to execute it with a route (not using cron), it works as intended. I really don't know what is the problem with it.
I thank you for your help.
The code below:
function correios_web_service_cron()
{
$trackingService = \Drupal::service('correios_web_service.tracking');
$eventService = \Drupal::service('correios_web_service.event');
$error = null;
try {
$order_ids = \Drupal::entityQuery('commerce_order')
->condition('type', 'campaign') //! Ver se terá que mudar o tipo
->condition('state', $eventService->getStatusByAlias('entregue')['description'], '<>')
->condition('state', $eventService->getStatusByAlias('avaliado')['description'], '<>')
->condition('state', $eventService->getStatusByAlias('cancelado')['description'], '<>')
->condition('field_tracking_code', NULL, '<>')
->execute();
$Orders = \Drupal::entityTypeManager()->getStorage('commerce_order')->loadMultiple($order_ids);
}
catch (\Throwable $e) {
$error = $e->getMessage();
}
if (empty($error) && !empty($Orders)) {
foreach ($Orders as $Order) {
$tracking_code = $Order->get('field_tracking_code')->value;
try {
$response = $trackingService->trackObjectFormatted($tracking_code);
$Order->set('state', $response['description']);
$Order->set('field_tracking_event_code', $response['event_code']);
$Order->set('field_tracking_event_message', $response['event_message']);
$Order->set('field_tracking_delivery_date', $response['delivery_date']);
$Order->save();
}
catch (\Throwable $e) {
\Drupal::logger('correios_web_service_cron')->error($e->getMessage());
}
}
}
if (!empty($error)) {
\Drupal::logger('correios_web_service_cron')->error($error);
}
}