Skip to content

Commit ccfc138

Browse files
cedrancontardiThiago ContardiGabrielAntalcarolineesteves
authored
Criação de filas para os callbacks (Cancelamento) (#17)
* feat: added new credit card form * feat: added setup for old settings and minor bugfixes * fix: error with 1i18n on setting's page * fix: allow all countris by default * i18n: add new terms for language file * feat: added max installments and minum installment value * feat: added reseller token to transactions * feat: added reseller token to transactions * feat: send tracking code to Vindi * fix: mask also reseller token and token account * fix: when the card number comes with 4 digits, don't add 20 before it * fix: when the card number comes with 4 digits, don't add 20 before it * doc: added pull request template * fix: observer to bankslippix * fix: cancel unapproved orders without config * feat: adjust with phpstan * fix: error monitoring transactions * fix: worng price additional * fix: update terms to ask for a CPF on checkout * feat: don't auto select TaxVat when is not a CPF number * feat: don't auto select TaxVat when is not a CPF number * Payment link functionality created * Vindi payment method verification to send the payment link has been added * The payment link email template changed and made an email configuration to set the template * Template Id changed * Email path and list fixed * feat/VINDI-143: estilo da pagina de link de pagamento com boleto, pix, bolepix e cartao * feat/VINDI-143: estilizacao pagina link de pagamento * Use strict added to js file * ko library added * float cast removed * Applying the requested changes on payment link files * adding the vindi_customer_taxvat to additionalInformation * Fixing the bugs about payment link * VP module version has been updated * payment link email template has been changed * Deleting the payment link when it is expired * Fixing the payment link summary details * Adding a discount verification * Making the discount value positive * fix: change fingerprint loader * VINDI-143: pagina de sucesso * VINDI-143: mensagem de desconto no link de pagamento * Remove linha comentada * The payment link delete has been removed from the payment link page * fix: add fingerprint method in define * fix: customer without taxvat * fix: preventing conflict with the vindi recurrence module * feat: adding security validations and better payment link management * fix: phpstan fix * feat: creating mass sending of payment link * fix: remove await vindi fingerprint * feat: add translate * feat: automatically cancels orders whose payment link has expired more than 30 days ago * feat: custom email template * fix: remove await vindi fingerprint * fix: remove await vindi fingerprint * refactor: adding validation on payment methods and payment link success page * fix: change form with get status * feat: implementing single view system on success page * feat: translate * fix: remove await vindi fingerprint * fix: remove await vindi fingerprint * feat: expire_at field * update * update * update * update * fix: processing payment link when canceling * fix: Adjust payment data displays if the order has already been invoiced * feat: added refund functionality * fix: allow to refund * fix: remove default consumer-key, consumer secret * fix: remove default consumer-key, consumer secret * fix: remove default consumer-key, consumer secret * feat: create authentication button * refactor: add logging in refund flow * fix: address saving repeated * fix: address saving repeated * fix: logger in helper * fix: logger in helper * fix: logger in helper * refactor: add log in RefundRequest * refactor: add log in RefundRequest * refactor: add log in RefundRequest * fix: correcting the way the access_token is taken * fix: generate new access_token * refactor: refactoring duplicate code and creating tests * refactor: refactoring duplicate code and creating tests * refactor: refactoring duplicate code and creating tests * fix: call fingerprint script in all pages * fix: regenerate acces_token * v1.4.1 * fix: refresh token error * fix: it should not be possible to generate payment link via the frontend * feat: added text to return URL * fix: round the discount tag * feat: creation for callback queue management * feat: create ProcessCallbackQueueCommand console * refactor: adjusting documentation and validation * refactor: add logs * refactor: add logs --------- Co-authored-by: Thiago Contardi <thiagocontardi@hotmail.com> Co-authored-by: Thiago Contardi <thiago@bizcommerce.com.br> Co-authored-by: Contardi <contardi@users.noreply.github.com> Co-authored-by: Gabriel Antal <gabrielantalsilva@gmail.com> Co-authored-by: Caroline Esteves <carol@bizcommerce.com.br> Co-authored-by: Antal <gabriel.antal@bizcommerce.com.br> Co-authored-by: Antal <44688111+GabrielAntal@users.noreply.github.com> Co-authored-by: carolineesteves <131886821+carolineesteves@users.noreply.github.com> Co-authored-by: Iago Cedran <iago@bizcommerce.com.br>
1 parent 2af9d00 commit ccfc138

File tree

7 files changed

+329
-85
lines changed

7 files changed

+329
-85
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php
2+
3+
namespace Vindi\VP\Console\Command;
4+
5+
use Vindi\VP\Cron\ProcessCallbackQueue;
6+
use Magento\Framework\Console\Cli;
7+
use Symfony\Component\Console\Command\Command;
8+
use Symfony\Component\Console\Input\InputInterface;
9+
use Symfony\Component\Console\Output\OutputInterface;
10+
use Psr\Log\LoggerInterface;
11+
12+
/**
13+
* Command to execute the vindi_vp_process_callback_queue cron job manually.
14+
*/
15+
class ProcessCallbackQueueCommand extends Command
16+
{
17+
/**
18+
* @var ProcessCallbackQueue
19+
*/
20+
private $processCallbackQueue;
21+
22+
/**
23+
* @var LoggerInterface
24+
*/
25+
private $logger;
26+
27+
/**
28+
* Constructor.
29+
*
30+
* @param ProcessCallbackQueue $processCallbackQueue
31+
* @param LoggerInterface $logger
32+
*/
33+
public function __construct(
34+
ProcessCallbackQueue $processCallbackQueue,
35+
LoggerInterface $logger
36+
) {
37+
$this->processCallbackQueue = $processCallbackQueue;
38+
$this->logger = $logger;
39+
parent::__construct();
40+
}
41+
42+
/**
43+
* Configure the command options and description.
44+
*/
45+
protected function configure()
46+
{
47+
$this->setName('vindi:process-callback-queue')
48+
->setDescription('Executes the vindi_vp_process_callback_queue cron job manually.');
49+
parent::configure();
50+
}
51+
52+
/**
53+
* Execute the command.
54+
*
55+
* @param InputInterface $input
56+
* @param OutputInterface $output
57+
* @return int
58+
*/
59+
protected function execute(InputInterface $input, OutputInterface $output)
60+
{
61+
try {
62+
$this->processCallbackQueue->execute();
63+
$output->writeln('<info>Callback queue processing executed successfully.</info>');
64+
return Cli::RETURN_SUCCESS;
65+
} catch (\Exception $e) {
66+
$this->logger->error('Error executing callback queue processing: ' . $e->getMessage());
67+
$output->writeln('<error>Error executing callback queue processing: ' . $e->getMessage() . '</error>');
68+
return Cli::RETURN_FAILURE;
69+
}
70+
}
71+
}

Controller/Callback/Payments.php

Lines changed: 14 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,54 @@
11
<?php
2-
3-
/**
4-
*
5-
* @category Vindi
6-
* @package Vindi_VP
7-
*/
2+
declare(strict_types=1);
83

94
namespace Vindi\VP\Controller\Callback;
105

116
use Magento\Framework\App\RequestInterface;
127
use Magento\Framework\Controller\ResultFactory;
13-
use Vindi\VP\Controller\Callback;
14-
use Vindi\VP\Gateway\Http\Client\Api;
15-
use Vindi\VP\Helper\Order as HelperOrder;
16-
use Magento\Sales\Model\Order as SalesOrder;
178

18-
class Payments extends Callback
9+
class Payments extends \Vindi\VP\Controller\Callback
1910
{
2011
/**
2112
* @var string
2213
*/
2314
protected $eventName = 'pix';
2415

2516
/**
26-
* @inheritDoc
17+
* Validate CSRF request.
18+
*
19+
* @param RequestInterface $request
20+
* @return bool|null
2721
*/
2822
public function validateForCsrf(RequestInterface $request): ?bool
2923
{
3024
$hash = $request->getParam('hash');
3125
$storeHash = sha1($this->helperData->getToken());
32-
return ($hash == $storeHash);
26+
return ($hash === $storeHash);
3327
}
3428

3529
/**
30+
* Execute callback and register it in the callback table.
31+
*
3632
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
3733
*/
3834
public function execute()
3935
{
4036
$this->helperData->log(__('Webhook %1', __CLASS__), self::LOG_NAME);
41-
4237
$result = $this->resultFactory->create(ResultFactory::TYPE_RAW);
43-
$statusCode = 500;
38+
$statusCode = 200;
4439

4540
try {
4641
$content = $this->getContent($this->getRequest()) ?? '';
4742
$params = $this->getRequest()->getParams();
4843
$this->logParams($content, $params);
4944

5045
if (isset($params['transaction'])) {
51-
$method = 'vindi-payments';
52-
$transaction = $params['transaction'];
53-
$orderIncrementId = $transaction['order_number'] ?? $transaction['free'];
54-
if (isset($transaction['status_id'])) {
55-
$vindiStatus = $transaction['status_id'];
56-
$order = $this->helperOrder->loadOrder($transaction['order_number']);
57-
if ($order->getId()) {
58-
$method = $order->getPayment()->getMethod();
59-
$amount = $transaction['price_original'] ?? $order->getGrandTotal();
60-
$this->helperOrder->updateOrder($order, $vindiStatus, $transaction, $amount, true);
61-
$statusCode = 200;
62-
}
63-
}
64-
65-
/** @var \Vindi\VP\Model\Callback $callBack */
6646
$callBack = $this->callbackFactory->create();
67-
$callBack->setStatus($transaction['status_name'] ?? '');
68-
$callBack->setMethod($method);
69-
$callBack->setIncrementId($orderIncrementId);
47+
$callBack->setStatus($params['transaction']['status_name'] ?? '');
48+
$callBack->setMethod('vindi-payments');
49+
$callBack->setIncrementId($params['transaction']['order_number'] ?? ($params['transaction']['free'] ?? ''));
7050
$callBack->setPayload($this->json->serialize($params));
51+
$callBack->setQueueStatus('pending');
7152
$this->callbackResourceModel->save($callBack);
7253
}
7354
} catch (\Exception $e) {

Cron/ProcessCallbackQueue.php

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace Vindi\VP\Cron;
5+
6+
use Magento\Framework\Filesystem\Driver\File as FileDriver;
7+
use Magento\Framework\App\ResourceConnection;
8+
use Vindi\VP\Logger\Logger;
9+
use Vindi\VP\Helper\Order as HelperOrder;
10+
11+
class ProcessCallbackQueue
12+
{
13+
/**
14+
* @var ResourceConnection
15+
*/
16+
protected $resource;
17+
18+
/**
19+
* @var Logger
20+
*/
21+
protected $logger;
22+
23+
/**
24+
* @var HelperOrder
25+
*/
26+
protected $helperOrder;
27+
28+
/**
29+
* @var FileDriver
30+
*/
31+
protected $fileDriver;
32+
33+
/**
34+
* Constructor.
35+
*
36+
* @param ResourceConnection $resource
37+
* @param Logger $logger
38+
* @param HelperOrder $helperOrder
39+
* @param FileDriver $fileDriver
40+
*/
41+
public function __construct(
42+
ResourceConnection $resource,
43+
Logger $logger,
44+
HelperOrder $helperOrder,
45+
FileDriver $fileDriver
46+
) {
47+
$this->resource = $resource;
48+
$this->logger = $logger;
49+
$this->helperOrder = $helperOrder;
50+
$this->fileDriver = $fileDriver;
51+
}
52+
53+
/**
54+
* Execute Cron Job to process callback queue.
55+
*
56+
* @return void
57+
*/
58+
public function execute(): void
59+
{
60+
$this->logger->info(__('Starting callback processing without lock mechanism.'));
61+
62+
try {
63+
$connection = $this->resource->getConnection();
64+
$tableName = $this->resource->getTableName('vindi_vp_callback');
65+
66+
$select = $connection->select()
67+
->from($tableName)
68+
->where('queue_status = ?', 'pending')
69+
->where('attempts < ?', 3);
70+
71+
$callbacks = $connection->fetchAll($select);
72+
$this->logger->info(__('Found %1 pending callbacks to process.', count($callbacks)));
73+
74+
foreach ($callbacks as $callback) {
75+
$callbackId = $callback['entity_id'];
76+
$this->logger->info(__('Processing callback ID: %1', $callbackId));
77+
$attempts = (int)$callback['attempts'];
78+
79+
$connection->update(
80+
$tableName,
81+
['attempts' => $attempts + 1],
82+
['entity_id = ?' => $callbackId]
83+
);
84+
85+
try {
86+
$params = json_decode($callback['payload'], true);
87+
if (!is_array($params)) {
88+
throw new \Exception((string) __('Invalid JSON payload for callback ID %1', $callbackId));
89+
}
90+
91+
if (isset($params['transaction'])) {
92+
$transaction = $params['transaction'];
93+
$orderIncrementId = $transaction['order_number'] ?? ($transaction['free'] ?? '');
94+
$order = $this->helperOrder->loadOrder($orderIncrementId);
95+
96+
if ($order && $order->getId()) {
97+
$vindiStatus = $transaction['status_id'] ?? '';
98+
$amount = $transaction['price_original'] ?? $order->getGrandTotal();
99+
$this->helperOrder->updateOrder($order, $vindiStatus, $transaction, (float)$amount, true);
100+
$this->logger->info(__('Callback ID %1 processed successfully. Order %2 updated.', $callbackId, $orderIncrementId));
101+
} else {
102+
$this->logger->warning(__('Order not found for callback ID %1 with order number %2.', $callbackId, $orderIncrementId));
103+
}
104+
} else {
105+
$this->logger->warning(__('Transaction data missing in callback ID %1.', $callbackId));
106+
}
107+
108+
$connection->update(
109+
$tableName,
110+
['queue_status' => 'executed'],
111+
['entity_id = ?' => $callbackId]
112+
);
113+
} catch (\Exception $e) {
114+
$this->logger->error(__('Error processing callback ID %1: %2', $callbackId, $e->getMessage()));
115+
116+
if (($attempts + 1) >= 3) {
117+
$connection->update(
118+
$tableName,
119+
['queue_status' => 'failed'],
120+
['entity_id = ?' => $callbackId]
121+
);
122+
$this->logger->error(__('Callback ID %1 marked as failed after %2 attempts.', $callbackId, $attempts + 1));
123+
}
124+
}
125+
}
126+
$this->logger->info(__('Finished processing callbacks.'));
127+
} catch (\Exception $e) {
128+
$this->logger->error(__('Error executing cron job: %1', $e->getMessage()));
129+
}
130+
}
131+
}

0 commit comments

Comments
 (0)