diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md index 9d69299..2a6f4d6 100644 --- a/backend/CLAUDE.md +++ b/backend/CLAUDE.md @@ -21,7 +21,7 @@ Com implementação real até agora: - `suppliers`: fornecedores, sob a permissão `suppliers.manage` (só organizador), em `/editions/{id}/suppliers`. O cadastro (`suppliers`, com contatos em `supplier_contacts`) é global **da comunidade**, não da plataforma: toda consulta passa por `Access\SupplierAccess`, que filtra pelo `community_id` da edição (lido do contrato `EditionDirectory::communityId`), então outra comunidade recebe 404. Nome (comparado por `name_key`, sem acento e caixa) e CNPJ/CPF não se repetem na comunidade. O contato e o documento só aparecem para quem é da equipe de alguma edição em que o fornecedor está (`canSeeContacts`); para os outros, vem `contacts: null` e `contacts_visible: false`. Na edição, o vínculo (`edition_suppliers`) tem status `SupplierStatus` (a contatar, em orçamento, contratado, recusado), responsável da equipe e valor contratado. O primeiro orçamento (`supplier_quotes`) passa para "em orçamento"; contratar exige um orçamento (que vira aceito) ou um valor, recusar exige motivo, e a mudança é auditada como `suppliers.status_changed`. O "orçado" de cada fornecedor é o menor orçamento recebido ou aceito. A lista (`GET /suppliers`, sem paginação) devolve os totais de orçado (sem os recusados) e contratado calculados sobre a mesma lista filtrada (`SupplierTotals`), que também vão para a Visão geral (`indicators.suppliers`). Histórico em `supplier_activities`: anotações da equipe com canal e registros automáticos de status, orçamento e anexo. Anexos (`supplier_attachments`: orçamento, contrato, nota fiscal) seguem o mesmo esquema dos patrocinadores: disco privado `SUPPLIERS_ATTACHMENTS_DISK` e download só por URL assinada que expira (`/api/v1/suppliers/attachments/{id}/download`). Reaproveitar fornecedor: `GET /suppliers/directory?q=` busca no cadastro da comunidade e mostra em que edições ele esteve e com que status; `POST /suppliers/directory/{supplier}` traz para esta edição como "a contatar". `SuppliersCloner` leva os contratados para a próxima edição como "a contatar", sem valores nem orçamentos. - `finance`: finanças da edição, sem nota fiscal, sob a permissão `finance.manage` (organizador e financeiro), em `/editions/{id}/finance`. A receita não é guardada: `Reports\FinanceReport` calcula na hora a partir dos contratos `Ticketing\Contracts\TicketRevenue` (pedidos pagos ou reembolsados com valor, por conta de recebimento: vendido, reembolsos, taxa do gateway real em `orders.gateway_fee_cents` ou estimada pelo percentual da edição, e líquido) e `Sponsors\Contracts\SponsorRevenue` (patrocínio recebido e a receber), com o titular de cada conta (CPF ou CNPJ, documento mascarado, inclusive contas trocadas) vindo de `PaymentAccounts::all`. Pedido gratuito e importado ficam de fora. Saldo = receita líquida recebida − despesas pagas; previsão = saldo + patrocínio a receber − despesas a pagar. Despesas (`expenses`) com categoria, fornecedor opcional da edição (contrato `Suppliers\Contracts\EditionSuppliers`), valor, vencimento, status (a pagar, paga, que exige data, ou cancelada) e comprovante no disco privado `FINANCE_RECEIPTS_DISK`, baixado só por URL assinada que expira; criar, mudar e remover são auditados (`finance.expense_*`). Categorias (`finance_categories`) com orçamento: a edição ganha as padrão (`FinanceCategory::DEFAULTS`) na primeira leitura, e o resumo compara orçado, comprometido (a pagar e paga) e pago por categoria. `GET .../export` gera XLSX com as abas Resumo, Receita por conta, Orçamento e Despesas (`Export\XlsxWriter`, sem biblioteca, com `ZipArchive`; valores como número), e `?format=csv` gera só as despesas, com ponto e vírgula e BOM. Texto que começa com `=`, `+`, `-` ou `@` ganha apóstrofo para não virar fórmula. A Visão geral recebe a pendência de despesas vencidas (só para quem tem `finance.manage`), e `FinanceCloner` leva categorias e orçamento para a próxima edição. - `tasks`: quadro kanban da organização, em `/editions/{id}/tasks`. Toda a equipe da edição vê o quadro (`GET /board?filter=mine|overdue`); `tasks.manage` (só organizador) cria, edita, remove e mexe nas colunas, e o responsável move a própria tarefa. Colunas (`task_columns`, as quatro de `TaskColumn::DEFAULTS` nascem na primeira leitura) com `is_done`: tarefa que entra nela ganha `completed_at` e deixa de ficar atrasada; o quadro nunca fica sem coluna de concluídas e só remove coluna vazia. Mover (`MoveTask`): trava as colunas de origem e destino pelo id, em ordem, e renumera as duas de 0 a n−1 na mesma transação; se a tarefa mudou de coluna enquanto isso, tenta de novo. `TaskReorderConcurrencyTest` prova com 12 processos PHP simultâneos que não duplica nem perde posição. Atrasada = prazo antes de hoje e não concluída (pendência na Visão geral). E-mail só para o responsável, se ainda é da equipe e se não desligou `assigned_tasks` (`UserAccounts::wantsNotification`): `task_assigned` ao virar responsável (menos quando a pessoa se atribui) e `task_due_soon` pelo `tasks:due-reminders` (08:00 de Brasília), uma vez por prazo; mudar o prazo libera outro lembrete. Vínculo da tarefa (`link_type`, `link_id`) por ponto de extensão: o módulo dono implementa `Tasks\Contracts\TaskLinkProvider` e registra com `$app->tag([...], TaskLinkProvider::TAG)` (hoje `supplier`, do Suppliers, e `sponsorship`, do Sponsors; a sessão entra com o Program). `TasksCloner` leva colunas e tarefas para a próxima edição como checklist, sem responsável, prazo nem vínculo. -- `notifications`: e-mail transacional por edição. Outro módulo envia pelo contrato `EditionMailer::send(editionId, EmailTemplate, email, nome, variáveis, url)`, que registra o envio em `email_deliveries` e enfileira `SendEmailDelivery` (5 tentativas, backoff 30s → 30min). Os tipos de e-mail ficam em `EmailTemplate` (assunto/corpo padrão, variáveis permitidas, transacional ou não), e a edição só sobrescreve assunto e corpo (`email_templates`). O corpo é texto com `{variavel}`, substituído sem Blade e com todo HTML escapado. O layout usa o tema publicado (Branding). Não transacional leva link assinado e `List-Unsubscribe` (one-click), e quem se descadastra fica em `email_unsubscribes`. Produção usa Resend (`MAIL_MAILER=resend`, `RESEND_API_KEY`) e dev usa o Mailpit. +- `notifications`: e-mail transacional por edição. Outro módulo envia pelo contrato `EditionMailer::send(editionId, EmailTemplate, email, nome, variáveis, url)`, que registra o envio em `email_deliveries` e enfileira `SendEmailDelivery` (5 tentativas, backoff 30s → 30min). Os tipos de e-mail ficam em `EmailTemplate` (assunto/corpo padrão, variáveis permitidas, transacional ou não), e a edição só sobrescreve assunto e corpo (`email_templates`). O corpo é texto com `{variavel}`, substituído sem Blade e com todo HTML escapado. O layout usa o tema publicado (Branding). Não transacional leva link assinado e `List-Unsubscribe` (one-click), e quem se descadastra fica em `email_unsubscribes`. Produção usa Resend (`MAIL_MAILER=resend`, `RESEND_API_KEY`) e dev usa o Mailpit. O transport do Resend grava o id do Resend como Message-ID, e o envio guarda esse id em `provider_message_id`. Webhooks do Resend em `POST /api/v1/webhooks/resend` (`throttle:webhooks`): assinatura Svix verificada com `RESEND_WEBHOOK_SECRET` e janela de 5 minutos (`Webhooks\SvixSignature`, 401 e nada muda se falhar), um registro por `svix-id` em `email_webhook_events` (entrega repetida responde `duplicate: true`) e a edição descoberta pelo envio (`provider_message_id`), nunca pelo que o webhook manda. `email.delivered` marca entregue; bounce permanente e `email.complained` marcam o envio e bloqueiam o endereço na edição (`email_suppressions`, auditado como `notifications.address_suppressed`), inclusive para e-mail transacional e para o que já estava na fila; bounce temporário e `email.delivery_delayed` só registram o motivo em `provider_detail`. A organização vê os bloqueados em `GET /emails/suppressions` e libera em `DELETE /emails/suppressions/{id}` (`notifications.suppression_lifted`); reenviar para endereço bloqueado é recusado. ## Estrutura de cada módulo (`app-modules//src/`) diff --git a/backend/app-modules/notifications/database/migrations/2026_12_03_100000_add_delivery_tracking_and_suppressions.php b/backend/app-modules/notifications/database/migrations/2026_12_03_100000_add_delivery_tracking_and_suppressions.php new file mode 100644 index 0000000..a49ec99 --- /dev/null +++ b/backend/app-modules/notifications/database/migrations/2026_12_03_100000_add_delivery_tracking_and_suppressions.php @@ -0,0 +1,59 @@ +timestamp('delivered_at')->nullable(); + $table->timestamp('bounced_at')->nullable(); + $table->timestamp('complained_at')->nullable(); + $table->string('provider_detail', 500)->nullable(); + + $table->index('provider_message_id'); + }); + + // Endereço que não recebe mais nada da edição (nem transacional) até a + // organização liberar: bounce permanente ou reclamação de spam. + Schema::create('email_suppressions', function (Blueprint $table): void { + $table->uuid('id')->primary(); + $table->foreignUuid('edition_id')->constrained('editions')->cascadeOnDelete(); + $table->string('email'); + $table->string('reason', 16); + $table->string('detail', 500)->nullable(); + $table->uuid('email_delivery_id')->nullable(); + $table->timestamps(); + + $table->unique(['edition_id', 'email']); + }); + + // Caixa de entrada dos webhooks do Resend, um registro por svix-id: + // a mesma entrega repetida não tem efeito duas vezes. + Schema::create('email_webhook_events', function (Blueprint $table): void { + $table->uuid('id')->primary(); + $table->string('svix_id', 100)->unique(); + $table->string('type', 40); + $table->string('provider_message_id', 100)->nullable(); + $table->uuid('edition_id')->nullable()->index(); + $table->string('outcome', 16); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('email_webhook_events'); + Schema::dropIfExists('email_suppressions'); + + Schema::table('email_deliveries', function (Blueprint $table): void { + $table->dropIndex(['provider_message_id']); + $table->dropColumn(['delivered_at', 'bounced_at', 'complained_at', 'provider_detail']); + }); + } +}; diff --git a/backend/app-modules/notifications/routes/notifications-routes.php b/backend/app-modules/notifications/routes/notifications-routes.php index 34907a5..e533b0f 100644 --- a/backend/app-modules/notifications/routes/notifications-routes.php +++ b/backend/app-modules/notifications/routes/notifications-routes.php @@ -5,7 +5,9 @@ use Illuminate\Support\Facades\Route; use PHPeste\Notifications\Enums\EmailTemplate; use PHPeste\Notifications\Http\Controllers\EmailDeliveryController; +use PHPeste\Notifications\Http\Controllers\EmailSuppressionController; use PHPeste\Notifications\Http\Controllers\EmailTemplateController; +use PHPeste\Notifications\Http\Controllers\ResendWebhookController; use PHPeste\Notifications\Http\Controllers\UnsubscribeController; Route::apiV1Edition('emails')->group(function (): void { @@ -33,8 +35,17 @@ Route::post('/deliveries/{delivery}/resend', [EmailDeliveryController::class, 'resend']) ->whereUuid('delivery') ->name('notifications.deliveries.resend'); + + Route::get('/suppressions', [EmailSuppressionController::class, 'index'])->name('notifications.suppressions.index'); + Route::delete('/suppressions/{suppression}', [EmailSuppressionController::class, 'destroy']) + ->whereUuid('suppression') + ->name('notifications.suppressions.destroy'); }); +Route::apiV1('webhooks')->post('/resend', ResendWebhookController::class) + ->middleware('throttle:webhooks') + ->name('notifications.webhooks.resend'); + Route::apiV1('public')->match(['get', 'post'], '/editions/{edition}/unsubscribe', UnsubscribeController::class) ->whereUuid('edition') ->middleware('signed') diff --git a/backend/app-modules/notifications/src/Actions/QueueEmail.php b/backend/app-modules/notifications/src/Actions/QueueEmail.php index c41c8ad..6e90c22 100644 --- a/backend/app-modules/notifications/src/Actions/QueueEmail.php +++ b/backend/app-modules/notifications/src/Actions/QueueEmail.php @@ -9,6 +9,7 @@ use PHPeste\Notifications\Enums\EmailTemplate; use PHPeste\Notifications\Jobs\SendEmailDelivery; use PHPeste\Notifications\Models\EmailDelivery; +use PHPeste\Notifications\Models\EmailSuppression; use PHPeste\Notifications\Models\EmailUnsubscribe; class QueueEmail implements EditionMailer @@ -33,7 +34,8 @@ public function queue( bool $isTest = false, ): EmailDelivery { $email = mb_strtolower(mb_trim($email)); - $suppressed = !$template->isTransactional() && !$isTest && $this->isUnsubscribed($editionId, $email); + $blocked = $this->isBlocked($editionId, $email); + $suppressed = $blocked || (!$template->isTransactional() && !$isTest && $this->isUnsubscribed($editionId, $email)); $delivery = EmailDelivery::create([ 'edition_id' => $editionId, @@ -44,6 +46,7 @@ public function queue( 'content' => $content, 'action_url' => $actionUrl, 'status' => $suppressed ? DeliveryStatus::Suppressed : DeliveryStatus::Queued, + 'provider_detail' => $blocked ? 'Endereço bloqueado nesta edição por bounce permanente ou spam' : null, 'is_test' => $isTest, ]); @@ -54,6 +57,15 @@ public function queue( return $delivery; } + /** + * Bounce permanente ou reclamação: nada sai para o endereço, nem e-mail + * transacional, até a organização liberar. + */ + public function isBlocked(string $editionId, string $email): bool + { + return EmailSuppression::query()->forEdition($editionId)->where('email', $email)->exists(); + } + private function isUnsubscribed(string $editionId, string $email): bool { return EmailUnsubscribe::query()->forEdition($editionId)->where('email', $email)->exists(); diff --git a/backend/app-modules/notifications/src/Actions/ResendEmail.php b/backend/app-modules/notifications/src/Actions/ResendEmail.php index c187201..1a5c01d 100644 --- a/backend/app-modules/notifications/src/Actions/ResendEmail.php +++ b/backend/app-modules/notifications/src/Actions/ResendEmail.php @@ -11,15 +11,23 @@ class ResendEmail { + public function __construct(private readonly QueueEmail $queue) {} + public function handle(EmailDelivery $delivery): EmailDelivery { + if ($this->queue->isBlocked($delivery->edition_id, $delivery->to_email)) { + throw ValidationException::withMessages([ + 'delivery' => 'Este endereço está bloqueado por bounce ou spam. Libere em "Endereços bloqueados" antes de reenviar.', + ]); + } + if ($delivery->status === DeliveryStatus::Queued) { throw ValidationException::withMessages([ 'delivery' => 'Este envio ainda está na fila.', ]); } - $delivery->update(['status' => DeliveryStatus::Queued, 'last_error' => null]); + $delivery->update(['status' => DeliveryStatus::Queued, 'last_error' => null, 'provider_detail' => null, 'delivered_at' => null, 'bounced_at' => null, 'complained_at' => null]); dispatch(new SendEmailDelivery($delivery->edition_id, $delivery->id)); diff --git a/backend/app-modules/notifications/src/Enums/DeliveryStatus.php b/backend/app-modules/notifications/src/Enums/DeliveryStatus.php index 6a22c72..f5d3a8b 100644 --- a/backend/app-modules/notifications/src/Enums/DeliveryStatus.php +++ b/backend/app-modules/notifications/src/Enums/DeliveryStatus.php @@ -8,6 +8,22 @@ enum DeliveryStatus: string { case Queued = 'queued'; case Sent = 'sent'; + case Delivered = 'delivered'; + case Bounced = 'bounced'; + case Complained = 'complained'; case Failed = 'failed'; case Suppressed = 'suppressed'; + + public function label(): string + { + return match ($this) { + self::Queued => 'Na fila', + self::Sent => 'Enviado', + self::Delivered => 'Entregue', + self::Bounced => 'Voltou (bounce)', + self::Complained => 'Marcado como spam', + self::Failed => 'Falhou', + self::Suppressed => 'Não enviado: endereço bloqueado', + }; + } } diff --git a/backend/app-modules/notifications/src/Enums/SuppressionReason.php b/backend/app-modules/notifications/src/Enums/SuppressionReason.php new file mode 100644 index 0000000..5453625 --- /dev/null +++ b/backend/app-modules/notifications/src/Enums/SuppressionReason.php @@ -0,0 +1,19 @@ + 'Bounce permanente (endereço não existe ou recusa)', + self::Complained => 'Marcou o e-mail como spam', + }; + } +} diff --git a/backend/app-modules/notifications/src/Events/AddressSuppressionChanged.php b/backend/app-modules/notifications/src/Events/AddressSuppressionChanged.php new file mode 100644 index 0000000..728602a --- /dev/null +++ b/backend/app-modules/notifications/src/Events/AddressSuppressionChanged.php @@ -0,0 +1,41 @@ +editionId, + $this->lifted ? 'notifications.suppression_lifted' : 'notifications.address_suppressed', + 'email_suppression', + $this->suppressionId, + $this->actorId, + null, + ['email' => $this->email, 'reason' => $this->reason], + ); + } +} diff --git a/backend/app-modules/notifications/src/Http/Controllers/EmailSuppressionController.php b/backend/app-modules/notifications/src/Http/Controllers/EmailSuppressionController.php new file mode 100644 index 0000000..7e45e1c --- /dev/null +++ b/backend/app-modules/notifications/src/Http/Controllers/EmailSuppressionController.php @@ -0,0 +1,61 @@ +query('q'))); + $page = EmailSuppression::query() + ->when($search !== '', fn ($query) => $query->where('email', 'like', "%{$search}%")) + ->latest()->orderByDesc('id') + ->paginate(50); + + return response()->json([ + 'data' => collect($page->items())->map(fn (EmailSuppression $suppression): array => [ + 'id' => $suppression->id, + 'email' => $suppression->email, + 'reason' => $suppression->reason->value, + 'reason_label' => $suppression->reason->label(), + 'detail' => $suppression->detail, + 'delivery_id' => $suppression->email_delivery_id, + 'created_at' => $suppression->created_at->clone()->utc()->toIso8601ZuluString(), + ])->all(), + 'meta' => ['current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), 'per_page' => $page->perPage(), 'total' => $page->total()], + ]); + } + + public function destroy(Request $request): Response + { + Gate::authorize('manage-edition-emails'); + + $id = $request->route('suppression'); + abort_unless(is_string($id), 404); + $suppression = EmailSuppression::query()->whereKey($id)->firstOrFail(); + $actor = $request->user()?->getAuthIdentifier(); + + DB::transaction(function () use ($suppression, $actor): void { + $suppression->delete(); + event(new AddressSuppressionChanged($suppression->edition_id, $suppression->id, $suppression->email, $suppression->reason->value, true, is_string($actor) ? $actor : null)); + }); + + return response()->noContent(); + } +} diff --git a/backend/app-modules/notifications/src/Http/Controllers/ResendWebhookController.php b/backend/app-modules/notifications/src/Http/Controllers/ResendWebhookController.php new file mode 100644 index 0000000..cb0c7f6 --- /dev/null +++ b/backend/app-modules/notifications/src/Http/Controllers/ResendWebhookController.php @@ -0,0 +1,41 @@ +getContent(); + $signature = new SvixSignature((string) config('services.resend.webhook_secret')); + + if (!$signature->valid($request->header('svix-id'), $request->header('svix-timestamp'), $request->header('svix-signature'), $body)) { + Log::warning('Webhook do Resend com assinatura inválida.', ['svix_id' => $request->header('svix-id')]); + + return response()->json(['code' => 'invalid_signature', 'message' => 'Assinatura inválida.'], 401); + } + + $payload = json_decode($body, true); + + if (!is_array($payload)) { + return response()->json(['code' => 'invalid_payload', 'message' => 'Corpo inválido.'], 400); + } + + /** @var array $payload */ + $outcome = $process->handle((string) $request->header('svix-id'), $payload); + + return response()->json(['data' => ['outcome' => $outcome, 'duplicate' => $outcome === 'duplicate']]); + } +} diff --git a/backend/app-modules/notifications/src/Http/Resources/EmailDeliveryResource.php b/backend/app-modules/notifications/src/Http/Resources/EmailDeliveryResource.php index d9be432..63a246d 100644 --- a/backend/app-modules/notifications/src/Http/Resources/EmailDeliveryResource.php +++ b/backend/app-modules/notifications/src/Http/Resources/EmailDeliveryResource.php @@ -27,6 +27,11 @@ public function toArray(Request $request): array 'to_email' => $delivery->to_email, 'to_name' => $delivery->to_name, 'status' => $delivery->status->value, + 'status_label' => $delivery->status->label(), + 'provider_detail' => $delivery->provider_detail, + 'delivered_at' => $this->isoDate($delivery->delivered_at), + 'bounced_at' => $this->isoDate($delivery->bounced_at), + 'complained_at' => $this->isoDate($delivery->complained_at), 'attempts' => $delivery->attempts, 'last_error' => $delivery->last_error, 'is_test' => $delivery->is_test, diff --git a/backend/app-modules/notifications/src/Jobs/SendEmailDelivery.php b/backend/app-modules/notifications/src/Jobs/SendEmailDelivery.php index 4253755..3b2c653 100644 --- a/backend/app-modules/notifications/src/Jobs/SendEmailDelivery.php +++ b/backend/app-modules/notifications/src/Jobs/SendEmailDelivery.php @@ -7,6 +7,7 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Facades\Mail; +use PHPeste\Notifications\Actions\QueueEmail; use PHPeste\Notifications\Enums\DeliveryStatus; use PHPeste\Notifications\Mail\EditionMail; use PHPeste\Notifications\Mail\EmailComposer; @@ -42,6 +43,14 @@ public function handle(EmailComposer $composer): void return; } + // O endereço pode ter sido bloqueado (bounce, spam) enquanto o envio + // esperava na fila. + if (resolve(QueueEmail::class)->isBlocked($delivery->edition_id, $delivery->to_email)) { + $delivery->update(['status' => DeliveryStatus::Suppressed, 'provider_detail' => 'Endereço bloqueado nesta edição por bounce permanente ou spam']); + + return; + } + $delivery->update(['attempts' => $delivery->attempts + 1]); try { diff --git a/backend/app-modules/notifications/src/Models/EmailDelivery.php b/backend/app-modules/notifications/src/Models/EmailDelivery.php index 0534d5c..347fd34 100644 --- a/backend/app-modules/notifications/src/Models/EmailDelivery.php +++ b/backend/app-modules/notifications/src/Models/EmailDelivery.php @@ -28,10 +28,14 @@ * @property string|null $provider_message_id * @property bool $is_test * @property Carbon|null $sent_at + * @property Carbon|null $delivered_at + * @property Carbon|null $bounced_at + * @property Carbon|null $complained_at + * @property string|null $provider_detail * @property Carbon $created_at * @property Carbon $updated_at */ -#[Fillable(['edition_id', 'template', 'to_email', 'to_name', 'variables', 'content', 'action_url', 'status', 'attempts', 'last_error', 'provider_message_id', 'is_test', 'sent_at'])] +#[Fillable(['edition_id', 'template', 'to_email', 'to_name', 'variables', 'content', 'action_url', 'status', 'attempts', 'last_error', 'provider_message_id', 'is_test', 'sent_at', 'delivered_at', 'bounced_at', 'complained_at', 'provider_detail'])] #[Table(name: 'email_deliveries')] class EmailDelivery extends Model { @@ -51,6 +55,9 @@ protected function casts(): array 'attempts' => 'integer', 'is_test' => 'boolean', 'sent_at' => 'datetime', + 'delivered_at' => 'datetime', + 'bounced_at' => 'datetime', + 'complained_at' => 'datetime', ]; } } diff --git a/backend/app-modules/notifications/src/Models/EmailSuppression.php b/backend/app-modules/notifications/src/Models/EmailSuppression.php new file mode 100644 index 0000000..22a067f --- /dev/null +++ b/backend/app-modules/notifications/src/Models/EmailSuppression.php @@ -0,0 +1,39 @@ + + */ + protected function casts(): array + { + return ['reason' => SuppressionReason::class]; + } +} diff --git a/backend/app-modules/notifications/src/Models/EmailWebhookEvent.php b/backend/app-modules/notifications/src/Models/EmailWebhookEvent.php new file mode 100644 index 0000000..984788a --- /dev/null +++ b/backend/app-modules/notifications/src/Models/EmailWebhookEvent.php @@ -0,0 +1,28 @@ + $payload + * @return string `processed`, `ignored` ou `duplicate` + */ + public function handle(string $svixId, array $payload): string + { + $type = is_string($payload['type'] ?? null) ? $payload['type'] : 'unknown'; + $data = is_array($payload['data'] ?? null) ? $payload['data'] : []; + $messageId = is_string($data['email_id'] ?? null) ? $data['email_id'] : null; + $delivery = $messageId === null ? null : EmailDelivery::query()->withoutGlobalScopes()->where('provider_message_id', $messageId)->first(); + + try { + return DB::transaction(function () use ($svixId, $type, $data, $messageId, $delivery): string { + $outcome = $delivery instanceof EmailDelivery + ? (string) $this->currentEdition->run($delivery->edition_id, fn (): string => $this->apply($delivery, $type, $data)) + : 'ignored'; + + EmailWebhookEvent::create([ + 'svix_id' => $svixId, + 'type' => mb_substr($type, 0, 40), + 'provider_message_id' => $messageId === null ? null : mb_substr($messageId, 0, 100), + 'edition_id' => $delivery?->edition_id, + 'outcome' => $outcome, + ]); + + return $outcome; + }); + } catch (UniqueConstraintViolationException) { + return 'duplicate'; + } + } + + /** + * @param array $data o `data` do evento, como veio do Resend + */ + private function apply(EmailDelivery $delivery, string $type, array $data): string + { + $bounce = is_array($data['bounce'] ?? null) ? $data['bounce'] : []; + $detail = mb_substr(mb_trim(implode(' · ', array_filter([ + is_string($bounce['type'] ?? null) ? $bounce['type'] : null, + is_string($bounce['subType'] ?? null) ? $bounce['subType'] : null, + is_string($bounce['message'] ?? null) ? $bounce['message'] : null, + ]))), 0, 500); + + switch ($type) { + case 'email.delivered': + if (in_array($delivery->status, [DeliveryStatus::Sent, DeliveryStatus::Queued], true)) { + $delivery->update(['status' => DeliveryStatus::Delivered, 'delivered_at' => now()]); + } + + return 'processed'; + + case 'email.bounced': + if (mb_strtolower((string) ($bounce['type'] ?? '')) !== 'permanent') { + $delivery->update(['provider_detail' => 'Bounce temporário'.($detail === '' ? '' : ': '.$detail)]); + + return 'processed'; + } + + $delivery->update(['status' => DeliveryStatus::Bounced, 'bounced_at' => now(), 'provider_detail' => $detail === '' ? 'Bounce permanente' : $detail]); + $this->suppress($delivery, SuppressionReason::Bounced, $detail); + + return 'processed'; + + case 'email.delivery_delayed': + $delivery->update(['provider_detail' => 'Entrega atrasada: o servidor de destino ainda não aceitou']); + + return 'processed'; + + case 'email.complained': + $delivery->update(['status' => DeliveryStatus::Complained, 'complained_at' => now()]); + $this->suppress($delivery, SuppressionReason::Complained, null); + + return 'processed'; + + default: + return 'ignored'; + } + } + + private function suppress(EmailDelivery $delivery, SuppressionReason $reason, ?string $detail): void + { + $suppression = EmailSuppression::query()->forEdition($delivery->edition_id)->firstOrCreate( + ['edition_id' => $delivery->edition_id, 'email' => $delivery->to_email], + ['reason' => $reason, 'detail' => $detail === '' ? null : $detail, 'email_delivery_id' => $delivery->id], + ); + + if ($suppression->wasRecentlyCreated) { + Log::warning('Endereço bloqueado por bounce ou reclamação.', ['edition_id' => $delivery->edition_id, 'reason' => $reason->value, 'delivery_id' => $delivery->id]); + event(new AddressSuppressionChanged($delivery->edition_id, $suppression->id, $delivery->to_email, $reason->value, false, null)); + } + } +} diff --git a/backend/app-modules/notifications/src/Webhooks/SvixSignature.php b/backend/app-modules/notifications/src/Webhooks/SvixSignature.php new file mode 100644 index 0000000..fae4912 --- /dev/null +++ b/backend/app-modules/notifications/src/Webhooks/SvixSignature.php @@ -0,0 +1,48 @@ +secret === '' || $id === null || $timestamp === null || $signatures === null || !ctype_digit($timestamp)) { + return false; + } + + if (abs(($now ?? now()->getTimestamp()) - (int) $timestamp) > self::TOLERANCE_SECONDS) { + return false; + } + + $expected = $this->sign($id, $timestamp, $body); + + foreach (explode(' ', $signatures) as $candidate) { + [$version, $signature] = array_pad(explode(',', $candidate, 2), 2, ''); + + if ($version === 'v1' && hash_equals($expected, $signature)) { + return true; + } + } + + return false; + } + + public function sign(string $id, string $timestamp, string $body): string + { + $key = base64_decode(str_starts_with($this->secret, 'whsec_') ? mb_substr($this->secret, 6) : $this->secret, true); + + return base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$body}", $key === false ? '' : $key, true)); + } +} diff --git a/backend/app-modules/notifications/tests/Feature/ResendWebhookTest.php b/backend/app-modules/notifications/tests/Feature/ResendWebhookTest.php new file mode 100644 index 0000000..2c3fb5f --- /dev/null +++ b/backend/app-modules/notifications/tests/Feature/ResendWebhookTest.php @@ -0,0 +1,159 @@ +set('services.resend.webhook_secret', RESEND_SECRET); + $this->travelTo('2027-06-10 12:00:00'); + $this->edition = Edition::factory()->status(EditionStatus::SalesOpen)->create(['name' => 'PHPeste 2027']); + $this->delivery = EmailDelivery::query()->forEdition($this->edition->id)->findOrFail( + resolve(EditionMailer::class)->send($this->edition->id, EmailTemplate::OrderConfirmed, 'ana@exemplo.com', 'Ana', ['nome' => 'Ana', 'pedido' => '#1']), + ); + $this->delivery->update(['provider_message_id' => 're_4ef9a417-02e9-4d39-ad75-9611e0fcc33c']); +}); + +function resendEvent(object $test, string $type, array $data = [], ?string $svixId = null, ?int $timestamp = null, ?string $secret = null): TestResponse +{ + $body = json_encode(['type' => $type, 'created_at' => '2027-06-10T12:00:00Z', 'data' => ['email_id' => 're_4ef9a417-02e9-4d39-ad75-9611e0fcc33c', 'to' => ['ana@exemplo.com'], ...$data]], JSON_THROW_ON_ERROR); + $svixId ??= 'msg_'.bin2hex(random_bytes(6)); + $timestamp ??= now()->getTimestamp(); + $signature = new SvixSignature($secret ?? RESEND_SECRET)->sign($svixId, (string) $timestamp, $body); + + return $test->call('POST', '/api/v1/webhooks/resend', [], [], [], [ + 'CONTENT_TYPE' => 'application/json', + 'HTTP_ACCEPT' => 'application/json', + 'HTTP_SVIX_ID' => $svixId, + 'HTTP_SVIX_TIMESTAMP' => (string) $timestamp, + 'HTTP_SVIX_SIGNATURE' => "v1,outra-assinatura v1,{$signature}", + ], $body); +} + +function resendDelivery(object $test): EmailDelivery +{ + return EmailDelivery::query()->forEdition($test->edition->id)->findOrFail($test->delivery->id); +} + +it('marca o envio como entregue', function (): void { + resendEvent($this, 'email.delivered')->assertOk()->assertJsonPath('data.outcome', 'processed'); + + expect(resendDelivery($this)->status)->toBe(DeliveryStatus::Delivered) + ->and(resendDelivery($this)->delivered_at)->not->toBeNull() + ->and(EmailWebhookEvent::query()->sole()->edition_id)->toBe($this->edition->id); +}); + +it('rejeita assinatura inválida, segredo errado ou timestamp fora da janela, sem mudar nada', function (): void { + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Permanent']], secret: 'whsec_'.base64_encode('outro-segredo'))->assertUnauthorized(); + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Permanent']], timestamp: now()->subMinutes(6)->getTimestamp())->assertUnauthorized(); + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Permanent']], timestamp: now()->addMinutes(6)->getTimestamp())->assertUnauthorized(); + $this->postJson('/api/v1/webhooks/resend', ['type' => 'email.bounced'])->assertUnauthorized(); + + config()->set('services.resend.webhook_secret'); + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Permanent']])->assertUnauthorized(); + + expect(resendDelivery($this)->status)->toBe(DeliveryStatus::Sent) + ->and(EmailSuppression::query()->forEdition($this->edition->id)->count())->toBe(0) + ->and(EmailWebhookEvent::query()->count())->toBe(0); +}); + +it('o mesmo evento recebido duas vezes não duplica efeito', function (): void { + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Permanent', 'subType' => 'General', 'message' => 'mailbox does not exist']], svixId: 'msg_repetido')->assertOk(); + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Permanent']], svixId: 'msg_repetido')->assertOk()->assertJsonPath('data.duplicate', true); + + expect(EmailWebhookEvent::query()->count())->toBe(1) + ->and(EmailSuppression::query()->forEdition($this->edition->id)->count())->toBe(1) + ->and(AuditLog::query()->where('action', 'notifications.address_suppressed')->count())->toBe(1); +}); + +it('bounce permanente bloqueia o endereço, inclusive para e-mail transacional, até a organização liberar', function (): void { + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Permanent', 'subType' => 'General', 'message' => 'mailbox does not exist']])->assertOk(); + + $bounced = resendDelivery($this); + expect($bounced->status)->toBe(DeliveryStatus::Bounced) + ->and($bounced->bounced_at)->not->toBeNull() + ->and($bounced->provider_detail)->toBe('Permanent · General · mailbox does not exist'); + + $next = EmailDelivery::query()->forEdition($this->edition->id)->findOrFail( + resolve(EditionMailer::class)->send($this->edition->id, EmailTemplate::TicketTransferred, 'ANA@exemplo.com', 'Ana', ['nome' => 'Ana']), + ); + expect($next->status)->toBe(DeliveryStatus::Suppressed)->and($next->provider_detail)->toContain('bloqueado'); + + $organizer = User::factory()->create(); + EditionMember::factory()->for($this->edition)->create(['user_id' => $organizer->id, 'role' => EditionRole::Organizer]); + Sanctum::actingAs($organizer); + $api = "/api/v1/editions/{$this->edition->id}/emails"; + + $this->postJson("{$api}/deliveries/{$next->id}/resend")->assertUnprocessable()->assertJsonValidationErrors(['delivery']); + + $list = $this->getJson("{$api}/suppressions")->assertOk()->json('data'); + expect($list)->toHaveCount(1) + ->and($list[0])->toMatchArray(['email' => 'ana@exemplo.com', 'reason' => 'bounced', 'delivery_id' => $this->delivery->id]); + + $this->getJson("{$api}/deliveries?status=bounced")->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.status_label', 'Voltou (bounce)'); + + $this->deleteJson("{$api}/suppressions/{$list[0]['id']}")->assertNoContent(); + expect(AuditLog::query()->where('action', 'notifications.suppression_lifted')->value('actor_id'))->toBe($organizer->id); + + $this->postJson("{$api}/deliveries/{$next->id}/resend")->assertOk()->assertJsonPath('data.status', 'sent'); +}); + +it('bounce temporário e entrega atrasada não bloqueiam o endereço', function (): void { + resendEvent($this, 'email.bounced', ['bounce' => ['type' => 'Transient', 'subType' => 'MailboxFull', 'message' => 'mailbox full']])->assertOk(); + resendEvent($this, 'email.delivery_delayed')->assertOk(); + + expect(resendDelivery($this)->status)->toBe(DeliveryStatus::Sent) + ->and(resendDelivery($this)->provider_detail)->toBe('Entrega atrasada: o servidor de destino ainda não aceitou') + ->and(EmailSuppression::query()->forEdition($this->edition->id)->count())->toBe(0); + + $next = resolve(EditionMailer::class)->send($this->edition->id, EmailTemplate::OrderConfirmed, 'ana@exemplo.com', 'Ana', ['nome' => 'Ana']); + expect(EmailDelivery::query()->forEdition($this->edition->id)->findOrFail($next)->status)->toBe(DeliveryStatus::Sent); +}); + +it('reclamação de spam marca o envio e bloqueia o endereço', function (): void { + resendEvent($this, 'email.delivered')->assertOk(); + resendEvent($this, 'email.complained')->assertOk(); + + expect(resendDelivery($this)->status)->toBe(DeliveryStatus::Complained) + ->and(EmailSuppression::query()->forEdition($this->edition->id)->sole()->reason->value)->toBe('complained'); +}); + +it('a edição vem do envio, nunca do webhook; envio desconhecido é ignorado', function (): void { + $other = Edition::factory()->create(); + + resendEvent($this, 'email.bounced', ['email_id' => 're_desconhecido', 'bounce' => ['type' => 'Permanent'], 'edition_id' => $other->id])->assertOk()->assertJsonPath('data.outcome', 'ignored'); + resendEvent($this, 'email.opened')->assertOk()->assertJsonPath('data.outcome', 'ignored'); + + expect(EmailSuppression::query()->withoutGlobalScopes()->count())->toBe(0) + ->and(EmailWebhookEvent::query()->count())->toBe(2); +}); + +it('envio que estava na fila não sai se o endereço for bloqueado antes', function (): void { + EmailSuppression::create(['edition_id' => $this->edition->id, 'email' => 'bia@exemplo.com', 'reason' => 'bounced']); + $queued = EmailDelivery::create(['edition_id' => $this->edition->id, 'template' => EmailTemplate::OrderConfirmed, 'to_email' => 'bia@exemplo.com', 'to_name' => 'Bia', 'variables' => [], 'status' => DeliveryStatus::Queued]); + + dispatch_sync(new SendEmailDelivery($this->edition->id, $queued->id)); + + expect($queued->fresh()->status)->toBe(DeliveryStatus::Suppressed); + Mail::assertNotSent(EditionMail::class, fn ($mail): bool => $mail->hasTo('bia@exemplo.com')); +}); diff --git a/backend/app-modules/ticketing/src/Http/Controllers/TicketTypeController.php b/backend/app-modules/ticketing/src/Http/Controllers/TicketTypeController.php index feba970..b9a9266 100644 --- a/backend/app-modules/ticketing/src/Http/Controllers/TicketTypeController.php +++ b/backend/app-modules/ticketing/src/Http/Controllers/TicketTypeController.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Gate; use PHPeste\Community\Enums\EditionPermission; use PHPeste\Community\Tenancy\CurrentEdition; +use PHPeste\Payments\Contracts\PaymentAccounts; use PHPeste\Ticketing\Actions\DeleteTicketBatch; use PHPeste\Ticketing\Actions\DeleteTicketType; use PHPeste\Ticketing\Actions\SaveTicketBatch; @@ -119,11 +120,13 @@ public function destroyBatch(Request $request, DeleteTicketBatch $delete): Respo } /** - * @return array + * @return array */ private function settings(TicketingSetting $settings): array { return [ + // Lote pago só vende com a conta do gateway pronta (chaves e webhook testados). + 'gateway_ready' => resolve(PaymentAccounts::class)->ready($settings->edition_id), 'capacity' => $settings->capacity, 'allocated' => $settings->allocated, 'remaining' => $settings->capacity === null ? null : max(0, $settings->capacity - $settings->allocated), diff --git a/backend/app-modules/ticketing/tests/Feature/TicketTypesTest.php b/backend/app-modules/ticketing/tests/Feature/TicketTypesTest.php index fd5364c..9285392 100644 --- a/backend/app-modules/ticketing/tests/Feature/TicketTypesTest.php +++ b/backend/app-modules/ticketing/tests/Feature/TicketTypesTest.php @@ -56,7 +56,8 @@ function createBatch(object $test, string $typeId, array $overrides = []): strin ->assertJsonPath('data.0.batches.0.price', ['amount' => 15_000, 'currency' => 'BRL']) ->assertJsonPath('data.0.batches.1.status', 'scheduled') ->assertJsonPath('data.0.batches.1.status_label', 'Agendado') - ->assertJsonPath('meta.capacity', null); + ->assertJsonPath('meta.capacity', null) + ->assertJsonPath('meta.gateway_ready', false); }); it('valida código de acesso, mínimo e máximo, janela e nome repetido', function (): void { diff --git a/backend/config/services.php b/backend/config/services.php index 03b1971..cf8026f 100644 --- a/backend/config/services.php +++ b/backend/config/services.php @@ -22,6 +22,8 @@ 'resend' => [ 'key' => env('RESEND_API_KEY'), + // Segredo de assinatura do webhook (whsec_...), em Resend → Webhooks. + 'webhook_secret' => env('RESEND_WEBHOOK_SECRET'), ], 'github' => [ diff --git a/docs/arquitetura/PHPeste_Arquitetura.pdf b/docs/arquitetura/PHPeste_Arquitetura.pdf index bc32369..d5e2798 100644 Binary files a/docs/arquitetura/PHPeste_Arquitetura.pdf and b/docs/arquitetura/PHPeste_Arquitetura.pdf differ diff --git a/docs/arquitetura/README.md b/docs/arquitetura/README.md index 94db2ec..6aed5f4 100644 --- a/docs/arquitetura/README.md +++ b/docs/arquitetura/README.md @@ -1,6 +1,6 @@ # Arquitetura da PHPeste Platform -**[PHPeste_Arquitetura.pdf](PHPeste_Arquitetura.pdf)** (18 páginas, A4 paisagem). O mesmo conteúdo, para abrir no navegador: [`fonte/arquitetura.html`](fonte/arquitetura.html). +**[PHPeste_Arquitetura.pdf](PHPeste_Arquitetura.pdf)** (19 páginas, A4 paisagem). O mesmo conteúdo, para abrir no navegador: [`fonte/arquitetura.html`](fonte/arquitetura.html). | Página | Conteúdo | |--------|----------| @@ -11,7 +11,7 @@ | 5 | Ciclo de vida da edição, transições, clonagem e Visão geral | | 6 | Os 15 módulos do backend | | 7 | Como os módulos conversam: contratos e pontos de extensão | -| 8 | Banco de dados por domínio (67 tabelas) | +| 8 | Banco de dados por domínio (69 tabelas) | | 9 | Papéis e permissões | | 10 | Ingresso: da compra ao QR | | 11 | CFP: da proposta à grade | @@ -21,9 +21,10 @@ | 15 | Desenvolvimento, CI e deploy | | 16 | Telas: o design do painel (`docs/design/`) | | 17 | Telas: o painel em uso (capturas do front-admin) | -| 18 | Onde estamos e o que falta | +| 18 | Telas: vendas e organização (cresce a cada tela do Marco 2) | +| 19 | Onde estamos e o que falta | -Retrato de 19/11/2026, com a B34 (tarefas). +Retrato de 19/11/2026, com a A14 (tela de ingressos). ## Como atualizar diff --git a/docs/arquitetura/fonte/arquitetura.html b/docs/arquitetura/fonte/arquitetura.html index 6e54207..a6b82ae 100644 --- a/docs/arquitetura/fonte/arquitetura.html +++ b/docs/arquitetura/fonte/arquitetura.html @@ -54,6 +54,8 @@ .shots { display: grid; gap: 5mm; width: 100%; height: 100%; align-items: start; } .two-shots { grid-template-columns: 1fr 1fr; } .mosaic { grid-template-columns: 1.05fr 1fr; grid-template-rows: 1fr 1fr; } +.sales { grid-template-columns: repeat(2, 1fr); } +.sales figure img { max-height: 140mm; } .mosaic .big { grid-row: span 2; } .mosaic figure:not(.big) img { max-height: 64mm; } figure { margin: 0; display: flex; flex-direction: column; gap: 1.5mm; min-height: 0; } @@ -83,7 +85,7 @@

