Cancelamento de parcelamento para o nectar-charges — Plano de implementação
TLDR: endpoint
POST /api/v2/financial/cancellations, que cancela no Asaas e depois marca parcelas não pagas ePaymentcomodeleted_or_canceled_by_new_payment.
Spec:
.project/docs/specs/20261026083315_installment_plan_cancellation.mdBranch:feat/CancelChargeService
Arquitetura: um use case Payments::Cancellations::Cancel (Ucasy), com a validação do payload em ParamsValidation, no mesmo molde de refinancings/ e settlements/. Sem status novo, sem tabela de pedidos e sem mudança no webhook: a idempotência vem do status deleted_or_canceled_by_new_payment do Payment.
Stack: Rails, Ucasy, ActiveModel::Serializer, RSpec, Asaas::Client.
Restrições globais
- Sem commits nesta entrega (pedido do usuário).
- Código, nomes e testes em inglês; docs em
.project/docs/em português. - Testes no padrão arrange / act / assert dos specs vizinhos.
- O Postgres de teste precisa estar de pé (porta 5001) para o
bundle exec rspec.
Task 1: Endpoint POST /api/v2/financial/cancellations
Files:
- Modify: config/routes.rb
- Create: app/controllers/api/v2/financial/cancellations_controller.rb
- Create: app/use_cases/payments/cancellations/params_validation.rb
- Create: app/use_cases/payments/cancellations/cancel.rb
- Create: app/serializers/financial/cancellation_serializer.rb
- Test: spec/requests/api/v2/financial/cancellations_spec.rb
Interfaces:
- Consumes: Asaas::Client#cancel_installment_payments(installment_id).
- Produces: Payments::Cancellations::Cancel.call(params) com #response_payload; Financial::CancellationSerializer.
- [ ] Step 1: Write the failing test —
spec/requests/api/v2/financial/cancellations_spec.rbcobrindo:- autenticação: sem header e com token errado → 403;
- sucesso: 200 com
{"provider_payment_plan_id" => "plan_original", "status" => "cancelled", "installments" => [{"provider_installment_id" => "pay_2", "number" => 2}, {"provider_installment_id" => "pay_3", "number" => 3}]}; cancel_installment_paymentschamado com"plan_original";- parcelas
overdue/pendingePaymentemdeleted_or_canceled_by_new_payment, parcelapaidintacta; - repetição com a mesma chave e com chave nova: mesmo corpo, gateway chamado uma vez só;
organization_not_found,original_payment_not_found,invalid_payload(semoperator_email) → 422;- gateway com
errors→ 422gateway_refusedcom a mensagem; gateway levantando exceção → 502gateway_error; nos dois, nada muda no banco.
- [ ] Step 2: Run to verify it fails
bash
bundle exec rspec spec/requests/api/v2/financial/cancellations_spec.rb
Expected: FAIL — undefined local variable or method 'api_v2_financial_cancellations_path'.
- [ ] Step 3: Write minimal implementation
config/routes.rb, no namespace :financial:
ruby
resources :cancellations, only: [:create]
app/controllers/api/v2/financial/cancellations_controller.rb: cópia do SettlementsController, chamando Payments::Cancellations::Cancel, respondendo status: :ok e com:
ruby
def cancellation_params
params.permit(*Payments::Cancellations::ParamsValidation::ATTRIBUTES).to_h.symbolize_keys
end
app/use_cases/payments/cancellations/params_validation.rb:
```ruby module Payments module Cancellations class ParamsValidation < BaseValidation ATTRIBUTES = %i[idempotency_key organization_slug provider_payment_plan_id operator_email].freeze
attr_accessor(*ATTRIBUTES)
validates(*ATTRIBUTES, presence: true)
def message_error = "Payload inválido"
end end end ```
app/use_cases/payments/cancellations/cancel.rb:
```ruby module Payments module Cancellations class Cancel < Ucasy::Base CANCELLABLE_INSTALLMENT_STATUSES = %i[pending overdue].freeze
validate(ParamsValidation, *ParamsValidation::ATTRIBUTES)
attr_reader :response_payload
def call
cancel_payment unless payment.canceled?
@response_payload = Financial::CancellationSerializer.new(payment).as_json.deep_stringify_keys
end
private
# A repeated call finds the payment already cancelled and only answers again: nothing
# changes in the checkout until the gateway accepts.
def cancel_payment
cancel_charges_on_gateway
ActiveRecord::Base.transaction do
payment.installments.where(status: CANCELLABLE_INSTALLMENT_STATUSES).find_each do |installment|
installment.update!(status: :deleted_or_canceled_by_new_payment)
end
payment.update!(status: :deleted_or_canceled_by_new_payment)
end
end
def cancel_charges_on_gateway
response = gateway.cancel_installment_payments(payment.gateway_installment_id)
raise Asaas::RefusedError, gateway_errors(response) if response.try(:[], :errors)
rescue Asaas::RefusedError => e
refuse(:gateway_refused, e.message)
rescue => e
context.fail!(status: :bad_gateway, error: "gateway_error", message: e.message)
end
def organization
@organization ||= Organization.find_by(slug: organization_slug) ||
refuse(:organization_not_found, "Organização não encontrada para o slug informado")
end
def payment
@payment ||= organization.payments.find_by(gateway_installment_id: provider_payment_plan_id) ||
refuse(:original_payment_not_found, "Parcelamento não encontrado nesta organização")
end
def gateway
@gateway ||= Asaas::Client.new(payment.checkout.organization_id)
end
def gateway_errors(response)
Array(response[:errors]).filter_map { |error| error[:description].presence }.join(" ")
.presence || "O gateway recusou a operação"
end
def refuse(error, message)
context.fail!(status: :unprocessable_entity, error: error.to_s, message: message)
end
end end end ```
app/serializers/financial/cancellation_serializer.rb:
```ruby module Financial class CancellationSerializer < ActiveModel::Serializer attributes :provider_payment_plan_id, :status, :installments
def provider_payment_plan_id = object.gateway_installment_id
# Same external name RepaymentService gives to deleted_or_canceled_by_new_payment.
def status = "cancelled"
# Read from the database, so the first call and every retry answer the same list.
def installments
object.installments.where(status: :deleted_or_canceled_by_new_payment).order(:installment_number).map do |installment|
{provider_installment_id: installment.gateway_id, number: installment.installment_number}
end
end end end ```
- [ ] Step 4: Run to verify it passes
bash
bundle exec rspec spec/requests/api/v2/financial && bin/rubocop app/controllers/api/v2/financial app/use_cases/payments/cancellations app/serializers/financial config/routes.rb spec/requests/api/v2/financial
Expected: PASS, sem offenses.
Task 2: Documentação
Files:
- Create: .project/docs/rules/payments/installment_plan_cancellation.md (R-011)
- Modify: .project/docs/README.md (linha R-011 na tabela de regras; spec done quando a suíte passar)
- [ ] Step 1: regra R-011 com: Asaas antes do checkout; reaproveitamento de
deleted_or_canceled_by_new_payment; idempotência pelo status; webhookPAYMENT_DELETEDinalterado. - [ ] Step 2:
bundle exec rspec && bin/rubocop→ PASS.