assignmentResource->getConnection(); $assignmentIds = []; $connection->beginTransaction(); try { foreach (array_values($codes) as $index => $code) { $coupon = $this->couponFactory->create()->load($code, 'code'); if (!$coupon->getId()) { throw new LocalizedException(__('The generated coupon "%1" could not be loaded.', $code)); } $assignment = $this->assignmentFactory->create(); $assignment->setData([ 'coupon_id' => (int)$coupon->getId(), 'rule_id' => $ruleId, 'customer_id' => (int)$customerIds[$index], 'source' => $source, ]); $this->assignmentResource->save($assignment); $assignmentIds[] = (int)$assignment->getId(); } $connection->commit(); } catch (\Throwable $exception) { $connection->rollBack(); throw $exception; } foreach ($assignmentIds as $assignmentId) { try { $this->couponNotifier->notify($assignmentId); } catch (\Throwable) { // Notification delivery is best-effort and must not invalidate an assigned coupon. } } } }