Skip to content

Commit

Permalink
Merge pull request #9 from WebStollenPaymentTeam/main
Browse files Browse the repository at this point in the history
v1.9.1
  • Loading branch information
hwysoszynski authored Oct 3, 2024
2 parents a8adda9 + eeb1a4d commit 650236e
Show file tree
Hide file tree
Showing 11 changed files with 341 additions and 37 deletions.
82 changes: 82 additions & 0 deletions Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,22 @@
use JTL\Events\Dispatcher;
use JTL\Exceptions\CircularReferenceException;
use JTL\Exceptions\ServiceNotFoundException;
use JTL\Router\Router;
use Plugin\ws5_mollie\lib\CleanupCronJob;
use Plugin\ws5_mollie\lib\Hook\ApplePay;
use Plugin\ws5_mollie\lib\Hook\Checkbox;
use Plugin\ws5_mollie\lib\Hook\IncompletePaymentHandler;
use Plugin\ws5_mollie\lib\Hook\Queue;
use Plugin\ws5_mollie\lib\Hook\FrontendHook;
use Plugin\ws5_mollie\lib\PluginHelper;
use JTL\Events\Event;

require_once __DIR__ . '/vendor/autoload.php';

class Bootstrap extends \WS\JTL5\V1_0_16\Bootstrap
{
private const CRON_TYPE = 'cronjob_mollie_cleanup';

/**
* @param Dispatcher $dispatcher
* @throws CircularReferenceException
Expand All @@ -29,7 +35,16 @@ public function boot(Dispatcher $dispatcher): void
{
parent::boot($dispatcher);

$dispatcher->listen(Event::GET_AVAILABLE_CRONJOBS, [$this, 'availableCronjobType']);
$dispatcher->listen(Event::MAP_CRONJOB_TYPE, static function (array &$args) {
if ($args['type'] === self::CRON_TYPE) {
$args['mapping'] = CleanupCronJob::class;
}
});


$this->listen(HOOK_SMARTY_OUTPUTFILTER, [ApplePay::class, 'execute']);
$this->listen(HOOK_SMARTY_OUTPUTFILTER, [FrontendHook::class, 'execute']);

$this->listen(HOOK_BESTELLVORGANG_PAGE, [IncompletePaymentHandler::class, 'checkForIncompletePayment']);

Expand All @@ -44,6 +59,69 @@ public function boot(Dispatcher $dispatcher): void
if (PluginHelper::getSetting('useCustomerAPI') === 'C') {
$this->listen(HOOK_CHECKBOX_CLASS_GETCHECKBOXFRONTEND, [Checkbox::class, 'execute']);
}

//routes
if (PluginHelper::getSetting('queue') === 'async') {
$this->listen(HOOK_ROUTER_PRE_DISPATCH, function ($args) {
/** @var Router $router */
$router = $args['router'];
$router->addRoute('/' . self::getPlugin()->getPluginID() . '/queue', [\Plugin\ws5_mollie\lib\Queue::class, 'runAsynchronous'], null, ['POST']);
});
}
}

/**
* @return void
*/
private function addCleanupCron(): void
{
$isInstalled = $this->getDB()->executeQueryPrepared('SELECT * FROM tcron WHERE name = :name AND jobType = :jobType',
[
':name' => 'Mollie Queue Cleanup',
':jobType' => self::CRON_TYPE
],
3) > 0;

if (!$isInstalled) {
$job = new \stdClass();
$job->name = 'Mollie Queue Cleanup';
$job->jobType = self::CRON_TYPE;
$job->frequency = 1;
$job->startDate = 'NOW()';
$job->startTime = '06:00:00';
$this->getDB()->insert('tcron', $job);
}
}

/**
* @param array $args
* @return void
*/
public function availableCronjobType(array &$args): void
{
if (!\in_array(self::CRON_TYPE, $args['jobs'], true)) {
$args['jobs'][] = self::CRON_TYPE;
}
}


/**
* @return void
*/
public function installed(): void
{
parent::installed();
$this->addCleanupCron();
}

/**
* @param bool $deleteData
* @return void
*/
public function uninstalled(bool $deleteData = true): void
{
parent::uninstalled($deleteData);
$this->getDB()->delete('tcron', ['name', 'jobType'], ['Mollie Queue Cleanup', self::CRON_TYPE]);
}