Resumo em cinco pontos

Conteúdo

-
  1. Visão geral do sistema2
  2. Tenancy: comunidade, edição e o que é global3
  3. Como uma requisição encontra a edição4
  4. Ciclo de vida da edição5
  5. Os 15 módulos do backend6
  6. Como os módulos conversam7
  7. Banco de dados por domínio8
  8. Papéis e permissões9
  9. Ingresso: da compra ao QR10
  10. CFP: da proposta à grade11
  11. Dinheiro: patrocínio, fornecedores e finanças12
  12. Fila, rotinas agendadas, e-mail e auditoria13
  13. Segurança14
  14. Desenvolvimento, CI e deploy15
  15. Telas: design e painel16
  16. Telas: painel em uso17
  17. Onde estamos e o que falta18
+
  1. Visão geral do sistema2
  2. Tenancy: comunidade, edição e o que é global3
  3. Como uma requisição encontra a edição4
  4. Ciclo de vida da edição5
  5. Os 15 módulos do backend6
  6. Como os módulos conversam7
  7. Banco de dados por domínio8
  8. Papéis e permissões9
  9. Ingresso: da compra ao QR10
  10. CFP: da proposta à grade11
  11. Dinheiro: patrocínio, fornecedores e finanças12
  12. Fila, rotinas agendadas, e-mail e auditoria13
  13. Segurança14
  14. Desenvolvimento, CI e deploy15
  15. Telas: design e painel16
  16. Telas: painel em uso17
  17. Telas: vendas e organização18
  18. Onde estamos e o que falta19

