This commit is contained in:
2026-03-30 20:23:38 +02:00
parent 70662afd2c
commit 5435209b08
26 changed files with 1949 additions and 160 deletions

View File

@@ -157,8 +157,7 @@ final class CronHandlerFactory
new ApaczkaIntegrationRepository($this->db, $this->integrationSecret)
),
new AllegroTrackingService(
$apiClient,
$tokenManager
new InpostIntegrationRepository($this->db, $this->integrationSecret)
),
]),
new ShipmentPackageRepository($this->db),

View File

@@ -16,6 +16,8 @@ use App\Modules\Email\EmailSendingService;
use App\Modules\Settings\EmailMailboxRepository;
use App\Modules\Settings\EmailTemplateRepository;
use App\Modules\Settings\ReceiptConfigRepository;
use App\Modules\Settings\ShopproApiClient;
use App\Modules\Settings\ShopproIntegrationsRepository;
use App\Modules\Shipments\ShipmentPackageRepository;
final class OrdersController
@@ -32,7 +34,8 @@ final class OrdersController
private readonly ?EmailTemplateRepository $emailTemplateRepo = null,
private readonly ?EmailMailboxRepository $emailMailboxRepo = null,
private readonly string $storagePath = '',
private readonly ?\App\Modules\Printing\PrintJobRepository $printJobRepo = null
private readonly ?\App\Modules\Printing\PrintJobRepository $printJobRepo = null,
private readonly ?ShopproIntegrationsRepository $shopproIntegrations = null
) {
}
@@ -781,4 +784,102 @@ final class OrdersController
return Response::json($preview);
}
public function addPayment(Request $request): Response
{
$orderId = max(0, (int) $request->input('id', 0));
if ($orderId <= 0) {
return Response::json(['ok' => false, 'error' => 'Nieprawidłowe ID zamówienia.'], 400);
}
if (!Csrf::verify((string) $request->input('_token', ''))) {
return Response::json(['ok' => false, 'error' => 'Nieprawidłowy token CSRF.'], 403);
}
$amount = (float) $request->input('amount', 0);
$paymentTypeId = trim((string) $request->input('payment_type_id', ''));
$paymentDate = trim((string) $request->input('payment_date', ''));
$comment = trim((string) $request->input('comment', ''));
if ($amount <= 0) {
return Response::json(['ok' => false, 'error' => 'Kwota musi być większa od 0.'], 422);
}
if ($paymentTypeId === '') {
return Response::json(['ok' => false, 'error' => 'Wybierz typ płatności.'], 422);
}
$result = $this->orders->addPayment($orderId, [
'amount' => $amount,
'payment_type_id' => $paymentTypeId,
'payment_date' => $paymentDate !== '' ? $paymentDate . ' ' . date('H:i:s') : '',
'comment' => $comment,
]);
if ($result === null) {
return Response::json(['ok' => false, 'error' => 'Nie udało się zapisać płatności.'], 500);
}
$this->orders->recordActivity(
$orderId,
'payment',
'Dodano płatność: ' . number_format($amount, 2, '.', ' ') . ' PLN (' . $paymentTypeId . ')',
['payment_id' => $result['id'], 'amount' => $amount, 'type' => $paymentTypeId],
'user',
$this->auth->user()['name'] ?? null
);
$this->pushPaymentToShoppro($orderId, $result['payment_status']);
return Response::json([
'ok' => true,
'payment_id' => $result['id'],
'payment_status' => $result['payment_status'],
'total_paid' => $result['total_paid'],
]);
}
private function pushPaymentToShoppro(int $orderId, int $paymentStatus): void
{
if ($paymentStatus !== 2 || $this->shopproIntegrations === null) {
return;
}
try {
$orderStmt = $this->orders->findOrderSourceInfo($orderId);
if ($orderStmt === null || ($orderStmt['source'] ?? '') !== 'shoppro') {
return;
}
$integrationId = (int) ($orderStmt['integration_id'] ?? 0);
$sourceOrderId = trim((string) ($orderStmt['source_order_id'] ?? ''));
if ($integrationId <= 0 || $sourceOrderId === '') {
return;
}
$integration = $this->shopproIntegrations->findIntegration($integrationId);
if ($integration === null || empty($integration['is_active']) || empty($integration['has_api_key'])) {
return;
}
$baseUrl = trim((string) ($integration['base_url'] ?? ''));
$apiKey = $this->shopproIntegrations->getApiKeyDecrypted($integrationId);
if ($baseUrl === '' || $apiKey === null || trim($apiKey) === '') {
return;
}
$client = new ShopproApiClient();
$pushResult = $client->setOrderPaid($baseUrl, $apiKey, 10, $sourceOrderId);
$this->orders->recordActivity(
$orderId,
'sync',
$pushResult['ok']
? 'Wysłano status płatności do shopPRO (opłacone)'
: 'Błąd push płatności do shopPRO: ' . ($pushResult['message'] ?? 'unknown'),
['direction' => 'push', 'target' => 'shoppro', 'ok' => $pushResult['ok']],
'system'
);
} catch (\Throwable) {
}
}
}