/**
Expand All @@ -55,6 +133,10 @@ public function updated($oldVersion, $newVersion): void
{
parent::updated($oldVersion, $newVersion);

if ($newVersion >= "1.9.0") {
$this->addCleanupCron();
}

if (PluginHelper::isShopVersionEqualOrGreaterThan('5.3.0')) {
\JTL\Update\DBMigrationHelper::migrateToInnoDButf8('xplugin_ws5_mollie_kunde'); // TODO: remove this code when min. shop version is 5.3
\JTL\Update\DBMigrationHelper::migrateToInnoDButf8('xplugin_ws5_mollie_orders'); // TODO: remove this code when min. shop version is 5.3
Expand Down
23 changes: 23 additions & 0 deletions Migrations/Migration20240919161400.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Plugin\ws5_mollie\Migrations;

use JTL\Plugin\Migration;
use JTL\Update\IMigration;

class Migration20240919161400 extends Migration implements IMigration
{

/**
* @inheritDoc
*/
public function up()
{
$this->execute('CREATE INDEX idx_composite_with_order ON xplugin_ws5_mollie_queue (`dDone`, `bLock`, `cType`, `dCreated` DESC);');
}

public function down()
{
// No need to change since 'xplugin_ws5_mollie_orders' is removed in Migration where it is created, and we don't support downgrading of Plugins
}
}
32 changes: 6 additions & 26 deletions frontend/hooks/131.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@

require_once __DIR__ . '/../../vendor/autoload.php';

ifndef('MOLLIE_QUEUE_MAX', 3);
/** @noinspection PhpUndefinedConstantInspection */
Queue::run(MOLLIE_QUEUE_MAX);
if (PluginHelper::getSetting('queue') === 'sync') {
ifndef('MOLLIE_QUEUE_MAX', 3);
/** @noinspection PhpUndefinedConstantInspection */
Queue::runSynchronous(MOLLIE_QUEUE_MAX);
}

//TODO: remove this check in next version
// forces v5.1 Shop to abschlussseite
Expand Down Expand Up @@ -83,32 +85,10 @@
}
}




ifndef('MOLLIE_REMINDER_PROP', 10);
if (random_int(1, MOLLIE_REMINDER_PROP) % MOLLIE_REMINDER_PROP === 0) {
/** @noinspection PhpUndefinedConstantInspection */
$lock = new ExclusiveLock('mollie_reminder', PFAD_ROOT . PFAD_COMPILEDIR);
if ($lock->lock()) {
AbstractCheckout::sendReminders();
Queue::storno(PluginHelper::getSetting('autoStorno'));
}
}

// TODO: DOKU
ifndef('MOLLIE_DISABLE_USER_CLEANUP', false);

if (!MOLLIE_DISABLE_USER_CLEANUP) {
ifndef('MOLLIE_CLEANUP_PROP', 15);
/** @noinspection PhpUndefinedConstantInspection */
if (MOLLIE_CLEANUP_PROP && random_int(1, MOLLIE_CLEANUP_PROP) % MOLLIE_CLEANUP_PROP === 0) {
QueueModel::cleanUp();
}
}
if (array_key_exists('mollie_cleanup_cron', $_REQUEST)) {
exit((string) QueueModel::cleanUp());
}

} catch (Exception $e) {
Shop::Container()->getLogService()->error($e->getMessage() . " (Trace: {$e->getTraceAsString()})");
}
22 changes: 22 additions & 0 deletions frontend/template/queue.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<script type="text/javascript">
{if isset($wsQueueURL)}{literal}
$(function() {
fetch({/literal}'{$wsQueueURL}{literal}', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
credentials: 'omit',
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // If the response is JSON
})
.catch(error => {
console.error('Error:', error);
});
});
{/literal}{/if}
</script>
3 changes: 2 additions & 1 deletion info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
<ShopVersion>5.2.0</ShopVersion>
<PluginID>ws5_mollie</PluginID>
<CreateDate>2023-02-13</CreateDate>
<Version>1.9.0</Version>
<Version>1.9.1</Version>
<ExsID>689388c6-9f04-4648-b516-e67d96b0dc1d</ExsID>
<Install>
<Hooks>
<Hook id="131">hooks/131.php</Hook>
Expand Down
32 changes: 32 additions & 0 deletions lib/CleanupCronJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Plugin\ws5_mollie\lib;

use JTL\Cron\Job;
use JTL\Cron\JobInterface;
use JTL\Cron\QueueEntry;
use Plugin\ws5_mollie\lib\Model\QueueModel;

