Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added: error notification on draft creation failure #559

Open
wants to merge 1 commit into
base: release/4.0.7
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions src/services/repository/DraftRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ public function getDraftById($draftId, $siteId)
public function saveDraft($element)
{
$element->validate();
if($element->getErrors()){
return $element->getErrors();
if($element->getErrors()) {
// Extract the error messages from the element's errors
$errorMessages = $this->extractErrorMessages($element->getErrors());
throw new Exception("Validation failed: " . $errorMessages);
}

return Craft::$app->elements->saveElement($element, true, true, false);
Expand Down Expand Up @@ -188,9 +190,12 @@ public function createOrderDrafts($orderId, $wordCounts, $publish, $fileIds, $qu
$currentElement = 0;

$createDrafts = new CreateDrafts();
$transaction = Craft::$app->db->beginTransaction();


foreach ($order->getFiles() as $file) {
/* Create transaction per file so that in case a file has validation error
only that will be rolledback and others can be processed */
$transaction = Craft::$app->db->beginTransaction();

if (! in_array($file->id, $fileIds)) {
continue;
}
Expand Down Expand Up @@ -231,12 +236,13 @@ public function createOrderDrafts($orderId, $wordCounts, $publish, $fileIds, $qu
if ($publish) {
$this->applyDrafts($order->id, [$element->id], [$file->id], $queue);
}
$transaction->commit();
} catch(Exception $e) {
$transaction->rollback();
throw $e;
$this->setError($e->getMessage());
continue;
}
}
$transaction->commit();

if ($isNewDraft)
$order->logActivity(Translations::$plugin->translator->translate('app', 'Drafts created'));
Expand Down Expand Up @@ -418,4 +424,25 @@ public function deleteDraft($draftId, $siteId)
throw $e;
}
}

/**
* Extract error messages from an error object in string format
*/
private function extractErrorMessages($errorObject)
{
$errorMessages = [];

// Iterate through each key in the error object
foreach ($errorObject as $field => $messages) {
if (is_array($messages)) {
// Iterate through each error message in the array
foreach ($messages as $message) {
$errorMessages[] = $message; // Add the message to the list
}
}
}

// Return the concatenated error messages as a string
return implode("\n", $errorMessages);
}
}