Skip to content

Commit

Permalink
PT-13152 - Add turnover report
Browse files Browse the repository at this point in the history
  • Loading branch information
DennisGarding committed Apr 24, 2024
1 parent dda33d2 commit 0eff40b
Show file tree
Hide file tree
Showing 21 changed files with 1,999 additions and 1,991 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/e2e-tests-legacy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ jobs:
PAYPAL_SEPA_PHONE: ${{ secrets.PAYPAL_SEPA_PHONE }}
PAYPAL_SEPA_BIRTHDAY: ${{ secrets.PAYPAL_SEPA_BIRTHDAY }}

HOME=/root

steps:
- run: /usr/bin/supervisord -c /etc/supervisord.conf &

Expand Down Expand Up @@ -75,6 +77,8 @@ jobs:
npx playwright install-deps
- name: Execute legacy E2E tests
env:
HOME: /root
run: |
cd /shopware/custom/plugins/SwagPaymentPayPalUnified/Tests/E2E
npx playwright test --workers=1 --grep-invert @notIn5.2
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/e2e-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,11 @@ jobs:
make install-plugin
cd /shopware/custom/plugins/SwagPaymentPayPalUnified/Tests/E2E
npm install
npx playwright install --with-deps chromium
npx playwright install --with-deps firefox
- name: Execute E2E tests
env:
HOME: /root
run: |
cd /shopware/custom/plugins/SwagPaymentPayPalUnified/Tests/E2E
npm run e2e:run
Expand Down
95 changes: 95 additions & 0 deletions Components/TransactionReport/ReportResult.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php
/**
* (c) shopware AG <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace SwagPaymentPayPalUnified\Components\TransactionReport;

class ReportResult
{
const PRECISION = 2;

/**
* @var array<string, array<int, array{'id': int, 'invoice_amount': float}>>
*/
private $ordersToReport;

/**
* @var array<string, array<int, int>>
*/
private $orderIds = [];

/**
* @var array<string, float>
*/
private $turnover = [];

/**
* @var array<int, string>
*/
private $currencies = [];

/**
* @param array<string, array<int, array{'id': int, 'invoice_amount': float}>> $ordersToReport
*/
public function __construct(array $ordersToReport)
{
$this->ordersToReport = $ordersToReport;
$this->init();
}

/**
* @return array<int, string>
*/
public function getCurrencies()
{
return $this->currencies;
}

/**
* @param string $currency
*
* @return float
*/
public function getTurnover($currency)
{
if (!\array_key_exists($currency, $this->turnover)) {
return 0.0;
}

return round($this->turnover[$currency], self::PRECISION, \PHP_ROUND_HALF_UP);
}

/**
* @param string $currency
*
* @return array<int, int>
*/
public function getOrderIds($currency)
{
if (!\array_key_exists($currency, $this->orderIds)) {
return [];
}

return $this->orderIds[$currency];
}

/**
* @return void
*/
private function init()
{
foreach ($this->ordersToReport as $currency => $orders) {
$this->currencies[] = $currency;
$this->orderIds[$currency] = [];
$this->turnover[$currency] = 0.0;
foreach ($orders as $order) {
$this->turnover[$currency] += (float) $order['invoice_amount'];
$this->orderIds[$currency][] = $order['id'];
}
}
}
}
135 changes: 135 additions & 0 deletions Components/TransactionReport/TransactionReport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<?php
/**
* (c) shopware AG <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace SwagPaymentPayPalUnified\Components\TransactionReport;

use DateTime;
use Doctrine\DBAL\Connection;
use GuzzleHttp\Client;
use PDO;
use Shopware\Models\Order\Status;

final class TransactionReport
{
const TRANSACTION_REPORT_TABLE = 'swag_payment_paypal_unified_transaction_report';
const API_IDENTIFIER = '9b6f559b-5ca1-4969-b23d-e0aa2c01d562';
const POST_URL = 'https://api.shopware.com';
const POST_URL_ENDPOINT = '/shopwarepartners/reports/technology';

/**
* @var Connection
*/
private $connection;

public function __construct(Connection $connection)
{
$this->connection = $connection;
}

/**
* @param int $orderId
*
* @return void
*/
public function reportOrder($orderId)
{
$this->connection->createQueryBuilder()
->insert(self::TRANSACTION_REPORT_TABLE)
->setValue('order_id', ':orderId')
->setParameter('orderId', $orderId)
->execute();
}

/**
* @param string $shopwareVersion
*
* @return void
*/
public function report($shopwareVersion, Client $client)
{
$reportResult = $this->getReportResult($this->getReportedOrderIds());
$currencies = $reportResult->getCurrencies();

foreach ($currencies as $currency) {
$requestBody = [
'identifier' => self::API_IDENTIFIER,
'reportDate' => (new DateTime())->format('Y-m-d\\TH:i:sP'),
'shopwareVersion' => $shopwareVersion,
'currency' => $currency,
'reportDataKeys' => ['turnover' => $reportResult->getTurnover($currency)],
];

$client->post(self::POST_URL_ENDPOINT, ['json' => $requestBody]);

$this->deleteReportedOrders($reportResult->getOrderIds($currency));
}
}

/**
* @return array<int, int>
*/
private function getReportedOrderIds()
{
return $this->connection->createQueryBuilder()
->select(['order_id'])
->from(self::TRANSACTION_REPORT_TABLE)
->execute()
->fetchAll(PDO::FETCH_COLUMN);
}