class CleanupCronJob extends Job
{
public function start(QueueEntry $queueEntry): JobInterface
{
parent::start($queueEntry);

try {
$this->logger->debug('Mollie Queue Cleanup');
ifndef('MOLLIE_DISABLE_USER_CLEANUP', false);
if (!MOLLIE_DISABLE_USER_CLEANUP) {
QueueModel::cleanUp();
}

PluginHelper::cleanupPaymentLogs();

} catch (\Exception $e) {
$this->logger->debug('Mollie Queue Exception: ' . $e->getMessage());
}

$this->setFinished(true);
return $this;
}
}
30 changes: 21 additions & 9 deletions lib/Hook/ApplePay.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,8 @@ public static function execute($args_arr = []): void
return;
}

// Reset CreditCard-Token after Order!
if (
($key = sprintf('kPlugin_%d_creditcard', PluginHelper::getPlugin()->getID()))
&& array_key_exists($key, $_SESSION) && !array_key_exists('Zahlungsart', $_SESSION)
) {
unset($_SESSION[$key]);
}

if (!array_key_exists('ws_mollie_applepay_available', $_SESSION)) {
// append applepay script
if (!array_key_exists('ws_mollie_applepay_available', $_SESSION) && self::isActive()) {
pq('head')->append("<script>window.MOLLIE_APPLEPAY_CHECK_URL = '" . PluginHelper::getPlugin()->getPaths()->getBaseURL() . "applepay.php';</script>");
}
} catch (Exception $e) {
Expand All @@ -58,4 +51,23 @@ public static function setAvailable(bool $status): void
{
$_SESSION['ws_mollie_applepay_available'] = $status;
}

/**
* @return bool
*/
public static function isActive(): bool
{
$kZahlunsgart = PluginHelper::getDB()->executeQueryPrepared('SELECT kZahlungsart FROM tzahlungsart WHERE cModulId = :cModulId',
[
':cModulId' => 'kPlugin_' . PluginHelper::getPlugin()->getID() . '_applepay'
], 1)->kZahlungsart ?? null;
if ($kZahlunsgart > 0) {
return PluginHelper::getDB()->executeQueryPrepared('SELECT * FROM tversandartzahlungsart WHERE kZahlungsart = :kZahlungsart',
[
':kZahlungsart' => $kZahlunsgart
], 3) > 0;
} else {
return false;
}
}
}
45 changes: 45 additions & 0 deletions lib/Hook/FrontendHook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

/**
* @copyright 2021 WebStollen GmbH
* @link https://www.webstollen.de
*/

namespace Plugin\ws5_mollie\lib\Hook;

use Exception;
use JTL\Shop;
use Plugin\ws5_mollie\lib\Model\QueueModel;
use Plugin\ws5_mollie\lib\PluginHelper;
use WS\JTL5\V1_0_16\Hook\AbstractHook;

class FrontendHook extends AbstractHook
{
/**
* @param array $args_arr
* @throws Exception
*/
public static function execute($args_arr = []): void
{
try {
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
return;
}

// Reset CreditCard-Token after Order!
if (
($key = sprintf('kPlugin_%d_creditcard', PluginHelper::getPlugin()->getID()))
&& array_key_exists($key, $_SESSION) && !array_key_exists('Zahlungsart', $_SESSION)
) {
unset($_SESSION[$key]);
}

// append queue script
if (PluginHelper::getSetting('queue') === 'async') {
Shop::Smarty()->assign('wsQueueURL', Shop::getURL() . '/ws5_mollie/queue');
pq('body')->append(Shop::Smarty()->fetch(PluginHelper::getPlugin()->getPaths()->getFrontendPath() . 'template/queue.tpl', false));
}
} catch (Exception $e) {
}
}
}
9 changes: 9 additions & 0 deletions lib/PluginHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,13 @@
class PluginHelper extends AbstractPluginHelper
{
protected static $pluginId = 'ws5_mollie';

public static function cleanupPaymentLogs(): void
{
self::getDB()->executeQueryPrepared('DELETE FROM tzahlungslog WHERE cModulId LIKE :cModulId AND dDatum < DATE_SUB(NOW(), INTERVAL 3 MONTH) LIMIT 100000;',
[
'cModulId' => 'kPlugin_' . self::getPlugin()->getID() . '_%'
],
10);
}
}
Loading

0 comments on commit 650236e

Please sign in to comment.