Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backend/CLAUDE.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

use App\Http\Resources\ApiResource;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use PHPeste\Payments\Enums\PaymentMethod;
use PHPeste\Payments\Models\PaymentAccount;
use PHPeste\Payments\Models\WebhookEventRecord;

class PaymentAccountResource extends ApiResource
{
Expand Down Expand Up @@ -45,6 +47,16 @@ public function toArray(Request $request): array
'retired_at' => $this->isoDate($account->retired_at),
'created_at' => $this->isoDate($account->created_at),
'webhook_url' => $account->isActive() ? url("/api/v1/webhooks/payments/{$account->webhook_token}") : null,
// Último evento assinado que o gateway mandou para esta conta: mostra
// no painel se o webhook continua chegando depois do primeiro teste.
'last_event_at' => $account->isActive() ? $this->isoDate($this->lastEventAt($account)) : null,
];
}

private function lastEventAt(PaymentAccount $account): ?Carbon
{
$latest = WebhookEventRecord::query()->forEdition($account->edition_id)->where('payment_account_id', $account->id)->latest()->first(['created_at']);

return $latest?->created_at;
}
}
16 changes: 16 additions & 0 deletions backend/app-modules/payments/tests/Feature/PaymentAccountsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@ function webhook(object $test, string $url, string $body, string $secret = WEBHO
->assertJsonPath('data', ['driver' => 'fake', 'public_key' => null, 'holder_name' => 'Fulana de Tal, responsável financeira da PHPeste 2027', 'holder_type' => 'individual', 'methods' => ['pix', 'card'], 'max_installments' => 3, 'pix_expiration_minutes' => 30, 'sandbox' => true, 'ready' => true]);
});

it('mostra quando chegou o último evento do webhook da conta ativa', function (): void {
$id = $this->postJson($this->base, accountPayload())->json('data.id');
$this->getJson($this->base)->assertJsonPath('data.active.last_event_at', null);

$url = parse_url((string) $this->getJson($this->base)->json('data.active.webhook_url'), PHP_URL_PATH);
$this->travel(5)->minutes();
webhook($this, $url, '{"id":"evt_1","type":"ping"}')->assertOk();

$this->getJson($this->base)
->assertJsonPath('data.active.id', $id)
->assertJsonPath('data.active.last_event_at', now()->utc()->toIso8601ZuluString());

$this->postJson($this->base, accountPayload(['api_key' => 'nova_chave_3333']))->assertCreated();
$this->getJson($this->base)->assertJsonPath('data.active.last_event_at', null)->assertJsonPath('data.previous.0.last_event_at', null);
});

it('trocar a conta cria uma nova, guarda a antiga só para consulta e audita sem expor a chave', function (): void {
$old = $this->postJson($this->base, accountPayload())->json('data.id');
$new = $this->postJson($this->base, accountPayload(['api_key' => 'nova_chave_produção_wxyz', 'environment' => 'production', 'holder_type' => 'company', 'holder_name' => 'Associação PHP Paraíba', 'holder_document' => '11.222.333/0001-81']))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,14 @@ class OrderController
* Pedidos da edição, do mais novo para o mais antigo. `status` filtra pela
* situação; `q` procura no nome, no e-mail ou no número (com ou sem #).
*/
public function index(Request $request): AnonymousResourceCollection
public function index(Request $request, EditionDirectory $editions, CurrentEdition $currentEdition): AnonymousResourceCollection
{
Gate::authorize(EditionPermission::ViewOrders->value);

return OrderResource::collection($this->filtered($request)->with('items')->paginate(25));
$timezone = $editions->summary((string) $currentEdition->id())['timezone'] ?? 'America/Fortaleza';

return OrderResource::collection($this->filtered($request)->with('items')->paginate(25))
->additional(['meta' => ['summary' => $this->summary($timezone)]]);
}

/**
Expand Down Expand Up @@ -125,6 +128,29 @@ public function remind(Request $request, SendPaymentReminder $reminder): JsonRes
return response()->json(['data' => ['delivery_id' => $reminder->handle($this->order($request), $this->actor($request))]], 202);
}

/**
* Números da edição inteira para o topo da lista (não seguem o filtro):
* pagos, aguardando (e quantos vencem até o fim do dia), reembolsos e a
* taxa do gateway sobre o bruto recebido.
*
* @return array{paid: int, awaiting: int, awaiting_expiring_today: int, refunds: int, refunded_cents: int, gross_cents: int, gateway_fee_cents: int}
*/
private function summary(string $timezone): array
{
$received = [OrderStatus::Paid->value, OrderStatus::Refunded->value];
$endOfDay = now($timezone)->endOfDay()->utc();

return [
'paid' => Order::query()->where('status', OrderStatus::Paid->value)->count(),
'awaiting' => Order::query()->where('status', OrderStatus::AwaitingPayment->value)->count(),
'awaiting_expiring_today' => Order::query()->where('status', OrderStatus::AwaitingPayment->value)->where('expires_at', '<=', $endOfDay)->count(),
'refunds' => Order::query()->where('refunded_cents', '>', 0)->count(),
'refunded_cents' => (int) Order::query()->sum('refunded_cents'),
'gross_cents' => (int) Order::query()->whereIn('status', $received)->sum('total_cents'),
'gateway_fee_cents' => (int) Order::query()->whereIn('status', $received)->sum('gateway_fee_cents'),
];
}

/**
* @return EloquentBuilder<Order>
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,28 @@ function memberAs(object $test, EditionRole $role): User
expect($all)->toHaveCount(2)->and($all[1])->toContain('Caio Reis');
});

it('a lista traz o resumo da edição inteira, sem seguir o filtro', function (): void {
$paid = awaitingOrder($this, 'Ana Souza', 'pedido-1');
awaitingOrder($this, 'Caio Reis', 'pedido-2');
Sanctum::actingAs($this->organizer);
$this->postJson("{$this->api}/{$paid->id}/mark-paid", ['justification' => 'Recebido em dinheiro na secretaria'])->assertOk();
Order::query()->forEdition($this->edition->id)->whereKey($paid->id)->update(['gateway_fee_cents' => 1_497, 'refunded_cents' => 5_000]);

$this->getJson("{$this->api}?status=paid")
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('meta.total', 1)
->assertJsonPath('meta.summary', [
'paid' => 1,
'awaiting' => 1,
'awaiting_expiring_today' => 1,
'refunds' => 1,
'refunded_cents' => 5_000,
'gross_cents' => 30_000,
'gateway_fee_cents' => 1_497,
]);
});

it('outra edição não enxerga pedido nem histórico', function (): void {
$order = awaitingOrder($this);
$other = Edition::factory()->status(EditionStatus::SalesOpen)->create();
Expand Down
Binary file modified docs/arquitetura/PHPeste_Arquitetura.pdf
Binary file not shown.
Loading
Loading