Legenda usada nos diagramas

@@ -106,7 +108,7 @@

Conteúdo

chamada ou dependência assíncrono (evento, fila, webhook)
-
Fonte: código da main, backend/CLAUDE.md, docs/produto.md e ADRs 0001–0009.19/11/2026 · B34 (tarefas) · página 1
+
Fonte: código da main, backend/CLAUDE.md, docs/produto.md e ADRs 0001–0009.19/11/2026 · A14 (tela de ingressos) · página 1
@@ -183,7 +185,7 @@

Visão geral do sistema

MySQL 8 -um banco · 67 tabelas +um banco · 69 tabelas UUID em toda tabela Redis @@ -198,7 +200,7 @@

Visão geral do sistema

conta de cada edição (ADR 0009) Resend (e-mail) -Mailpit no dev +webhook de entrega · Mailpit no dev GitHub OAuth login de palestrante @@ -213,7 +215,7 @@

Visão geral do sistema

  • Painel e site são projetos separados (decisão: front-admin SPA, front-public SSR). O token é Bearer do Sanctum nos dois (ADR 0005).
  • Fila e agendador rodam a mesma imagem do backend (horizon e scheduler no infra/docker-compose.yml).
-
PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 2
+
PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 2
@@ -288,7 +290,7 @@

Tenancy: comunidade, edição e o que é global

community_id
  • Por que não um banco por comunidade: a mesma pessoa palestra no PHPeste de um ano e compra ingresso no outro, e o perfil dela é um só.
  • Dado de edição que vai para a próxima ("criar edição a partir da anterior") é copiado por um EditionCloner de cada módulo, nunca dado de pessoa.
-
PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 3
+
PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 3
@@ -336,7 +338,7 @@

Como uma requisição encontra a edição