/**
* @param array<int, int> $reportedOrderIds
*
* @return void
*/
private function deleteReportedOrders(array $reportedOrderIds)
{
$this->connection->createQueryBuilder()
->delete(self::TRANSACTION_REPORT_TABLE)
->where('order_id IN (:reportedOrderIds)')
->setParameter('reportedOrderIds', $reportedOrderIds, Connection::PARAM_INT_ARRAY)
->execute();
}

/**
* @param array<int, int> $reportedIds
*
* @return ReportResult
*/
private function getReportResult(array $reportedIds)
{
$queryBuilder = $this->connection->createQueryBuilder();

$result = $queryBuilder->select(['currency', 'id', 'invoice_amount'])
->from('s_order')
->where('id IN (:ordersToReport)')
->andWhere('cleared = :paymentStatus')
->andWhere('paymentID IN (:paymentIds)')
->setParameter('paymentStatus', Status::PAYMENT_STATE_COMPLETELY_PAID)
->setParameter('ordersToReport', $reportedIds, Connection::PARAM_INT_ARRAY)
->setParameter('paymentIds', $this->getPaymentIds(), Connection::PARAM_INT_ARRAY)
->execute()
->fetchAll(PDO::FETCH_GROUP);

return new ReportResult($result);
}

/**
* @return array<int, int>
*/
private function getPaymentIds()
{
return $this->connection->createQueryBuilder()
->select(['id'])
->from('s_core_paymentmeans')
->where('name LIKE :paymentName')
->setParameter('paymentName', 'SwagPaymentPayPalUnified%')
->execute()
->fetchAll(PDO::FETCH_COLUMN);
}
}
13 changes: 13 additions & 0 deletions Controllers/Frontend/AbstractPaypalPaymentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use SwagPaymentPayPalUnified\Components\Services\RequestIdService;
use SwagPaymentPayPalUnified\Components\Services\Validation\RedirectDataBuilderFactory;
use SwagPaymentPayPalUnified\Components\Services\Validation\SimpleBasketValidator;
use SwagPaymentPayPalUnified\Components\TransactionReport\TransactionReport;
use SwagPaymentPayPalUnified\Controllers\Frontend\AbstractPaypalPaymentControllerResults\DeterminedStatus;
use SwagPaymentPayPalUnified\Controllers\Frontend\Exceptions\AuthorizationDeniedException;
use SwagPaymentPayPalUnified\Controllers\Frontend\Exceptions\AuthorizationPendingException;
Expand Down Expand Up @@ -705,6 +706,16 @@ protected function createShopwareOrder($payPalOrderId, $paymentType, $paymentSta

$this->orderNumberService->releaseOrderNumber();

if ($paymentStatusId === Status::PAYMENT_STATE_COMPLETELY_PAID) {
try {
$orderId = $this->getOrderId($orderNumber);
} catch (OrderNotFoundException $exception) {
return $orderNumber;
}

(new TransactionReport($this->get('dbal_connection')))->reportOrder($orderId);
}

return $orderNumber;
}

Expand Down Expand Up @@ -808,6 +819,8 @@ protected function updatePaymentStatus($intent, $shopwareOrderId)
} else {
$this->paymentStatusService->updatePaymentStatusV2($shopwareOrderId, Status::PAYMENT_STATE_RESERVED);
}

(new TransactionReport($this->get('dbal_connection')))->reportOrder($shopwareOrderId);
}

/**
Expand Down
12 changes: 12 additions & 0 deletions Resources/cronjob.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<cronjobs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware5/shopware/5.3/engine/Shopware/Components/Plugin/schema/cronjob.xsd">

<cronjob>
<name>Execute PayPal transaktion report</name>
<action>SwagPaymentPayPalUnifiedTransaktionReport</action>
<active>true</active>
<interval>86400</interval>
<disableOnError>false</disableOnError>
</cronjob>
</cronjobs>
8 changes: 8 additions & 0 deletions Resources/services/subscribers.xml
Original file line number Diff line number Diff line change
Expand Up @@ -328,5 +328,13 @@
public="true">
<tag name="shopware.event_subscriber"/>
</service>

<service id="paypal_unified.subscriber.transaction_report"
class="SwagPaymentPayPalUnified\Subscriber\TransactionReportSubscriber"
public="true">
<argument type="service" id="dbal_connection"/>
<argument type="service" id="service_container"/>
<tag name="shopware.event_subscriber"/>
</service>
</services>
</container>
8 changes: 8 additions & 0 deletions Setup/Assets/tables.sql
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,11 @@ CREATE TABLE IF NOT EXISTS `swag_payment_paypal_unified_order_refund_info`
) ENGINE = InnoDB
DEFAULT CHARSET = utf8
COLLATE = utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `swag_payment_paypal_unified_transaction_report`
(
`id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`order_id` INT(11) NOT NULL
) ENGINE = InnoDB
DEFAULT CHARSET = utf8
COLLATE = utf8_unicode_ci;
7 changes: 7 additions & 0 deletions Setup/Updater.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use SwagPaymentPayPalUnified\Setup\Versions\UpdateTo604;
use SwagPaymentPayPalUnified\Setup\Versions\UpdateTo610;
use SwagPaymentPayPalUnified\Setup\Versions\UpdateTo616;
use SwagPaymentPayPalUnified\Setup\Versions\UpdateTo617;

class Updater
{
Expand Down Expand Up @@ -249,6 +250,12 @@ public function update($oldVersion)
$this->connection
))->update();
}

if (\version_compare($oldVersion, '6.1.7', '<')) {
(new UpdateTo617(
$this->connection
))->update();
}
}

/**
Expand Down
Loading

0 comments on commit 0eff40b

Please sign in to comment.