View File

@@ -847,6 +847,94 @@ final class OrdersRepository
], $actorType, $actorName);
}
/**
* @param array<string, mixed> $data Keys: payment_type_id, amount, payment_date, comment, currency
* @return array{id:int, payment_status:int, total_paid:float}|null
*/
/**
* @return array{source:string, integration_id:int, source_order_id:string}|null
*/
public function findOrderSourceInfo(int $orderId): ?array
{
if ($orderId <= 0) {
return null;
}
$stmt = $this->pdo->prepare('SELECT source, integration_id, source_order_id FROM orders WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $orderId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return is_array($row) ? $row : null;
}
/**
* @param array<string, mixed> $data Keys: payment_type_id, amount, payment_date, comment, currency
* @return array{id:int, payment_status:int, total_paid:float}|null
*/
public function addPayment(int $orderId, array $data): ?array
{
if ($orderId <= 0) {
return null;
}
$stmt = $this->pdo->prepare('SELECT id, total_with_tax, currency FROM orders WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $orderId]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);
if (!is_array($order)) {
return null;
}
$amount = round((float) ($data['amount'] ?? 0), 2);
$paymentTypeId = trim((string) ($data['payment_type_id'] ?? ''));
$paymentDate = trim((string) ($data['payment_date'] ?? ''));
$comment = trim((string) ($data['comment'] ?? ''));
$currency = trim((string) ($data['currency'] ?? $order['currency'] ?? 'PLN'));
if ($amount <= 0 || $paymentTypeId === '') {
return null;
}
$sourcePaymentId = 'manual_' . $orderId . '_' . time();
$insert = $this->pdo->prepare(
'INSERT INTO order_payments (order_id, source_payment_id, payment_type_id, payment_date, amount, currency, comment, created_at, updated_at)
VALUES (:order_id, :source_payment_id, :payment_type_id, :payment_date, :amount, :currency, :comment, NOW(), NOW())'
);
$insert->execute([
'order_id' => $orderId,
'source_payment_id' => $sourcePaymentId,
'payment_type_id' => $paymentTypeId,
'payment_date' => $paymentDate !== '' ? $paymentDate : date('Y-m-d H:i:s'),
'amount' => $amount,
'currency' => $currency,
'comment' => $comment !== '' ? $comment : null,
]);
$paymentId = (int) $this->pdo->lastInsertId();
$sumStmt = $this->pdo->prepare('SELECT COALESCE(SUM(amount), 0) FROM order_payments WHERE order_id = :order_id');
$sumStmt->execute(['order_id' => $orderId]);
$totalPaid = round((float) $sumStmt->fetchColumn(), 2);
$totalWithTax = $order['total_with_tax'] !== null ? (float) $order['total_with_tax'] : null;
$paymentStatus = 0;
if ($totalPaid > 0 && $totalWithTax !== null && $totalPaid >= $totalWithTax) {
$paymentStatus = 2;
} elseif ($totalPaid > 0) {
$paymentStatus = 1;
}
$update = $this->pdo->prepare('UPDATE orders SET payment_status = :payment_status, total_paid = :total_paid, updated_at = NOW() WHERE id = :id');
$update->execute([
'payment_status' => $paymentStatus,
'total_paid' => $totalPaid,
'id' => $orderId,
]);
return [
'id' => $paymentId,
'payment_status' => $paymentStatus,
'total_paid' => $totalPaid,
];
}
public function updateOrderStatus(int $orderId, string $newStatusCode, string $actorType = 'user', ?string $actorName = null): bool
{
try {

View File

@@ -36,6 +36,7 @@ final class AllegroIntegrationController
];
private const OAUTH_SCOPES = [
AllegroOAuthClient::ORDERS_READ_SCOPE,
AllegroOAuthClient::ORDERS_WRITE_SCOPE,
AllegroOAuthClient::SALE_OFFERS_READ_SCOPE,
AllegroOAuthClient::SHIPMENTS_READ_SCOPE,
AllegroOAuthClient::SHIPMENTS_WRITE_SCOPE,

View File

@@ -8,6 +8,7 @@ use App\Core\Exceptions\AllegroOAuthException;
final class AllegroOAuthClient
{
public const ORDERS_READ_SCOPE = 'allegro:api:orders:read';
public const ORDERS_WRITE_SCOPE = 'allegro:api:orders:write';
public const SALE_OFFERS_READ_SCOPE = 'allegro:api:sale:offers:read';
public const SHIPMENTS_READ_SCOPE = 'allegro:api:shipments:read';
public const SHIPMENTS_WRITE_SCOPE = 'allegro:api:shipments:write';

View File

@@ -249,6 +249,34 @@ final class ShopproApiClient
];
}
/**
* @return array{ok:bool,http_code:int|null,message:string}
*/
public function setOrderPaid(
string $baseUrl,
string $apiKey,
int $timeoutSeconds,
string $sourceOrderId
): array {
if ($sourceOrderId === '') {
return ['ok' => false, 'http_code' => null, 'message' => 'Brak source_order_id.'];
}
$url = rtrim(trim($baseUrl), '/') . '/api.php?' . http_build_query([
'endpoint' => 'orders',
'action' => 'set_paid',
'id' => $sourceOrderId,
]);
$response = $this->requestJsonPut($url, $apiKey, $timeoutSeconds, json_encode(['send_email' => 0], JSON_THROW_ON_ERROR));
return [
'ok' => ($response['ok'] ?? false) === true,
'http_code' => $response['http_code'] ?? null,
'message' => (string) ($response['message'] ?? ''),
];
}
/**
* @return array{ok:bool,http_code:int|null,message:string,data:array<string,mixed>|array<int,mixed>|null}
*/

View File

@@ -86,7 +86,7 @@ final class AllegroShipmentService implements ShipmentProviderInterface
'deliveryMethodId' => $deliveryMethodId,
'sender' => $senderAddress,
'receiver' => $receiverAddress,
'referenceNumber' => $sourceOrderId !== '' ? $sourceOrderId : (string) $orderId,
'referenceNumber' => substr($sourceOrderId !== '' ? $sourceOrderId : (string) $orderId, 0, 35),
'packages' => [[
'type' => $packageType,
'length' => ['value' => $lengthCm, 'unit' => 'CENTIMETER'],
@@ -140,7 +140,7 @@ final class AllegroShipmentService implements ShipmentProviderInterface
'label_format' => $labelFormat,
'receiver_point_id' => trim((string) ($formData['receiver_point_id'] ?? '')),
'sender_point_id' => trim((string) ($formData['sender_point_id'] ?? '')),
'reference_number' => $sourceOrderId !== '' ? $sourceOrderId : (string) $orderId,
'reference_number' => substr($sourceOrderId !== '' ? $sourceOrderId : (string) $orderId, 0, 35),
'payload_json' => $apiPayload,
]);
@@ -196,10 +196,11 @@ final class AllegroShipmentService implements ShipmentProviderInterface
if ($status === 'SUCCESS' && $shipmentId !== '') {
$details = $this->apiClient->getShipmentDetails($env, $accessToken, $shipmentId);
$trackingNumber = trim((string) ($details['waybill'] ?? ''));
$detailPackages = is_array($details['packages'] ?? null) ? $details['packages'] : [];
$trackingNumber = trim((string) ($detailPackages[0]['waybill'] ?? ''));
$carrierId = trim((string) ($package['carrier_id'] ?? ''));
if ($carrierId === '') {
$carrierId = trim((string) ($details['carrierId'] ?? ''));
$carrierId = trim((string) ($details['carrier'] ?? ''));
}
$this->packages->update($packageId, [
@@ -264,7 +265,7 @@ final class AllegroShipmentService implements ShipmentProviderInterface
[$accessToken, $env] = $this->tokenManager->resolveToken();
$labelFormat = trim((string) ($package['label_format'] ?? 'PDF'));
$pageSize = $labelFormat === 'ZPL' ? 'A6' : 'A4';
$pageSize = 'A6';
$binary = $this->apiClient->getShipmentLabel($env, $accessToken, [$shipmentId], $pageSize);
$dir = rtrim($storagePath, '/\\') . '/labels';
@@ -286,10 +287,11 @@ final class AllegroShipmentService implements ShipmentProviderInterface
if (trim((string) ($package['tracking_number'] ?? '')) === '') {
try {
$details = $this->apiClient->getShipmentDetails($env, $accessToken, $shipmentId);
$trackingNumber = trim((string) ($details['waybill'] ?? ''));
$detailPackages = is_array($details['packages'] ?? null) ? $details['packages'] : [];
$trackingNumber = trim((string) ($detailPackages[0]['waybill'] ?? ''));
$carrierId = trim((string) ($package['carrier_id'] ?? ''));
if ($carrierId === '') {
$carrierId = trim((string) ($details['carrierId'] ?? ''));
$carrierId = trim((string) ($details['carrier'] ?? ''));
}
if ($trackingNumber !== '') {

View File

@@ -3,15 +3,16 @@ declare(strict_types=1);
namespace App\Modules\Shipments;
use App\Modules\Settings\AllegroApiClient;
use App\Modules\Settings\AllegroTokenManager;
use App\Modules\Settings\InpostIntegrationRepository;
use Throwable;
final class AllegroTrackingService implements ShipmentTrackingInterface
{
private const INPOST_API_PRODUCTION = 'https://api-shipx-pl.easypack24.net/v1';
private const INPOST_API_SANDBOX = 'https://sandbox-api-shipx-pl.easypack24.net/v1';
public function __construct(
private readonly AllegroApiClient $apiClient,
private readonly AllegroTokenManager $tokenManager
private readonly InpostIntegrationRepository $inpostRepository
) {
}
@@ -22,32 +23,122 @@ final class AllegroTrackingService implements ShipmentTrackingInterface
public function getDeliveryStatus(array $package): ?array
{
$shipmentId = trim((string) ($package['shipment_id'] ?? ''));
if ($shipmentId === '') {
$trackingNumber = trim((string) ($package['tracking_number'] ?? ''));
if ($trackingNumber === '') {
return null;
}
return $this->fetchStatus($shipmentId);
$carrierId = strtolower(trim((string) ($package['carrier_id'] ?? '')));
if (str_contains($carrierId, 'inpost') || str_contains($carrierId, 'paczkomat')) {
return $this->fetchInpostStatus($trackingNumber);
}
// Allegro Delivery (One Kurier), DHL, DPD via Allegro — brak publicznego API trackingu
return null;
}
private function fetchStatus(string $shipmentId): ?array
private function fetchInpostStatus(string $trackingNumber): ?array
{
try {
[$accessToken, $env] = $this->tokenManager->resolveToken();
$details = $this->apiClient->getShipmentDetails($env, $accessToken, $shipmentId);
$token = $this->resolveInpostToken();
if ($token === null) {
return null;
}
$rawStatus = strtoupper(trim((string) ($details['status'] ?? '')));
$settings = $this->inpostRepository->getSettings();
$env = (string) ($settings['environment'] ?? 'sandbox');
$baseUrl = strtolower(trim($env)) === 'production'
? self::INPOST_API_PRODUCTION
: self::INPOST_API_SANDBOX;
$url = $baseUrl . '/tracking/' . rawurlencode($trackingNumber);
$response = $this->apiRequest($url, $token);
$details = is_array($response['tracking_details'] ?? null) ? $response['tracking_details'] : [];
if ($details === []) {
return null;
}
$rawStatus = strtolower(trim((string) ($details[0]['status'] ?? '')));
if ($rawStatus === '') {
return null;
}
return [
'status' => DeliveryStatus::normalize('allegro_wza', $rawStatus),
'status' => DeliveryStatus::normalize('inpost', $rawStatus),
'status_raw' => $rawStatus,
'description' => DeliveryStatus::description('allegro_wza', $rawStatus),
'description' => DeliveryStatus::description('inpost', $rawStatus),
];
} catch (Throwable) {
return null;
}
}
private function resolveInpostToken(): ?string
{
try {
$token = $this->inpostRepository->getDecryptedToken();
return ($token !== null && trim($token) !== '') ? trim($token) : null;
} catch (Throwable) {
return null;
}
}
/**
* @return array<string, mixed>
*/
private function apiRequest(string $url, string $token): array
{
$ch = curl_init($url);
if ($ch === false) {
return [];
}
$opts = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $token,
'Accept: application/json',
],
];
$caPath = $this->getCaBundlePath();
if ($caPath !== null) {
$opts[CURLOPT_CAINFO] = $caPath;
}
curl_setopt_array($ch, $opts);
$body = curl_exec($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$ch = null;
if ($body === false || $httpCode < 200 || $httpCode >= 300) {
return [];
}
$json = json_decode((string) $body, true);
return is_array($json) ? $json : [];
}
private function getCaBundlePath(): ?string
{
$candidates = [
(string) ($_ENV['CURL_CA_BUNDLE_PATH'] ?? ''),
(string) ini_get('curl.cainfo'),
'C:/xampp/apache/bin/curl-ca-bundle.crt',
'C:/xampp/php/extras/ssl/cacert.pem',
'/etc/ssl/certs/ca-certificates.crt',
];
foreach ($candidates as $path) {
if ($path !== '' && is_file($path)) {
return $path;
}
}
return null;
}
}

View File

@@ -308,10 +308,6 @@ final class DeliveryStatus
return 'https://inpost.pl/sledzenie-przesylek?number=' . $encoded;
}
if ($provider === 'allegro_wza') {
return 'https://allegro.pl/przesylka/' . $encoded;
}
if ($carrierId !== '') {
$url = self::matchCarrierByName($encoded, strtolower(trim($carrierId)));
if ($url !== null) {
@@ -319,6 +315,10 @@ final class DeliveryStatus
}
}
if ($provider === 'allegro_wza') {
return 'https://allegro.pl/allegrodelivery/sledzenie-paczki?numer=' . $encoded;
}
return 'https://www.google.com/search?q=' . $encoded . '+sledzenie+przesylki';
}
@@ -348,6 +348,9 @@ final class DeliveryStatus
if (str_contains($carrier, 'gls')) {
return 'https://gls-group.com/PL/pl/sledzenie-paczek?match=' . $encoded;
}
if ($carrier === 'allegro') {
return 'https://allegro.pl/allegrodelivery/sledzenie-paczki?numer=' . $encoded;
}
return null;
}