Rotas públicas e de máquina /api/v1/public/resolve?host=… site descobre a edição pelo domínio /api/v1/public/editions/{id}/theme tema publicado com ETag -/api/v1/webhooks/payments/{token} assinatura do gateway +/api/v1/webhooks/payments/{token} e /webhooks/resend assinados /api/v1/sponsors/attachments/{id}/download URL assinada CORS: só a origem do site próprio da edição, só em /public/* @@ -356,7 +358,7 @@

Como uma requisição encontra a edição

O site chama /public/resolve com o host da requisição, recebe edition_id e o domínio principal e redireciona se for preciso (ADR 0008). O host é normalizado (minúsculas, sem porta, IDN em punycode) e nunca é usado para montar URL sem passar pela tabela edition_domains. -
PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 4
+
PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 4
@@ -422,13 +424,13 @@

Ciclo de vida da edição

palestrantes, patrocínio, fornecedores), pendências com caminho e filtro (propostas sem revisor, divergência na conciliação, entregas e despesas vencidas) e marcos. O Community filtra cada pendência pela permissão de quem vê: o voluntário não vê pendência de finanças. -
PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 5
+
PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 5
06 · Backend

Os 15 módulos do backend

-

Cada módulo é um pacote Composer real em backend/app-modules/<nome> (ADR 0002), com namespace PHPeste\<Nome>: Models, Actions, Contracts, Events, Http, Jobs. 257 rotas na API.

+

Cada módulo é um pacote Composer real em backend/app-modules/<nome> (ADR 0002), com namespace PHPeste\<Nome>: Models, Actions, Contracts, Events, Http, Jobs. 260 rotas na API.

Identity @@ -471,9 +473,9 @@

Os 15 módulos do backend

Notifications e-mail transacional por edição com modelos -editáveis, descadastro, Resend - -9 rotas +editáveis, descadastro, Resend com bounce e spam + +12 rotas Audit trilha append-only das ações sensíveis, com @@ -521,7 +523,7 @@

Os 15 módulos do backend

casca
-
PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 6
+
PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 6
@@ -587,13 +589,13 @@

Como os módulos conversam

EditionMailer::send(...): todo e-mail passa por aqui, com tema da edição
  • Ponto de extensão é registrado com $app->tag([...], Contrato::TAG): o Community não conhece os módulos, só a tag. Módulo novo aparece na Visão geral e na clonagem sem mexer no Community. O mesmo vale para TaskLinkProvider (Tasks): Suppliers e Sponsors registram o que uma tarefa pode apontar, e o Program vai registrar a sessão.
-
PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 7
+
PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 7
08 · Dados

Banco de dados por domínio

-

MySQL 8, 67 tabelas, todas com UUID como chave. Verde é da edição (tem edition_id); azul é global. ● em Suppliers: global da comunidade (community_id).

+

MySQL 8, 69 tabelas, todas com UUID como chave. Verde é da edição (tem edition_id); azul é global. ● em Suppliers: global da comunidade (community_id); em Notifications: global, a edição vem do envio.

Identity · 5 @@ -645,32 +647,34 @@

Banco de dados por domínio

payment_charges webhook_events payment_refunds - -Notifications · 3 + +Notifications · 5 email_templates email_deliveries email_unsubscribes +email_suppressions +email_webhook_events ● Audit · 1 audit_logs - -Sponsors · 8 -sponsor_settings -sponsor_tiers -sponsors -sponsorships -sponsorship_payments -sponsor_deliverables -sponsor_contacts -sponsor_attachments - -Suppliers · 6 -suppliers ● -supplier_contacts ● -edition_suppliers -supplier_quotes -supplier_attachments -supplier_activities + +Sponsors · 8 +sponsor_settings +sponsor_tiers +sponsors +sponsorships +sponsorship_payments +sponsor_deliverables +sponsor_contacts +sponsor_attachments + +Suppliers · 6 +suppliers ● +supplier_contacts ● +edition_suppliers +supplier_quotes +supplier_attachments +supplier_activities Finance · 2 finance_categories @@ -687,7 +691,7 @@

Banco de dados por domínio

cache · cache_locks sessions
  • Dinheiro sempre em centavos (inteiro). Dado sensível cifrado no banco: CPF de quem compra, credenciais do gateway, acessibilidade, corpo de webhook, linhas de importação. APP_PREVIOUS_KEYS + comandos *:reencrypt-* para trocar a chave.
  • Estoque e cupom nunca são lidos e depois gravados: UPDATE … WHERE allocated + q <= quantity. Testes com 12 processos simultâneos provam que não vende além do lote.
-
PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 8
+
PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 8
@@ -708,7 +712,7 @@

Como funciona

  • Palestrante e participante não têm papel: entram pelas rotas de edição publicada.
  • -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 9
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 9
    @@ -782,7 +786,7 @@

    Ingresso: da compra ao QR

    ticketing:expire-orders (1/min) devolve estoque de reserva vencida · ticketing:rotate-batches abre o próximo lote payments:retry-webhooks (1, 5, 15, 60 min) · ticketing:reconcile (diário) grava divergência com o gateway
    • Reembolso: PaymentLedger::refund reserva o valor antes de chamar o gateway (dois reembolsos ao mesmo tempo nunca passam do pago). Pedido importado de outra plataforma entra pago, sem cobrança, e não passa por reembolso nem conciliação.
    -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 10
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 10
    @@ -858,7 +862,7 @@

    CFP: da proposta à grade

    Configurar CFP (A10) · Avaliar propostas com teclado (A11) · Palestrantes: lista, cobertura e detalhe (A12) · no site público: formulário de proposta e área do palestrante com entrar pelo GitHub (P03, P11). -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 11
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 11
    @@ -911,7 +915,7 @@

    Dinheiro: patrocínio, fornecedores e finanças

    ADR 0009: a plataforma não recebe nem repassa dinheiro Cada edição cadastra a conta do próprio gateway; a API valida as chaves e um webhook assinado antes de abrir vendas. Credenciais cifradas; a API só mostra os 4 últimos caracteres. -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 12
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 12
    @@ -932,14 +936,15 @@

    E-mail (Notifications)

  • Todo e-mail sai por EditionMailer::send: registra em email_deliveries e enfileira com 5 tentativas.
  • Modelo editável por edição, variáveis {nome} sem Blade, HTML escapado, layout com o tema publicado.
  • Não transacional leva descadastro com link assinado e List-Unsubscribe.
  • +
  • Webhook do Resend (assinatura Svix): entregue, bounce e spam. Bounce permanente ou spam bloqueia o endereço na edição, até para transacional, até a organização liberar.
  • Auditoria

      -
    • Evento que implementa Auditable vira linha em audit_logs pelo listener genérico. 21 eventos hoje.
    • +
    • Evento que implementa Auditable vira linha em audit_logs pelo listener genérico. 22 eventos hoje.
    • Segredo removido, dado pessoal mascarado; o model recusa update e delete.
    -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 13
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 13
    @@ -949,7 +954,7 @@

    Segurança

    TemaComo está
    AutenticaçãoSanctum Bearer, um token por dispositivo com expiração (SANCTUM_EXPIRATION_MINUTES); revogar é imediato. Senha mínima de 10 e checagem de vazamento.
    IsolamentoEscopo global por edição; outra comunidade recebe 404; arch test impede módulo de depender de App\ e controller de usar $request->all().
    Rate limitLimiters nomeados: login, password-reset, checkout, webhooks, configuráveis por .env.
    Headers e CORSCSP, HSTS, nosniff, Referrer-Policy, Permissions-Policy. CORS por ambiente e, em /public/*, só a origem do site próprio da edição.
    Dados sensíveisCifrados no banco (CPF, credenciais, acessibilidade, webhooks). Logs JSON com password, token, secret e cartão redigidos automaticamente.
    ArquivosDisco privado; download só por URL assinada que expira (10 min), sempre como anexo, com nosniff e CSP sandbox. SVG sanitizado.
    PagamentoSem dado de cartão na API; webhook com assinatura do driver e reconsulta ao gateway; idempotência no banco (unique(edition_id, idempotency_key)).
    SegredosADR 0006: nada de segredo no repositório; APP_PREVIOUS_KEYS para trocar a chave sem perder o que já foi cifrado.
    LGPDEncarregado e política por edição, anonimização após o evento (B43 em aberto). Decisão em aberto: comunidade controladora, PHPeste operador.
    -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 14
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 14
    @@ -1024,7 +1029,7 @@

    Desenvolvimento, CI e deploy

    Em aberto para o evento teste de carga, backups, runbook do dia do evento (B45) · dados de demonstração e documentação publicada (B46) -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 15
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 15
    @@ -1037,7 +1042,7 @@

    Telas: o design do painel

    Tokens do tema Sertão
    Design: tokens do tema Sertão
    -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 16
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 16
    @@ -1051,16 +1056,26 @@

    Telas: o painel em uso

    Login
    Entrar com e-mail e senha ou GitHub
    -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 17
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 17
    -
    18 · Roadmap
    +
    18 · Telas
    +

    Telas: vendas e organização

    +

    As telas do Marco 2 conforme ficam prontas. Mesma fonte dos outros prints: o painel rodando com a API simulada.

    +
    +
    Ingressos: tipos e lotes com o preço, o que a edição recebe depois da taxa do gateway, vendidos e situação. Cupons e regras da venda nas outras abas.
    + +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 18
    +
    +
    +
    +
    19 · Roadmap

    Onde estamos e o que falta

    Os milestones do GitHub e o board PHPeste Platform são a fonte da verdade do andamento; esta página é o retrato no dia da geração.

    -
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPBackend concluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosBackend concluídoingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas; faltam as telas A14–A23 e P04–P06
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37), check-in com modo offline (B38–B39), push (B40), API pública e checkout embutível (B41), site da edição (P02, P07–P09)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    +
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPBackend concluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosBackend concluído, telas em andamentobackend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas prontas: A14 (ingressos); faltam A15–A23 e P04–P06
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37), check-in com modo offline (B38–B39), push (B40), API pública e checkout embutível (B41), site da edição (P02, P07–P09)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    -
    PHPeste Platform · Arquitetura19/11/2026 · B34 (tarefas) · página 18
    +
    PHPeste Platform · Arquitetura19/11/2026 · A14 (tela de ingressos) · página 19
    diff --git a/docs/arquitetura/fonte/gerar.py b/docs/arquitetura/fonte/gerar.py index 7ce223d..c74d969 100644 --- a/docs/arquitetura/fonte/gerar.py +++ b/docs/arquitetura/fonte/gerar.py @@ -13,7 +13,7 @@ from pathlib import Path OUT = Path(__file__).with_name("arquitetura.html") -RETRATO = "19/11/2026 · B34 (tarefas)" +RETRATO = "19/11/2026 · A14 (tela de ingressos)" # ---------------------------------------------------------------- estilo --- # Cores do tema Sertão (front-admin) para o que é da plataforma, e neutras @@ -134,7 +134,7 @@ def legend(): "Ciclo de vida da edição", "Os 15 módulos do backend", "Como os módulos conversam", "Banco de dados por domínio", "Papéis e permissões", "Ingresso: da compra ao QR", "CFP: da proposta à grade", "Dinheiro: patrocínio, fornecedores e finanças", "Fila, rotinas agendadas, e-mail e auditoria", "Segurança", "Desenvolvimento, CI e deploy", "Telas: design e painel", - "Telas: painel em uso", "Onde estamos e o que falta", + "Telas: painel em uso", "Telas: vendas e organização", "Onde estamos e o que falta", ] pages.append(f"""
    @@ -186,11 +186,11 @@ def legend(): b.append(box(445, 394, 350, 122, "Regras que valem para todo módulo", ["Tenancy por edição (BelongsToEdition)", "Mutação só em Action · validação em FormRequest", "Módulo não usa model de outro (arch test)", "Ação sensível → evento Auditable", "Logs JSON com segredo redigido · Sentry opcional"], "backend", size=9.5)) b.append(arrow([(395, 275), (430, 275)], "infra")) -b.append(box(845, 40, 245, 70, "MySQL 8", ["um banco · 67 tabelas", "UUID em toda tabela"], "data")) +b.append(box(845, 40, 245, 70, "MySQL 8", ["um banco · 69 tabelas", "UUID em toda tabela"], "data")) b.append(box(845, 122, 245, 70, "Redis", ["cache, filas, locks,", "rate limit"], "data")) b.append(box(845, 204, 245, 70, "Disco privado", ["CSV de importação, anexos,", "comprovantes (URL assinada)"], "data")) b.append(box(845, 292, 245, 56, "Asaas · Mercado Pago", ["conta de cada edição (ADR 0009)"], "external")) -b.append(box(845, 360, 245, 50, "Resend (e-mail)", ["Mailpit no dev"], "external")) +b.append(box(845, 360, 245, 50, "Resend (e-mail)", ["webhook de entrega · Mailpit no dev"], "external")) b.append(box(845, 422, 245, 50, "GitHub OAuth", ["login de palestrante"], "external")) b.append(box(845, 484, 245, 46, "Sentry", ["opcional, sem DSN fica desligado"], "external")) for y in (75, 157, 239): @@ -244,7 +244,7 @@ def legend(): if i < len(steps) - 1: b.append(arrow([(x + 168, 71), (x + 182, 71)], "backend")) b.append(box(10, 140, 530, 140, "Rotas de quem não é da equipe", ["Route::apiV1PublishedEdition('speaker', 'proposals', ['auth:sanctum'])", "→ /api/v1/speaker/editions/{edition}/proposals", "só aceita edição publicada (rascunho = 404) e liga a edição no contexto", "sem exigir papel. Usado por palestrante, participante e checkout.", "A posse do dado é conferida na Action (a proposta é dela?)."], "edition", size=9.8)) -b.append(box(560, 140, 530, 140, "Rotas públicas e de máquina", ["/api/v1/public/resolve?host=… site descobre a edição pelo domínio", "/api/v1/public/editions/{id}/theme tema publicado com ETag", "/api/v1/webhooks/payments/{token} assinatura do gateway", "/api/v1/sponsors/attachments/{id}/download URL assinada", "CORS: só a origem do site próprio da edição, só em /public/*"], "infra", size=9.8)) +b.append(box(560, 140, 530, 140, "Rotas públicas e de máquina", ["/api/v1/public/resolve?host=… site descobre a edição pelo domínio", "/api/v1/public/editions/{id}/theme tema publicado com ETag", "/api/v1/webhooks/payments/{token} e /webhooks/resend assinados", "/api/v1/sponsors/attachments/{id}/download URL assinada", "CORS: só a origem do site próprio da edição, só em /public/*"], "infra", size=9.8)) b.append(box(10, 305, 530, 120, "Job e listener", ["recebem edition_id explícito no construtor e rodam dentro de", "resolve(CurrentEdition::class)->run($editionId, fn () => …)", "nunca herdam a edição de quem disparou: a fila roda depois,", "em outro processo, e a edição do contexto já não existe."], "backend", size=9.8)) b.append(box(560, 305, 530, 120, "Evento de domínio", ["carrega ids e enums, nunca Model de outro módulo", "ex.: EditionStatusChanged(editionId, from, to)", "ShouldDispatchAfterCommit: só sai se a transação gravou", "evento Auditable vira registro em audit_logs"], "backend", size=9.8)) b.append(box(10, 450, 1080, 80, "Front-public: a edição vem do host", ["O site chama /public/resolve com o host da requisição, recebe edition_id e o domínio principal e redireciona se for preciso (ADR 0008).", "O host é normalizado (minúsculas, sem porta, IDN em punycode) e nunca é usado para montar URL sem passar pela tabela edition_domains."], "client", size=9.8)) @@ -283,7 +283,7 @@ def legend(): ("Cfp", "chamada, trilhas, critérios, propostas, avaliação cega, decisão, cota do Nordeste, confirmação", 52, "backend"), ("Ticketing", "tipos, lotes, cupons, pedidos, estoque atômico, ingressos com QR, transferência, importação, conciliação", 50, "backend"), ("Payments", "contas de gateway por edição, drivers Asaas e Mercado Pago, cobranças, webhooks, reembolsos", 8, "backend"), - ("Notifications", "e-mail transacional por edição com modelos editáveis, descadastro, Resend", 9, "backend"), + ("Notifications", "e-mail transacional por edição com modelos editáveis, descadastro, Resend com bounce e spam", 12, "backend"), ("Audit", "trilha append-only das ações sensíveis, com redação de segredos", 1, "backend"), ("Sponsors", "cotas, funil, vagas, pagamentos, entregas, anexos por URL assinada", 28, "backend"), ("Suppliers", "cadastro da comunidade, orçamentos, contratação, anexos, reaproveitamento", 19, "backend"), @@ -307,7 +307,7 @@ def legend(): lines.append(cur) b.append(box(x, y, 350, 94, name, lines[:3], kind, dashed=kind == "todo", badge=(f"{routes} rotas", "backend") if routes else ("casca", "todo"), size=9.8)) pages.append(page(6, "Backend", "Os 15 módulos do backend", - "Cada módulo é um pacote Composer real em backend/app-modules/<nome> (ADR 0002), com namespace PHPeste\\<Nome>: Models, Actions, Contracts, Events, Http, Jobs. 257 rotas na API.", + "Cada módulo é um pacote Composer real em backend/app-modules/<nome> (ADR 0002), com namespace PHPeste\\<Nome>: Models, Actions, Contracts, Events, Http, Jobs. 260 rotas na API.", svg("\n".join(b), h=545))) # ================================================= 7 como conversam @@ -341,7 +341,7 @@ def legend(): ("Cfp", ["cfp_settings", "cfp_tracks", "cfp_criteria", "proposals", "proposal_speakers", "review_assignments", "reviews", "review_scores", "speaker_confirmations", "speaker_logistics"], "edition"), ("Ticketing", ["ticketing_settings", "ticket_types", "ticket_batches", "coupons", "coupon_redemptions", "orders", "order_items", "tickets", "ticket_transfers", "reconciliation_issues", "ticket_imports", "ticket_import_rejections"], "edition"), ("Payments", ["payment_accounts", "payment_charges", "webhook_events", "payment_refunds"], "edition"), - ("Notifications", ["email_templates", "email_deliveries", "email_unsubscribes"], "edition"), + ("Notifications", ["email_templates", "email_deliveries", "email_unsubscribes", "email_suppressions", "email_webhook_events ●"], "edition"), ("Audit", ["audit_logs"], "infra"), ("Sponsors", ["sponsor_settings", "sponsor_tiers", "sponsors", "sponsorships", "sponsorship_payments", "sponsor_deliverables", "sponsor_contacts", "sponsor_attachments"], "edition"), ("Suppliers", ["suppliers ●", "supplier_contacts ●", "edition_suppliers", "supplier_quotes", "supplier_attachments", "supplier_activities"], "edition"), @@ -359,7 +359,7 @@ def legend(): b.append(box(cols[col], 12 + heights[col], 260, h, f"{name} · {count}", tables, kind, mono=True, size=9.5, line_h=14)) heights[col] += h + 12 pages.append(page(8, "Dados", "Banco de dados por domínio", - "MySQL 8, 67 tabelas, todas com UUID como chave. Verde é da edição (tem edition_id); azul é global. ● em Suppliers: global da comunidade (community_id).", + "MySQL 8, 69 tabelas, todas com UUID como chave. Verde é da edição (tem edition_id); azul é global. ● em Suppliers: global da comunidade (community_id); em Notifications: global, a edição vem do envio.", svg("\n".join(b), h=max(heights) + 20), ["Dinheiro sempre em centavos (inteiro). Dado sensível cifrado no banco: CPF de quem compra, credenciais do gateway, acessibilidade, corpo de webhook, linhas de importação. APP_PREVIOUS_KEYS + comandos *:reencrypt-* para trocar a chave.", "Estoque e cupom nunca são lidos e depois gravados: UPDATE … WHERE allocated + q <= quantity. Testes com 12 processos simultâneos provam que não vende além do lote."])) @@ -493,10 +493,11 @@ def legend():
  • Todo e-mail sai por EditionMailer::send: registra em email_deliveries e enfileira com 5 tentativas.
  • Modelo editável por edição, variáveis {nome} sem Blade, HTML escapado, layout com o tema publicado.
  • Não transacional leva descadastro com link assinado e List-Unsubscribe.
  • +
  • Webhook do Resend (assinatura Svix): entregue, bounce e spam. Bounce permanente ou spam bloqueia o endereço na edição, até para transacional, até a organização liberar.
  • Auditoria

      -
    • Evento que implementa Auditable vira linha em audit_logs pelo listener genérico. 21 eventos hoje.
    • +
    • Evento que implementa Auditable vira linha em audit_logs pelo listener genérico. 22 eventos hoje.
    • Segredo removido, dado pessoal mascarado; o model recusa update e delete.
    """ pages.append(page(13, "Operação", "Fila, rotinas agendadas, e-mail e auditoria", "O que roda sem ninguém clicar. Todas as rotinas usam withoutOverlapping() e são idempotentes: rodar duas vezes não muda o resultado.", content)) @@ -556,15 +557,24 @@ def legend():
    Login
    Entrar com e-mail e senha ou GitHub
    """)) -# ================================================== 18 status +# ================================================== 18 telas de vendas +# Cada tela do Marco 2 que fica pronta entra aqui (prints de front-admin/e2e/capturas-arquitetura.spec.ts). +SALES_SCREENS = [ + ("painel-ingressos.png", "Ingressos: tipos e lotes com o preço, o que a edição recebe depois da taxa do gateway, vendidos e situação. Cupons e regras da venda nas outras abas."), +] +pages.append(page(18, "Telas", "Telas: vendas e organização", + "As telas do Marco 2 conforme ficam prontas. Mesma fonte dos outros prints: o painel rodando com a API simulada.", + '
    ' + "".join(f'
    {escape(caption)}
    ' for img, caption in SALES_SCREENS) + "
    ")) + +# ================================================== 19 status status = [ ("Marco 0 · Fundação", "Concluído", "esqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes"), ("Marco 1 · Núcleo e CFP", "Backend concluído", "Identity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03"), - ("Marco 2 · Ingressos", "Backend concluído", "ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas; faltam as telas A14–A23 e P04–P06"), + ("Marco 2 · Ingressos", "Backend concluído, telas em andamento", "backend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas prontas: A14 (ingressos); faltam A15–A23 e P04–P06"), ("Marco 3 · Evento pronto", "A fazer", "grade e programação (B35–B37), check-in com modo offline (B38–B39), push (B40), API pública e checkout embutível (B41), site da edição (P02, P07–P09)"), ("Marco 4 · Operação", "A fazer", "engajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)"), ] -pages.append(page(18, "Roadmap", "Onde estamos e o que falta", +pages.append(page(19, "Roadmap", "Onde estamos e o que falta", "Os milestones do GitHub e o board PHPeste Platform são a fonte da verdade do andamento; esta página é o retrato no dia da geração.", table(["Marco", "Situação", "O que tem"], [(f"{a}", b_, c) for a, b_, c in status], "cmp roadmap"))) @@ -622,6 +632,8 @@ def legend(): .shots { display: grid; gap: 5mm; width: 100%; height: 100%; align-items: start; } .two-shots { grid-template-columns: 1fr 1fr; } .mosaic { grid-template-columns: 1.05fr 1fr; grid-template-rows: 1fr 1fr; } +.sales { grid-template-columns: repeat(2, 1fr); } +.sales figure img { max-height: 140mm; } .mosaic .big { grid-row: span 2; } .mosaic figure:not(.big) img { max-height: 64mm; } figure { margin: 0; display: flex; flex-direction: column; gap: 1.5mm; min-height: 0; } diff --git a/docs/arquitetura/telas/painel-ingressos.png b/docs/arquitetura/telas/painel-ingressos.png new file mode 100644 index 0000000..60aa97e Binary files /dev/null and b/docs/arquitetura/telas/painel-ingressos.png differ diff --git a/front-admin/CLAUDE.md b/front-admin/CLAUDE.md index 621fa5c..4ef71fc 100644 --- a/front-admin/CLAUDE.md +++ b/front-admin/CLAUDE.md @@ -51,6 +51,7 @@ app/ cfp/avaliacao.vue # módulo cfpReview: fila do revisor com atalhos, quadro e atribuição da organização palestrantes/index.vue # módulo speakers: confirmações, cobertura dos nove estados e lista de espera palestrantes/[id].vue # módulo speakers: perfil, palestras, viagem e hospedagem e confirmação + ingressos/index.vue # módulo tickets: tipos e lotes com valor líquido e prévia do checkout, cupons e regras da venda configuracoes.vue # módulo editionSettings: dados e etapa da edição, domínio e site próprio, privacidade e auditoria meu-perfil.vue # módulo myProfile: conta, senha, sessões ativas e notificações index.vue diff --git a/front-admin/app/application/locales/pt-br/index.ts b/front-admin/app/application/locales/pt-br/index.ts index 1441197..ab59528 100644 --- a/front-admin/app/application/locales/pt-br/index.ts +++ b/front-admin/app/application/locales/pt-br/index.ts @@ -8,6 +8,7 @@ import overview from '../../../modules/overview/locales/pt-br' import identity from '../../../modules/identity/locales/pt-br' import team from '../../../modules/team/locales/pt-br' import cfpSettings from '../../../modules/cfpSettings/locales/pt-br' +import tickets from '../../../modules/tickets/locales/pt-br' import cfpReview from '../../../modules/cfpReview/locales/pt-br' import speakers from '../../../modules/speakers/locales/pt-br' import editionSettings from '../../../modules/editionSettings/locales/pt-br' @@ -28,6 +29,7 @@ export default { identity, team, cfpSettings, + tickets, cfpReview, speakers, editionSettings, diff --git a/front-admin/app/modules/tickets/components/BatchModal.vue b/front-admin/app/modules/tickets/components/BatchModal.vue new file mode 100644 index 0000000..9d591a6 --- /dev/null +++ b/front-admin/app/modules/tickets/components/BatchModal.vue @@ -0,0 +1,98 @@ + + + diff --git a/front-admin/app/modules/tickets/components/CouponModal.vue b/front-admin/app/modules/tickets/components/CouponModal.vue new file mode 100644 index 0000000..49066c1 --- /dev/null +++ b/front-admin/app/modules/tickets/components/CouponModal.vue @@ -0,0 +1,133 @@ + + + diff --git a/front-admin/app/modules/tickets/components/CouponsTab.vue b/front-admin/app/modules/tickets/components/CouponsTab.vue new file mode 100644 index 0000000..6fbc2b3 --- /dev/null +++ b/front-admin/app/modules/tickets/components/CouponsTab.vue @@ -0,0 +1,89 @@ + + + diff --git a/front-admin/app/modules/tickets/components/SalesSettingsTab.vue b/front-admin/app/modules/tickets/components/SalesSettingsTab.vue new file mode 100644 index 0000000..a626b8c --- /dev/null +++ b/front-admin/app/modules/tickets/components/SalesSettingsTab.vue @@ -0,0 +1,59 @@ + + + diff --git a/front-admin/app/modules/tickets/components/TicketCardPreview.vue b/front-admin/app/modules/tickets/components/TicketCardPreview.vue new file mode 100644 index 0000000..863309e --- /dev/null +++ b/front-admin/app/modules/tickets/components/TicketCardPreview.vue @@ -0,0 +1,46 @@ + + + diff --git a/front-admin/app/modules/tickets/components/TicketTypeModal.vue b/front-admin/app/modules/tickets/components/TicketTypeModal.vue new file mode 100644 index 0000000..b835faf --- /dev/null +++ b/front-admin/app/modules/tickets/components/TicketTypeModal.vue @@ -0,0 +1,157 @@ + + + diff --git a/front-admin/app/modules/tickets/components/TicketTypesTab.vue b/front-admin/app/modules/tickets/components/TicketTypesTab.vue new file mode 100644 index 0000000..ebc4031 --- /dev/null +++ b/front-admin/app/modules/tickets/components/TicketTypesTab.vue @@ -0,0 +1,163 @@ + + + diff --git a/front-admin/app/modules/tickets/components/TicketsComponents.test.ts b/front-admin/app/modules/tickets/components/TicketsComponents.test.ts new file mode 100644 index 0000000..e2b355a --- /dev/null +++ b/front-admin/app/modules/tickets/components/TicketsComponents.test.ts @@ -0,0 +1,37 @@ +import { mountSuspended } from '@nuxt/test-utils/runtime' +import { describe, expect, it } from 'vitest' +import BatchModal from './BatchModal.vue' +import TicketCardPreview from './TicketCardPreview.vue' +import type { Batch, TicketType } from '../types' + +const batch: Batch = { id: 'b-1', ticketTypeId: 'tt-1', name: '1º lote', position: 0, priceCents: 15000, quantity: 100, sold: 12, remaining: 88, startsAt: null, endsAt: null, onSellOut: 'next', status: 'on_sale', statusLabel: 'À venda' } +const type: TicketType = { id: 'tt-1', name: 'Inteira', description: '', visibility: 'public', visibilityLabel: 'Qualquer pessoa', accessCode: '', minPerOrder: 1, maxPerOrder: 10, showRemaining: true, passFeeToBuyer: false, questions: [], position: 0, sold: 12, quantity: 100, currentBatchId: 'b-1', batches: [batch] } + +describe('TicketCardPreview', () => { + it('mostra o ingresso como no checkout, com a taxa repassada e quantos restam', async () => { + const wrapper = await mountSuspended(TicketCardPreview, { props: { name: 'Inteira', description: 'Acesso aos dois dias', visibility: 'code', showRemaining: true, passFeeToBuyer: true, feeBasisPoints: 499, batch } }) + const text = wrapper.text() + + expect(text).toContain('Inteira') + expect(text).toContain('Acesso aos dois dias') + expect(text).toContain('R$ 157,49') + expect(text).toContain('+ R$ 7,49 de taxa') + expect(text).toContain('Restam 88') + expect(text).toContain('Só com código') + }) +}) + +describe('BatchModal', () => { + it('calcula o valor líquido ao vivo e avisa que pedidos existentes não mudam ao trocar o preço', async () => { + const wrapper = await mountSuspended(BatchModal, { props: { modelValue: false, type, batch, feeBasisPoints: 499, save: async () => ({ ok: true }) } }) + await wrapper.setProps({ modelValue: true }) + + expect(wrapper.find('[data-testid="net-calculation"]').text()).toContain('R$ 142,51') + expect(wrapper.find('[data-testid="price-change-warning"]').exists()).toBe(false) + + await wrapper.find('#batch-price').setValue('170,00') + + expect(wrapper.find('[data-testid="net-calculation"]').text()).toContain('R$ 161,51') + expect(wrapper.find('[data-testid="price-change-warning"]').text()).toContain('12 ingressos vendidos ou reservados') + }) +}) diff --git a/front-admin/app/modules/tickets/components/TicketsPanel.vue b/front-admin/app/modules/tickets/components/TicketsPanel.vue new file mode 100644 index 0000000..915a724 --- /dev/null +++ b/front-admin/app/modules/tickets/components/TicketsPanel.vue @@ -0,0 +1,71 @@ + + + diff --git a/front-admin/app/modules/tickets/composables/money.test.ts b/front-admin/app/modules/tickets/composables/money.test.ts new file mode 100644 index 0000000..74ff9c4 --- /dev/null +++ b/front-admin/app/modules/tickets/composables/money.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { centsToInput, feeFor, formatCents, netFor, parseReais } from './money' + +describe('money', () => { + it('formata em reais com separador de milhar', () => { + expect(formatCents(123456)).toBe('R$ 1.234,56') + expect(centsToInput(15000)).toBe('150,00') + }) + + it('lê o valor digitado em reais', () => { + expect(parseReais('150')).toBe(15000) + expect(parseReais('150,5')).toBe(15050) + expect(parseReais('1.234,56')).toBe(123456) + expect(parseReais('R$ 0,99')).toBe(99) + expect(parseReais('0')).toBe(0) + expect(parseReais('')).toBeNull() + expect(parseReais('15,999')).toBeNull() + expect(parseReais('abc')).toBeNull() + }) + + it('calcula a taxa como o backend (arredonda para cima) e o líquido', () => { + expect(feeFor(15000, 499)).toBe(749) + expect(feeFor(0, 499)).toBe(0) + expect(netFor(15000, 499, false)).toEqual({ buyerPays: 15000, fee: 749, received: 14251 }) + expect(netFor(15000, 499, true)).toEqual({ buyerPays: 15749, fee: 749, received: 15000 }) + }) +}) diff --git a/front-admin/app/modules/tickets/composables/money.ts b/front-admin/app/modules/tickets/composables/money.ts new file mode 100644 index 0000000..5dc8e11 --- /dev/null +++ b/front-admin/app/modules/tickets/composables/money.ts @@ -0,0 +1,44 @@ +const brl = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }) + +/** 15000 → "R$ 150,00" (com separador de milhar). */ +export const formatCents = (cents: number) => brl.format(cents / 100) + +/** "1.234,56", "1234,5", "150" ou "R$ 150,00" → centavos. Texto inválido → null. */ +export function parseReais(text: string): number | null { + const clean = text.replace(/R\$|\s/g, '').trim() + if (clean === '') return null + if (!/^\d{1,3}(\.\d{3})*(,\d{1,2})?$|^\d+(,\d{1,2})?$/.test(clean)) return null + const [integer = '0', decimals = ''] = clean.replace(/\./g, '').split(',') + return Number(integer) * 100 + Number(decimals.padEnd(2, '0')) +} + +/** Centavos → "1.234,56" para o campo de edição. */ +export const centsToInput = (cents: number) => new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(cents / 100) + +/** Mesma conta do backend (`Split::fee`): arredonda a taxa para cima. */ +export const feeFor = (cents: number, basisPoints: number) => (basisPoints === 0 || cents === 0 ? 0 : Math.ceil((cents * basisPoints) / 10_000)) + +/** + * Quanto quem compra paga e quanto a edição recebe por ingresso. + * Com a taxa repassada, ela soma ao preço; senão, sai do que a edição recebe. + */ +export function netFor(cents: number, basisPoints: number, passFeeToBuyer: boolean) { + const fee = feeFor(cents, basisPoints) + return passFeeToBuyer ? { buyerPays: cents + fee, fee, received: cents } : { buyerPays: cents, fee, received: cents - fee } +} + +/** ISO (UTC) → valor de `` no fuso do navegador. */ +export function isoToLocal(iso: string | null): string { + if (!iso) return '' + const date = new Date(iso) + const pad = (n: number) => String(n).padStart(2, '0') + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}` +} + +/** Valor do `datetime-local` → ISO (UTC); vazio → null. */ +export const localToIso = (local: string) => (local ? new Date(local).toISOString() : null) + +const dateTime = new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }) + +/** "10 de jun., 09:00" para listas. */ +export const formatDateTime = (iso: string | null) => (iso ? dateTime.format(new Date(iso)) : null) diff --git a/front-admin/app/modules/tickets/composables/useTickets.test.ts b/front-admin/app/modules/tickets/composables/useTickets.test.ts new file mode 100644 index 0000000..c6066ff --- /dev/null +++ b/front-admin/app/modules/tickets/composables/useTickets.test.ts @@ -0,0 +1,100 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ticketsService from '../services/ticketsService' +import { TicketsError } from '../services/ticketsError' +import { useTickets } from './useTickets' + +vi.mock('../services/ticketsService', () => ({ + default: { types: vi.fn(), createType: vi.fn(), updateType: vi.fn(), deleteType: vi.fn(), createBatch: vi.fn(), updateBatch: vi.fn(), closeBatch: vi.fn(), deleteBatch: vi.fn(), updateSettings: vi.fn(), coupons: vi.fn(), createCoupon: vi.fn(), updateCoupon: vi.fn(), deleteCoupon: vi.fn() }, +})) + +const batch = (overrides: Record = {}) => ({ + id: 'b-1', ticket_type_id: 'tt-1', name: '1º lote', position: 0, price: { amount: 15000, currency: 'BRL' }, quantity: 100, allocated: 12, remaining: 88, + starts_at: null, ends_at: '2027-05-01T02:59:59Z', on_sell_out: 'next', status: 'on_sale', status_label: 'À venda', ...overrides, +}) +const typesPayload = (gatewayReady = false, batches = [batch()]) => ({ + data: [{ + id: 'tt-1', name: 'Inteira', description: null, visibility: 'public', visibility_label: 'Qualquer pessoa', access_code: null, min_per_order: 1, max_per_order: 10, + show_remaining: true, pass_fee_to_buyer: false, questions: [{ label: 'Camiseta', type: 'select', required: true, options: ['P', 'M'] }], position: 0, allocated: 12, quantity: 100, current_batch_id: 'b-1', batches, + }], + meta: { gateway_ready: gatewayReady, capacity: 400, allocated: 12, remaining: 388, reservation_minutes: 30, max_tickets_per_buyer: null, gateway_fee_basis_points: 499 }, +}) +const coupons = { data: [{ id: 'c-1', code: 'COMUNIDADE', description: null, kind: 'percent', kind_label: 'Percentual', value: 20, max_uses: 50, used: 3, remaining: 47, starts_at: null, ends_at: null, ticket_type_ids: [], active: true, status: 'active', discount_total: { amount: 9000, currency: 'BRL' } }] } + +beforeEach(() => { + vi.clearAllMocks() + vi.mocked(ticketsService.types).mockResolvedValue(typesPayload() as never) + vi.mocked(ticketsService.coupons).mockResolvedValue(coupons as never) +}) + +describe('useTickets', () => { + it('carrega tipos com lotes em centavos, regras e cupons', async () => { + const tickets = useTickets('ed-1') + await tickets.load() + + expect(tickets.state.value).toBe('ready') + expect(tickets.types.value[0]).toMatchObject({ name: 'Inteira', sold: 12, quantity: 100, description: '', questions: [{ label: 'Camiseta', type: 'select', required: true, options: ['P', 'M'] }] }) + expect(tickets.types.value[0]!.batches[0]).toMatchObject({ priceCents: 15000, sold: 12, remaining: 88, status: 'on_sale' }) + expect(tickets.settings.value).toEqual({ gatewayReady: false, capacity: 400, sold: 12, remaining: 388, reservationMinutes: 30, maxTicketsPerBuyer: null, feeBasisPoints: 499 }) + expect(tickets.coupons.value[0]).toMatchObject({ code: 'COMUNIDADE', discountTotalCents: 9000 }) + }) + + it('vendas ficam pausadas só com lote pago ativo e gateway não validado', async () => { + const tickets = useTickets('ed-1') + await tickets.load() + expect(tickets.salesPaused.value).toBe(true) + + vi.mocked(ticketsService.types).mockResolvedValueOnce(typesPayload(true) as never) + await tickets.load() + expect(tickets.salesPaused.value).toBe(false) + + vi.mocked(ticketsService.types).mockResolvedValueOnce(typesPayload(false, [batch({ price: { amount: 0, currency: 'BRL' } })]) as never) + await tickets.load() + expect(tickets.salesPaused.value).toBe(false) + }) + + it('manda o lote em centavos e o período em UTC, e recarrega', async () => { + const tickets = useTickets('ed-1') + await tickets.load() + vi.mocked(ticketsService.updateBatch).mockResolvedValueOnce({ data: {} } as never) + + const result = await tickets.saveBatch(tickets.types.value[0]!, tickets.types.value[0]!.batches[0]!, { name: ' 1º lote ', priceCents: 17000, quantity: 120, startsAt: '', endsAt: '2027-04-30T23:59', onSellOut: 'close' }) + + expect(result).toEqual({ ok: true }) + expect(ticketsService.updateBatch).toHaveBeenCalledWith('ed-1', 'tt-1', 'b-1', expect.objectContaining({ name: '1º lote', price_cents: 17000, quantity: 120, starts_at: null, on_sell_out: 'close' })) + expect(vi.mocked(ticketsService.updateBatch).mock.calls[0]![3].ends_at).toMatch(/Z$/) + expect(ticketsService.types).toHaveBeenCalledTimes(2) + }) + + it('só manda o código de acesso quando a visibilidade pede e as opções só em pergunta de lista', async () => { + const tickets = useTickets('ed-1') + await tickets.load() + vi.mocked(ticketsService.createType).mockResolvedValueOnce({ data: {} } as never) + + await tickets.saveType(null, { name: 'VIP', description: '', visibility: 'public', accessCode: 'ESQUECIDO', minPerOrder: 1, maxPerOrder: 2, showRemaining: false, passFeeToBuyer: true, questions: [{ label: 'Empresa ', type: 'text', required: false, options: ['x'] }, { label: 'Camiseta', type: 'select', required: true, options: [' P', '', 'M '] }] }) + + expect(ticketsService.createType).toHaveBeenCalledWith('ed-1', expect.objectContaining({ + access_code: null, + description: null, + pass_fee_to_buyer: true, + questions: [{ label: 'Empresa', type: 'text', required: false }, { label: 'Camiseta', type: 'select', required: true, options: ['P', 'M'] }], + })) + }) + + it('não troca o código de cupom já usado e traduz erro de validação para o campo', async () => { + const tickets = useTickets('ed-1') + await tickets.load() + vi.mocked(ticketsService.updateCoupon).mockRejectedValueOnce(new TicketsError('x', 422, { value: ['O campo valor não pode ser superior a 100.'] })) + + const result = await tickets.saveCoupon(tickets.coupons.value[0]!, { code: 'OUTRO', description: '', kind: 'percent', value: 120, maxUses: null, startsAt: '', endsAt: '', ticketTypeIds: [], active: true }) + + expect(vi.mocked(ticketsService.updateCoupon).mock.calls[0]![2]).not.toHaveProperty('code') + expect(result).toEqual({ ok: false, message: 'O campo valor não pode ser superior a 100.', fieldErrors: { value: 'O campo valor não pode ser superior a 100.' } }) + }) + + it('erro ao carregar vira estado de erro', async () => { + vi.mocked(ticketsService.types).mockRejectedValueOnce(new TicketsError('x', 500)) + const tickets = useTickets('ed-1') + await tickets.load() + expect(tickets.state.value).toBe('error') + }) +}) diff --git a/front-admin/app/modules/tickets/composables/useTickets.ts b/front-admin/app/modules/tickets/composables/useTickets.ts new file mode 100644 index 0000000..829fa79 --- /dev/null +++ b/front-admin/app/modules/tickets/composables/useTickets.ts @@ -0,0 +1,195 @@ +import { computed, ref } from 'vue' +import ticketsService, { type BatchPayload, type CouponPayload, type SettingsPayload, type TicketTypePayload } from '../services/ticketsService' +import { TicketsError } from '../services/ticketsError' +import locale from '../locales/pt-br' +import { localToIso } from './money' +import type { Batch, BatchInput, Coupon, CouponInput, MutationResult, SalesSettings, SettingsInput, TicketType, TicketTypeInput } from '../types' + +const translateBatch = (payload: BatchPayload): Batch => ({ + id: payload.id, + ticketTypeId: payload.ticket_type_id, + name: payload.name, + position: payload.position, + priceCents: payload.price.amount, + quantity: payload.quantity, + sold: payload.allocated, + remaining: payload.remaining, + startsAt: payload.starts_at, + endsAt: payload.ends_at, + onSellOut: payload.on_sell_out, + status: payload.status, + statusLabel: payload.status_label, +}) + +const translateType = (payload: TicketTypePayload): TicketType => ({ + id: payload.id, + name: payload.name, + description: payload.description ?? '', + visibility: payload.visibility, + visibilityLabel: payload.visibility_label, + accessCode: payload.access_code ?? '', + minPerOrder: payload.min_per_order, + maxPerOrder: payload.max_per_order, + showRemaining: payload.show_remaining, + passFeeToBuyer: payload.pass_fee_to_buyer, + questions: payload.questions.map((q) => ({ label: q.label, type: q.type, required: q.required ?? false, options: q.options ?? [] })), + position: payload.position, + sold: payload.allocated, + quantity: payload.quantity, + currentBatchId: payload.current_batch_id, + batches: payload.batches.map(translateBatch), +}) + +const translateSettings = (payload: SettingsPayload): SalesSettings => ({ + gatewayReady: payload.gateway_ready, + capacity: payload.capacity, + sold: payload.allocated, + remaining: payload.remaining, + reservationMinutes: payload.reservation_minutes, + maxTicketsPerBuyer: payload.max_tickets_per_buyer, + feeBasisPoints: payload.gateway_fee_basis_points, +}) + +const translateCoupon = (payload: CouponPayload): Coupon => ({ + id: payload.id, + code: payload.code, + description: payload.description ?? '', + kind: payload.kind, + kindLabel: payload.kind_label, + value: payload.value, + maxUses: payload.max_uses, + used: payload.used, + remaining: payload.remaining, + startsAt: payload.starts_at, + endsAt: payload.ends_at, + ticketTypeIds: payload.ticket_type_ids, + active: payload.active, + status: payload.status, + discountTotalCents: payload.discount_total.amount, +}) + +const FIELDS: Record = { + name: 'name', description: 'description', visibility: 'visibility', access_code: 'accessCode', min_per_order: 'minPerOrder', max_per_order: 'maxPerOrder', + price_cents: 'price', quantity: 'quantity', starts_at: 'startsAt', ends_at: 'endsAt', on_sell_out: 'onSellOut', batch: 'batch', ticket_type: 'type', + code: 'code', kind: 'kind', value: 'value', max_uses: 'maxUses', ticket_type_ids: 'ticketTypeIds', active: 'active', coupon: 'coupon', + capacity: 'capacity', reservation_minutes: 'reservationMinutes', max_tickets_per_buyer: 'maxTicketsPerBuyer', gateway_fee_basis_points: 'feeBasisPoints', +} + +function failure(error: unknown): MutationResult { + if (error instanceof TicketsError && error.statusCode === 422 && error.fieldErrors) { + const fieldErrors = Object.fromEntries(Object.entries(error.fieldErrors).map(([key, messages]) => [FIELDS[key.split('.')[0] ?? key] ?? key, messages[0] ?? ''])) + return { ok: false, message: Object.values(fieldErrors)[0] ?? locale.genericError, fieldErrors } + } + return { ok: false, message: locale.genericError, fieldErrors: {} } +} + +const orNull = (text: string) => (text.trim() === '' ? null : text.trim()) + +export function useTickets(editionId: string) { + const types = ref([]) + const settings = ref(null) + const coupons = ref([]) + const state = ref<'loading' | 'ready' | 'error'>('loading') + + async function loadTypes() { + const payload = await ticketsService.types(editionId) + types.value = payload.data.map(translateType) + settings.value = translateSettings(payload.meta) + } + + async function loadCoupons() { + coupons.value = (await ticketsService.coupons(editionId)).data.map(translateCoupon) + } + + async function load(): Promise { + state.value = 'loading' + try { + await Promise.all([loadTypes(), loadCoupons()]) + state.value = 'ready' + } catch { + state.value = 'error' + } + } + + async function mutate(request: () => Promise, reload: () => Promise = loadTypes): Promise { + try { + await request() + await reload() + return { ok: true } + } catch (error) { + return failure(error) + } + } + + /** Lote pago à venda (ou agendado) com a conta do gateway ainda não validada. */ + const salesPaused = computed(() => settings.value !== null && !settings.value.gatewayReady + && types.value.some((type) => type.batches.some((batch) => batch.priceCents > 0 && batch.status !== 'ended' && batch.status !== 'sold_out'))) + + const saveType = (type: TicketType | null, input: TicketTypeInput) => mutate(() => { + const body = { + name: input.name.trim(), + description: orNull(input.description), + visibility: input.visibility, + access_code: input.visibility === 'code' ? orNull(input.accessCode) : null, + min_per_order: Number(input.minPerOrder), + max_per_order: Number(input.maxPerOrder), + show_remaining: input.showRemaining, + pass_fee_to_buyer: input.passFeeToBuyer, + questions: input.questions.map((q) => ({ label: q.label.trim(), type: q.type, required: q.required, ...(q.type === 'select' ? { options: q.options.map((o) => o.trim()).filter(Boolean) } : {}) })), + } + return type ? ticketsService.updateType(editionId, type.id, body) : ticketsService.createType(editionId, body) + }) + + const removeType = (type: TicketType) => mutate(() => ticketsService.deleteType(editionId, type.id)) + + async function moveType(type: TicketType, direction: -1 | 1): Promise { + const index = types.value.findIndex((item) => item.id === type.id) + const other = types.value[index + direction] + if (!other) return { ok: true } + return mutate(async () => { + await ticketsService.updateType(editionId, type.id, { position: other.position }) + await ticketsService.updateType(editionId, other.id, { position: type.position }) + }) + } + + const saveBatch = (type: TicketType, batch: Batch | null, input: BatchInput) => mutate(() => { + const body = { + name: input.name.trim(), + price_cents: input.priceCents, + quantity: Number(input.quantity), + starts_at: localToIso(input.startsAt), + ends_at: localToIso(input.endsAt), + on_sell_out: input.onSellOut, + } + return batch ? ticketsService.updateBatch(editionId, type.id, batch.id, body) : ticketsService.createBatch(editionId, type.id, body) + }) + + const closeBatch = (batch: Batch) => mutate(() => ticketsService.closeBatch(editionId, batch.ticketTypeId, batch.id)) + const removeBatch = (batch: Batch) => mutate(() => ticketsService.deleteBatch(editionId, batch.ticketTypeId, batch.id)) + + const saveCoupon = (coupon: Coupon | null, input: CouponInput) => mutate(() => { + const body = { + ...(coupon && coupon.used > 0 ? {} : { code: input.code.trim().toUpperCase() }), + description: orNull(input.description), + kind: input.kind, + value: Number(input.value), + max_uses: input.maxUses === null || String(input.maxUses) === '' ? null : Number(input.maxUses), + starts_at: localToIso(input.startsAt), + ends_at: localToIso(input.endsAt), + ticket_type_ids: input.ticketTypeIds, + active: input.active, + } + return coupon ? ticketsService.updateCoupon(editionId, coupon.id, body) : ticketsService.createCoupon(editionId, body as Required) + }, loadCoupons) + + const removeCoupon = (coupon: Coupon) => mutate(() => ticketsService.deleteCoupon(editionId, coupon.id), loadCoupons) + + const saveSettings = (input: SettingsInput) => mutate(() => ticketsService.updateSettings(editionId, { + capacity: input.capacity === null || String(input.capacity) === '' ? null : Number(input.capacity), + reservation_minutes: Number(input.reservationMinutes), + max_tickets_per_buyer: input.maxTicketsPerBuyer === null || String(input.maxTicketsPerBuyer) === '' ? null : Number(input.maxTicketsPerBuyer), + gateway_fee_basis_points: Number(input.feeBasisPoints), + })) + + return { types, settings, coupons, state, salesPaused, load, saveType, removeType, moveType, saveBatch, closeBatch, removeBatch, saveCoupon, removeCoupon, saveSettings } +} diff --git a/front-admin/app/modules/tickets/locales/pt-br/index.ts b/front-admin/app/modules/tickets/locales/pt-br/index.ts new file mode 100644 index 0000000..148b482 --- /dev/null +++ b/front-admin/app/modules/tickets/locales/pt-br/index.ts @@ -0,0 +1,146 @@ +export default { + title: 'Ingressos', + subtitle: 'O que vai ser vendido: tipos, lotes, cupons e regras da venda.', + loadError: 'Não foi possível carregar os ingressos.', + genericError: 'Não deu para salvar agora. Tente de novo.', + readOnly: 'Edição encerrada: os ingressos ficam só para consulta.', + tabsLabel: 'Seções de ingressos', + tabs: { types: 'Tipos e lotes', coupons: 'Cupons', settings: 'Regras da venda' }, + pausedTitle: 'Vendas pausadas até o teste do gateway', + pausedText: 'Há lote pago, mas a conta de recebimento ainda não foi validada. Ninguém consegue comprar ingresso pago até as chaves e o webhook serem testados.', + pausedAction: 'Ir para Pagamentos', + capacityUsed: '{sold} de {capacity} lugares da edição vendidos ou reservados', + capacityFree: '{sold} ingressos vendidos ou reservados (sem limite de lugares)', + + newType: 'Novo tipo de ingresso', + editType: 'Editar tipo', + noTypes: 'Nenhum tipo de ingresso ainda', + noTypesHint: 'Comece pelo ingresso principal (ex.: "Inteira") e depois crie os lotes com preço e quantidade.', + soldOfTotal: '{sold} de {total} vendidos', + newBatch: 'Novo lote', + noBatches: 'Sem lote, este ingresso não aparece para venda.', + batch: 'Lote', + price: 'Preço', + received: 'Você recebe', + sold: 'Vendidos', + period: 'Período', + status: 'Situação', + actions: 'Ações', + edit: 'Editar', + close: 'Encerrar', + remove: 'Remover', + current: 'atual', + anytime: 'Sem data', + untilSoldOut: 'até esgotar', + fromTo: '{from} a {to}', + from: 'a partir de {from}', + until: 'até {to}', + moveUp: 'Subir {nome}', + moveDown: 'Descer {nome}', + + typeName: 'Nome do ingresso', + typeDescription: 'Descrição (aparece no checkout)', + visibility: 'Quem pode comprar', + visibilityOptions: { public: 'Qualquer pessoa', code: 'Quem tem o código', hidden: 'Só por convite da organização' }, + accessCode: 'Código de acesso', + accessCodeHint: 'Letras, números, hífen e sublinhado. Quem digita o código no checkout vê este ingresso.', + minPerOrder: 'Mínimo por pedido', + maxPerOrder: 'Máximo por pedido', + showRemaining: 'Mostrar quantos restam no checkout', + passFee: 'Repassar a taxa do gateway para quem compra', + passFeeHint: 'Com a opção ligada, a taxa soma ao preço; desligada, sai do que a edição recebe.', + questionsTitle: 'Perguntas do checkout', + questionsHint: 'Perguntadas para cada participante deste ingresso, além de nome e e-mail.', + addQuestion: 'Adicionar pergunta', + question: 'Pergunta {n}', + questionLabel: 'Texto da pergunta', + questionType: 'Tipo de resposta', + questionTypes: { text: 'Texto livre', select: 'Escolha numa lista', boolean: 'Sim ou não' }, + questionRequired: 'Obrigatória', + questionOptions: 'Opções (uma por linha)', + removeQuestion: 'Remover pergunta {n}', + saveType: 'Salvar ingresso', + removeType: 'Remover ingresso', + removeTypeTitle: 'Remover "{nome}"?', + removeTypeText: 'O ingresso e os lotes dele deixam de existir. Só dá para remover ingresso sem vendas.', + typeSaved: 'Ingresso "{nome}" salvo.', + typeRemoved: 'Ingresso "{nome}" removido.', + previewTitle: 'Como aparece no checkout', + previewName: 'Nome do ingresso', + previewRemaining: 'Restam {n}', + previewFee: '+ {fee} de taxa', + previewSoldOut: 'Esgotado', + previewNoBatch: 'Ainda sem lote à venda', + previewOnlyCode: 'Só com código', + + newBatchTitle: 'Novo lote de "{nome}"', + editBatchTitle: 'Editar {lote}', + batchName: 'Nome do lote', + priceHint: 'Em reais. Use 0 para ingresso gratuito.', + priceInvalid: 'Use um valor como 150 ou 150,00.', + quantity: 'Quantidade', + startsAt: 'Começa em', + endsAt: 'Termina em', + endsAfterStarts: 'O fim precisa ser depois do começo.', + onSellOut: 'Quando esgotar', + onSellOutOptions: { next: 'Abrir o próximo lote', close: 'Encerrar vendas' }, + netTitle: 'Cálculo por ingresso', + netBuyerPays: 'Quem compra paga', + netFee: 'Taxa do gateway ({pct})', + netReceived: 'A edição recebe', + netFree: 'Ingresso gratuito: não passa pelo gateway nem tem taxa.', + priceChangeWarning: 'Este lote já tem {n} ingressos vendidos ou reservados. O preço novo só vale para as próximas compras; pedidos existentes não mudam.', + saveBatch: 'Salvar lote', + batchSaved: 'Lote "{nome}" salvo.', + closeBatchTitle: 'Encerrar {lote}?', + closeBatchText: 'O lote para de vender agora. Se houver próximo lote, ele abre.', + batchClosed: 'Lote "{nome}" encerrado.', + removeBatchTitle: 'Remover {lote}?', + removeBatchText: 'Só dá para remover lote sem vendas. Com vendas, encerre o lote.', + batchRemoved: 'Lote "{nome}" removido.', + + newCoupon: 'Novo cupom', + editCoupon: 'Editar cupom', + noCoupons: 'Nenhum cupom ainda', + noCouponsHint: 'Cupom dá desconto em percentual ou valor fixo por pedido, com limite de usos e validade.', + code: 'Código', + discount: 'Desconto', + uses: 'Usos', + validity: 'Validade', + discountGiven: 'Desconto dado', + usesOf: '{used} de {max}', + usesUnlimited: '{used} (sem limite)', + couponStatus: { active: 'Ativo', paused: 'Pausado', scheduled: 'Agendado', expired: 'Vencido', exhausted: 'Esgotado' } as Record, + couponCode: 'Código do cupom', + couponCodeHint: 'Quem compra digita este código. Guardado em maiúsculas.', + couponDescription: 'Para que serve (só a organização vê)', + couponKind: 'Tipo de desconto', + couponKinds: { percent: 'Percentual', fixed: 'Valor fixo por pedido' }, + couponPercent: 'Percentual de desconto', + couponFixed: 'Valor do desconto', + maxUses: 'Limite de usos', + maxUsesHint: 'Vazio = sem limite.', + couponTypes: 'Vale para', + couponAllTypes: 'Todos os ingressos', + couponActive: 'Cupom ativo', + couponUsedLocked: 'O cupom já foi usado: o código não muda mais. Para parar de aceitar, pause o cupom.', + saveCoupon: 'Salvar cupom', + couponSaved: 'Cupom {codigo} salvo.', + removeCoupon: 'Remover cupom', + couponRemoved: 'Cupom {codigo} removido.', + + settingsTitle: 'Regras da venda', + capacity: 'Lugares na edição', + capacityHint: 'Limite total, somando todos os tipos. Vazio = sem limite.', + reservationMinutes: 'Minutos para pagar', + reservationHint: 'Quanto tempo o pedido segura os ingressos antes de expirar.', + maxPerBuyer: 'Ingressos por pessoa', + maxPerBuyerHint: 'Somando todos os pedidos do mesmo e-mail ou CPF. Vazio = sem limite.', + feePercent: 'Taxa estimada do gateway (%)', + feeHint: 'Usada no cálculo do valor líquido e, nos ingressos com repasse, somada ao preço. Confira a taxa no guia dos gateways.', + saveSettings: 'Salvar regras', + settingsSaved: 'Regras da venda salvas.', + + back: 'Voltar', + required: 'Preencha este campo.', +} diff --git a/front-admin/app/modules/tickets/router/index.ts b/front-admin/app/modules/tickets/router/index.ts new file mode 100644 index 0000000..8ab6764 --- /dev/null +++ b/front-admin/app/modules/tickets/router/index.ts @@ -0,0 +1,9 @@ +import type { RouteRecordRaw } from 'vue-router' + +const TicketsView = () => import('../views/TicketsView.vue') + +export const ticketsRoutes: RouteRecordRaw[] = [ + { path: '/ingressos', name: 'tickets', component: TicketsView }, +] + +export default ticketsRoutes diff --git a/front-admin/app/modules/tickets/services/ticketsError.ts b/front-admin/app/modules/tickets/services/ticketsError.ts new file mode 100644 index 0000000..dfe6a5a --- /dev/null +++ b/front-admin/app/modules/tickets/services/ticketsError.ts @@ -0,0 +1,11 @@ +export class TicketsError extends Error { + statusCode: number | null + fieldErrors: Record | null + + constructor(message: string, statusCode: number | null = null, fieldErrors: Record | null = null) { + super(message) + this.name = 'TicketsError' + this.statusCode = statusCode + this.fieldErrors = fieldErrors + } +} diff --git a/front-admin/app/modules/tickets/services/ticketsService.test.ts b/front-admin/app/modules/tickets/services/ticketsService.test.ts new file mode 100644 index 0000000..e7a99f3 --- /dev/null +++ b/front-admin/app/modules/tickets/services/ticketsService.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it, vi } from 'vitest' +import { httpClient, HttpClientError } from '@/infrastructure/http/HttpClient' +import ticketsService from './ticketsService' +import { TicketsError } from './ticketsError' + +vi.mock('@/infrastructure/http/HttpClient', () => ({ + httpClient: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() }, + HttpClientError: class extends Error { + statusCode: number | null + fieldErrors: Record | null + + constructor(message: string, statusCode: number | null = null, fieldErrors: Record | null = null) { + super(message) + this.statusCode = statusCode + this.fieldErrors = fieldErrors + } + }, +})) + +describe('ticketsService', () => { + it('chama as rotas de tipos, lotes, cupons e regras da edição', async () => { + vi.mocked(httpClient.get).mockResolvedValue({ data: [] }) + vi.mocked(httpClient.post).mockResolvedValue({ data: {} }) + vi.mocked(httpClient.patch).mockResolvedValue({ data: {} }) + vi.mocked(httpClient.delete).mockResolvedValue(null) + + await ticketsService.types('ed-1') + await ticketsService.updateType('ed-1', 'tt-1', { position: 2 }) + await ticketsService.createBatch('ed-1', 'tt-1', { name: '1º lote', price_cents: 15000, quantity: 100, starts_at: null, ends_at: null, on_sell_out: 'next' }) + await ticketsService.closeBatch('ed-1', 'tt-1', 'b-1') + await ticketsService.deleteBatch('ed-1', 'tt-1', 'b-1') + await ticketsService.coupons('ed-1') + await ticketsService.deleteCoupon('ed-1', 'c-1') + await ticketsService.updateSettings('ed-1', { capacity: 400, reservation_minutes: 30, max_tickets_per_buyer: null, gateway_fee_basis_points: 499 }) + + expect(httpClient.get).toHaveBeenCalledWith('/editions/ed-1/ticketing/ticket-types') + expect(httpClient.patch).toHaveBeenCalledWith('/editions/ed-1/ticketing/ticket-types/tt-1', { body: { position: 2 } }) + expect(httpClient.post).toHaveBeenCalledWith('/editions/ed-1/ticketing/ticket-types/tt-1/batches', expect.objectContaining({ body: expect.objectContaining({ price_cents: 15000 }) })) + expect(httpClient.post).toHaveBeenCalledWith('/editions/ed-1/ticketing/ticket-types/tt-1/batches/b-1/close') + expect(httpClient.delete).toHaveBeenCalledWith('/editions/ed-1/ticketing/ticket-types/tt-1/batches/b-1') + expect(httpClient.get).toHaveBeenCalledWith('/editions/ed-1/ticketing/coupons') + expect(httpClient.delete).toHaveBeenCalledWith('/editions/ed-1/ticketing/coupons/c-1') + expect(httpClient.patch).toHaveBeenCalledWith('/editions/ed-1/ticketing/settings', { body: expect.objectContaining({ gateway_fee_basis_points: 499 }) }) + }) + + it('embrulha o erro da API num TicketsError', async () => { + vi.mocked(httpClient.post).mockRejectedValueOnce(new HttpClientError('x', 422, { name: ['O campo nome já está sendo utilizado.'] })) + + const error = await ticketsService.createType('ed-1', {} as never).catch((e: unknown) => e) + expect(error).toBeInstanceOf(TicketsError) + expect(error).toMatchObject({ statusCode: 422 }) + }) +}) diff --git a/front-admin/app/modules/tickets/services/ticketsService.ts b/front-admin/app/modules/tickets/services/ticketsService.ts new file mode 100644 index 0000000..672093b --- /dev/null +++ b/front-admin/app/modules/tickets/services/ticketsService.ts @@ -0,0 +1,144 @@ +import { httpClient, HttpClientError } from '@/infrastructure/http/HttpClient' +import { TicketsError } from './ticketsError' + +export interface Money { amount: number, currency: string } + +export interface BatchPayload { + id: string + ticket_type_id: string + name: string + position: number + price: Money + quantity: number + allocated: number + remaining: number + starts_at: string | null + ends_at: string | null + on_sell_out: 'next' | 'close' + status: 'scheduled' | 'on_sale' | 'sold_out' | 'ended' + status_label: string +} + +export interface QuestionPayload { label: string, type: 'text' | 'select' | 'boolean', required?: boolean, options?: string[] } + +export interface TicketTypePayload { + id: string + name: string + description: string | null + visibility: 'public' | 'code' | 'hidden' + visibility_label: string + access_code: string | null + min_per_order: number + max_per_order: number + show_remaining: boolean + pass_fee_to_buyer: boolean + questions: QuestionPayload[] + position: number + allocated: number + quantity: number + current_batch_id: string | null + batches: BatchPayload[] +} + +export interface SettingsPayload { + gateway_ready: boolean + capacity: number | null + allocated: number + remaining: number | null + reservation_minutes: number + max_tickets_per_buyer: number | null + gateway_fee_basis_points: number +} + +export interface CouponPayload { + id: string + code: string + description: string | null + kind: 'percent' | 'fixed' + kind_label: string + value: number + max_uses: number | null + used: number + remaining: number | null + starts_at: string | null + ends_at: string | null + ticket_type_ids: string[] + active: boolean + status: string + discount_total: Money +} + +export interface TicketTypeBody { + name: string + description: string | null + visibility: string + access_code: string | null + min_per_order: number + max_per_order: number + show_remaining: boolean + pass_fee_to_buyer: boolean + questions: QuestionPayload[] +} + +export interface BatchBody { + name: string + price_cents: number + quantity: number + starts_at: string | null + ends_at: string | null + on_sell_out: string +} + +export interface CouponBody { + code: string + description: string | null + kind: string + value: number + max_uses: number | null + starts_at: string | null + ends_at: string | null + ticket_type_ids: string[] + active: boolean +} + +export interface SettingsBody { + capacity: number | null + reservation_minutes: number + max_tickets_per_buyer: number | null + gateway_fee_basis_points: number +} + +const base = (editionId: string) => `/editions/${editionId}/ticketing` + +async function call(request: () => Promise): Promise { + try { + return await request() + } catch (error) { + if (error instanceof HttpClientError) { + throw new TicketsError(error.message, error.statusCode, error.fieldErrors) + } + throw new TicketsError('Request failed') + } +} + +export default { + types: (editionId: string) => call(() => httpClient.get<{ data: TicketTypePayload[], meta: SettingsPayload }>(`${base(editionId)}/ticket-types`)), + createType: (editionId: string, body: TicketTypeBody) => call(() => httpClient.post<{ data: TicketTypePayload }>(`${base(editionId)}/ticket-types`, { body })), + updateType: (editionId: string, typeId: string, body: Partial & { position?: number }) => + call(() => httpClient.patch<{ data: TicketTypePayload }>(`${base(editionId)}/ticket-types/${typeId}`, { body })), + deleteType: (editionId: string, typeId: string) => call(() => httpClient.delete(`${base(editionId)}/ticket-types/${typeId}`)), + createBatch: (editionId: string, typeId: string, body: BatchBody) => + call(() => httpClient.post<{ data: BatchPayload }>(`${base(editionId)}/ticket-types/${typeId}/batches`, { body })), + updateBatch: (editionId: string, typeId: string, batchId: string, body: Partial) => + call(() => httpClient.patch<{ data: BatchPayload }>(`${base(editionId)}/ticket-types/${typeId}/batches/${batchId}`, { body })), + closeBatch: (editionId: string, typeId: string, batchId: string) => + call(() => httpClient.post<{ data: BatchPayload }>(`${base(editionId)}/ticket-types/${typeId}/batches/${batchId}/close`)), + deleteBatch: (editionId: string, typeId: string, batchId: string) => + call(() => httpClient.delete(`${base(editionId)}/ticket-types/${typeId}/batches/${batchId}`)), + updateSettings: (editionId: string, body: SettingsBody) => call(() => httpClient.patch<{ data: SettingsPayload }>(`${base(editionId)}/settings`, { body })), + coupons: (editionId: string) => call(() => httpClient.get<{ data: CouponPayload[] }>(`${base(editionId)}/coupons`)), + createCoupon: (editionId: string, body: CouponBody) => call(() => httpClient.post<{ data: CouponPayload }>(`${base(editionId)}/coupons`, { body })), + updateCoupon: (editionId: string, couponId: string, body: Partial) => + call(() => httpClient.patch<{ data: CouponPayload }>(`${base(editionId)}/coupons/${couponId}`, { body })), + deleteCoupon: (editionId: string, couponId: string) => call(() => httpClient.delete(`${base(editionId)}/coupons/${couponId}`)), +} diff --git a/front-admin/app/modules/tickets/types/index.ts b/front-admin/app/modules/tickets/types/index.ts new file mode 100644 index 0000000..455a293 --- /dev/null +++ b/front-admin/app/modules/tickets/types/index.ts @@ -0,0 +1,117 @@ +export type Visibility = 'public' | 'code' | 'hidden' +export type SellOut = 'next' | 'close' +export type BatchStatus = 'scheduled' | 'on_sale' | 'sold_out' | 'ended' +export type QuestionType = 'text' | 'select' | 'boolean' +export type CouponKind = 'percent' | 'fixed' + +export interface Question { + label: string + type: QuestionType + required: boolean + options: string[] +} + +export interface Batch { + id: string + ticketTypeId: string + name: string + position: number + priceCents: number + quantity: number + sold: number + remaining: number + startsAt: string | null + endsAt: string | null + onSellOut: SellOut + status: BatchStatus + statusLabel: string +} + +export interface TicketType { + id: string + name: string + description: string + visibility: Visibility + visibilityLabel: string + accessCode: string + minPerOrder: number + maxPerOrder: number + showRemaining: boolean + passFeeToBuyer: boolean + questions: Question[] + position: number + sold: number + quantity: number + currentBatchId: string | null + batches: Batch[] +} + +export interface SalesSettings { + gatewayReady: boolean + capacity: number | null + sold: number + remaining: number | null + reservationMinutes: number + maxTicketsPerBuyer: number | null + feeBasisPoints: number +} + +export interface Coupon { + id: string + code: string + description: string + kind: CouponKind + kindLabel: string + value: number + maxUses: number | null + used: number + remaining: number | null + startsAt: string | null + endsAt: string | null + ticketTypeIds: string[] + active: boolean + status: string + discountTotalCents: number +} + +export interface TicketTypeInput { + name: string + description: string + visibility: Visibility + accessCode: string + minPerOrder: number + maxPerOrder: number + showRemaining: boolean + passFeeToBuyer: boolean + questions: Question[] +} + +export interface BatchInput { + name: string + priceCents: number + quantity: number + startsAt: string + endsAt: string + onSellOut: SellOut +} + +export interface CouponInput { + code: string + description: string + kind: CouponKind + value: number + maxUses: number | null + startsAt: string + endsAt: string + ticketTypeIds: string[] + active: boolean +} + +export interface SettingsInput { + capacity: number | null + reservationMinutes: number + maxTicketsPerBuyer: number | null + feeBasisPoints: number +} + +export type MutationResult = { ok: true } | { ok: false, message: string, fieldErrors: Record } diff --git a/front-admin/app/modules/tickets/views/TicketsView.vue b/front-admin/app/modules/tickets/views/TicketsView.vue new file mode 100644 index 0000000..a9a6018 --- /dev/null +++ b/front-admin/app/modules/tickets/views/TicketsView.vue @@ -0,0 +1,13 @@ + + + diff --git a/front-admin/app/pages/ingressos/index.vue b/front-admin/app/pages/ingressos/index.vue new file mode 100644 index 0000000..be476d6 --- /dev/null +++ b/front-admin/app/pages/ingressos/index.vue @@ -0,0 +1,7 @@ + + + diff --git a/front-admin/e2e/capturas-arquitetura.spec.ts b/front-admin/e2e/capturas-arquitetura.spec.ts index 93c81ec..30e03c8 100644 --- a/front-admin/e2e/capturas-arquitetura.spec.ts +++ b/front-admin/e2e/capturas-arquitetura.spec.ts @@ -85,3 +85,21 @@ test('catálogo de componentes', async ({ page, goto }) => { await goto('/_dev/componentes', { waitUntil: 'hydration' }) await page.screenshot({ path: out('painel-componentes') }) }) + +test('ingressos', async ({ page, goto }) => { + await page.setViewportSize({ width: 1440, height: 1000 }) + await signedIn(page) + const batch = (id: string, name: string, cents: number, sold: number, status: string, label: string) => ({ id, ticket_type_id: 'tt-1', name, position: 0, price: { amount: cents, currency: 'BRL' }, quantity: 150, allocated: sold, remaining: 150 - sold, starts_at: null, ends_at: '2027-06-30T23:59:00Z', on_sell_out: 'next', status, status_label: label }) + const types = [ + { id: 'tt-1', name: 'Inteira', description: 'Acesso aos dois dias', visibility: 'public', visibility_label: 'Qualquer pessoa', access_code: null, min_per_order: 1, max_per_order: 10, show_remaining: true, pass_fee_to_buyer: false, questions: [], position: 0, allocated: 188, quantity: 300, current_batch_id: 'b-2', batches: [batch('b-1', '1º lote', 12000, 150, 'sold_out', 'Esgotado'), batch('b-2', '2º lote', 15000, 38, 'on_sale', 'À venda')] }, + { id: 'tt-2', name: 'Estudante', description: null, visibility: 'code', visibility_label: 'Quem tem o código', access_code: 'UFPB2027', min_per_order: 1, max_per_order: 1, show_remaining: false, pass_fee_to_buyer: true, questions: [], position: 1, allocated: 41, quantity: 100, current_batch_id: 'b-3', batches: [{ ...batch('b-3', 'Lote único', 7500, 41, 'on_sale', 'À venda'), ticket_type_id: 'tt-2', quantity: 100, remaining: 59 }] }, + ] + await page.route('**/api/v1/editions/ed-27/ticketing/**', (route) => { + const path = new URL(route.request().url()).pathname + if (path.endsWith('/ticket-types')) return route.fulfill({ status: 200, json: { data: types, meta: { gateway_ready: true, capacity: 400, allocated: 229, remaining: 171, reservation_minutes: 30, max_tickets_per_buyer: 4, gateway_fee_basis_points: 499 } } }) + return route.fulfill({ status: 200, json: { data: [] } }) + }) + await goto('/ingressos', { waitUntil: 'hydration' }) + await expect(page.getByRole('heading', { name: 'Ingressos', level: 1 })).toBeVisible() + await page.screenshot({ path: out('painel-ingressos') }) +}) diff --git a/front-admin/e2e/tickets.spec.ts b/front-admin/e2e/tickets.spec.ts new file mode 100644 index 0000000..d492103 --- /dev/null +++ b/front-admin/e2e/tickets.spec.ts @@ -0,0 +1,115 @@ +import { expect, test } from '@nuxt/test-utils/playwright' +import type { Page, Route } from '@playwright/test' + +const session = { user: { id: 'u-me', name: 'Rita Organiza', email: 'rita@php-pb.net', avatarUrl: null }, token: 'e2e-token' } +const edition = (role: string) => ({ + id: 'ed-27', slug: '2027', name: 'PHPeste 2027', community_id: 'c1', community: { id: 'c1', name: 'PHP-PB', slug: 'php-pb' }, + status: 'sales_open', status_label: 'Vendas abertas', starts_on: '2027-10-08', ends_on: '2027-10-09', city: 'João Pessoa', state: 'PB', year: 2027, site_url: null, role, +}) +const batch = (overrides: Record = {}) => ({ + id: 'b-1', ticket_type_id: 'tt-1', name: '1º lote', position: 0, price: { amount: 15000, currency: 'BRL' }, quantity: 100, allocated: 12, remaining: 88, + starts_at: null, ends_at: null, on_sell_out: 'next', status: 'on_sale', status_label: 'À venda', ...overrides, +}) +const ticketType = { + id: 'tt-1', name: 'Inteira', description: 'Acesso aos dois dias', visibility: 'public', visibility_label: 'Qualquer pessoa', access_code: null, min_per_order: 1, max_per_order: 10, + show_remaining: true, pass_fee_to_buyer: false, questions: [], position: 0, allocated: 12, quantity: 100, current_batch_id: 'b-1', batches: [batch()], +} +const meta = (ready: boolean) => ({ gateway_ready: ready, capacity: 400, allocated: 12, remaining: 388, reservation_minutes: 30, max_tickets_per_buyer: null, gateway_fee_basis_points: 499 }) + +async function open(page: Page, goto: (url: string, options: { waitUntil: 'hydration' }) => Promise, role: string, ready: boolean, onRequest: (route: Route, method: string, path: string) => Promise | void = () => {}) { + await page.addInitScript((value) => localStorage.setItem('app.auth', JSON.stringify(value)), session) + await page.route('**/api/v1/editions', (route) => route.fulfill({ status: 200, json: { data: [edition(role)] } })) + await page.route('**/api/v1/editions/ed-27/ticketing/**', async (route) => { + const method = route.request().method() + const path = new URL(route.request().url()).pathname.replace('/api/v1/editions/ed-27/ticketing', '') + await onRequest(route, method, path) + if (path === '/ticket-types' && method === 'GET') return route.fulfill({ status: 200, json: { data: [ticketType], meta: meta(ready) } }) + if (path === '/coupons' && method === 'GET') return route.fulfill({ status: 200, json: { data: [] } }) + return route.fulfill({ status: 200, json: { data: {} } }) + }) + await goto('/ingressos', { waitUntil: 'hydration' }) + await expect(page.getByRole('heading', { name: 'Ingressos', level: 1 })).toBeVisible() +} + +test.describe('Ingressos', () => { + test('lista tipos e lotes com o líquido depois da taxa e avisa que as vendas estão pausadas', async ({ page, goto }) => { + await open(page, goto, 'organizador', false) + + await expect(page.getByTestId('sales-paused')).toContainText('Vendas pausadas até o teste do gateway') + await expect(page.getByRole('link', { name: 'Ir para Pagamentos' })).toHaveAttribute('href', '/pagamentos') + await expect(page.getByText('12 de 400 lugares da edição vendidos ou reservados')).toBeVisible() + + const row = page.getByRole('row', { name: /1º lote/ }) + await expect(row).toContainText('R$ 150,00') + await expect(row).toContainText('R$ 142,51') + await expect(row).toContainText('12 / 100') + await expect(row).toContainText('À venda') + }) + + test('editar o preço de lote com vendas avisa que pedidos existentes não mudam e manda centavos', async ({ page, goto }) => { + const bodies: unknown[] = [] + await open(page, goto, 'organizador', true, (route, method, path) => { + if (method === 'PATCH' && path === '/ticket-types/tt-1/batches/b-1') bodies.push(route.request().postDataJSON()) + }) + + await expect(page.getByTestId('sales-paused')).toHaveCount(0) + await page.getByRole('button', { name: 'Editar 1º lote de Inteira' }).click() + const dialog = page.getByRole('dialog', { name: 'Editar 1º lote' }) + await dialog.getByLabel('Preço').fill('170,00') + + await expect(dialog.getByTestId('price-change-warning')).toContainText('pedidos existentes não mudam') + await expect(dialog.getByTestId('net-calculation')).toContainText('R$ 161,51') + + await dialog.getByRole('button', { name: 'Salvar lote' }).click() + await expect(page.getByText('Lote "1º lote" salvo.')).toBeVisible() + expect(bodies[0]).toMatchObject({ price_cents: 17000, quantity: 100 }) + }) + + test('cria tipo com pergunta do checkout vendo a prévia do cartão', async ({ page, goto }) => { + const bodies: unknown[] = [] + await open(page, goto, 'organizador', true, (route, method, path) => { + if (method === 'POST' && path === '/ticket-types') bodies.push(route.request().postDataJSON()) + }) + + await page.getByRole('button', { name: 'Novo tipo de ingresso' }).click() + const drawer = page.getByRole('dialog', { name: 'Novo tipo de ingresso' }) + await drawer.getByLabel('Nome do ingresso').fill('Estudante') + await drawer.getByLabel('Quem pode comprar').selectOption('code') + await drawer.getByLabel('Código de acesso').fill('UFPB2027') + await drawer.getByRole('button', { name: 'Adicionar pergunta' }).click() + await drawer.getByLabel('Texto da pergunta').fill('Curso') + + await expect(drawer.getByTestId('ticket-preview')).toContainText('Estudante') + await expect(drawer.getByTestId('ticket-preview')).toContainText('Só com código') + + await drawer.getByRole('button', { name: 'Salvar ingresso' }).click() + await expect(page.getByText('Ingresso "Estudante" salvo.')).toBeVisible() + expect(bodies[0]).toMatchObject({ name: 'Estudante', visibility: 'code', access_code: 'UFPB2027', questions: [{ label: 'Curso', type: 'text', required: false }] }) + }) + + test('cria cupom percentual', async ({ page, goto }) => { + const bodies: unknown[] = [] + await open(page, goto, 'organizador', true, (route, method, path) => { + if (method === 'POST' && path === '/coupons') bodies.push(route.request().postDataJSON()) + }) + + await page.getByRole('tab', { name: 'Cupons' }).click() + await page.getByRole('button', { name: 'Novo cupom' }).click() + const dialog = page.getByRole('dialog', { name: 'Novo cupom' }) + await dialog.getByLabel('Código do cupom').fill('comunidade') + await dialog.getByLabel('Percentual de desconto').fill('20') + await dialog.getByLabel('Limite de usos').fill('50') + await dialog.getByRole('button', { name: 'Salvar cupom' }).click() + + await expect(page.getByText('Cupom COMUNIDADE salvo.')).toBeVisible() + expect(bodies[0]).toMatchObject({ code: 'COMUNIDADE', kind: 'percent', value: 20, max_uses: 50 }) + }) + + test('o financeiro vê os ingressos, mas não muda nada', async ({ page, goto }) => { + await open(page, goto, 'financeiro', true) + + await expect(page.getByRole('row', { name: /1º lote/ })).toBeVisible() + await expect(page.getByRole('button', { name: 'Novo tipo de ingresso' })).toHaveCount(0) + await expect(page.getByRole('button', { name: 'Editar 1º lote de Inteira' })).toHaveCount(0) + }) +})