Blocklist de terapeutas — Plano de implementação

TLDR: criar o model TherapistBlock gerenciado no Avo e plugar a checagem User#blocked? nos pontos existentes de busca, publicação, pedido e resgate de voucher.

Spec: .project/docs/specs/20261005143542_therapist_blocklist.md Branch: feat/therapist-blocklist

Arquitetura: um model novo (TherapistBlock) com scope active e um use case orquestrador (TherapistBlocks::Apply) que só chama peças existentes: Meetings::Cancel com user: nil e SearchTherapists::RefreshByProfile. Os bloqueios de comportamento são uma linha em cada validação já existente.

Stack: Rails 8, Ucasy, Avo 3, RSpec + FactoryBot.

Restrições globais

  • TDD: teste antes da implementação, triple-A (# arrange, # act, # assert), sem let nos testes novos.
  • Request specs sem mock.
  • Rodar testes com make run.test path=<path> e lint com make run.lint.
  • Código e comentários em inglês; mensagens ao usuário em português com acentuação real.
  • Commits de uma linha, até 60 caracteres, sem co-author.

Task 1: Model TherapistBlock + User#blocked?

Files: - Create: db/migrate/20261005150000_create_therapist_blocks.rb - Create: app/models/therapist_block.rb - Create: spec/factories/therapist_blocks.rb - Create: spec/models/therapist_block_spec.rb - Create: spec/models/user_blocked_spec.rb - Modify: app/models/user.rb

Interfaces: - Produces: - TherapistBlock::CANCEL_REASON, TherapistBlock.active, #active?, #blocked_message, #future_meetings, #canceled_meetings, #meetings_cancel? - User#therapist_blocks, User#active_therapist_block, User#blocked? - factory :therapist_block com traits :unlimited, :expired, :cancel_meetings

Os callbacks after_*_commit entram na Task 4. Nesta task o model ainda não tem callbacks.

  • [ ] Step 1: Migration

```ruby class CreateTherapistBlocks < ActiveRecord::Migration[8.1] def change create_table :therapist_blocks do |t| t.references :user, null: false, foreign_key: true t.references :created_by, foreign_key: {to_table: :admin_users} t.text :reason, null: false t.datetime :expires_at t.integer :future_meetings_action, null: false, default: 0

  t.timestamps
end

add_index :therapist_blocks, [:user_id, :expires_at]   end end ```

bash make run.migrate

  • [ ] Step 2: Factory

```ruby FactoryBot.define do factory :therapist_block do user { association :user, person_type: :professional } reason { “Suspensão administrativa” } expires_at { 90.days.from_now } future_meetings_action { :keep }

trait :unlimited do
  expires_at { nil }
end

trait :expired do
  after(:create) { |block| block.update_column(:expires_at, 1.day.ago) } # rubocop:disable Rails/SkipsModelValidations
end

trait :cancel_meetings do
  future_meetings_action { :cancel }
end   end end ```
  • [ ] Step 3: Write the failing tests

spec/models/therapist_block_spec.rb:

```ruby describe TherapistBlock do describe “validations” do context “when reason is missing” do it “is invalid” do # arrange block = build(:therapist_block, reason: nil)

    # act
    result = block.valid?

    # assert
    expect(result).to be false
    expect(block.errors[:reason]).to include("não pode ficar em branco")
  end
end

context "when expires_at is in the past" do
  it "is invalid" do
    # arrange
    block = build(:therapist_block, expires_at: 1.day.ago)

    # act
    result = block.valid?

    # assert
    expect(result).to be false
    expect(block.errors[:expires_at]).to include("precisa ser no futuro")
  end
end

context "when user is a patient" do
  it "is invalid" do
    # arrange
    block = build(:therapist_block, user: create(:user, person_type: :patient))

    # act
    result = block.valid?

    # assert
    expect(result).to be false
    expect(block.errors[:user]).to include("precisa ser um profissional")
  end
end

context "when user already has an active block" do
  it "is invalid" do
    # arrange
    existing = create(:therapist_block)
    block = build(:therapist_block, user: existing.user)

    # act
    result = block.valid?

    # assert
    expect(result).to be false
    expect(block.errors[:user]).to include("já possui um bloqueio ativo")
  end
end

context "when user only has an expired block" do
  it "is valid" do
    # arrange
    existing = create(:therapist_block, :expired)
    block = build(:therapist_block, user: existing.user)

    # act
    result = block.valid?

    # assert
    expect(result).to be true
  end
end   end

describe “.active” do it “returns unlimited and future blocks only” do # arrange unlimited = create(:therapist_block, :unlimited) future = create(:therapist_block) expired = create(:therapist_block, :expired)

  # act
  result = described_class.active

  # assert
  expect(result).to include(unlimited, future)
  expect(result).not_to include(expired)
end   end

describe “#blocked_message” do context “when block has expires_at” do it “returns the message with the date” do # arrange block = build(:therapist_block, expires_at: Time.zone.parse(“2027-01-05 10:00”))

    # act
    result = block.blocked_message

    # assert
    expect(result).to eq("Seu perfil está bloqueado até 05/01/2027. Entre em contato com o suporte.")
  end
end

context "when block is unlimited" do
  it "returns the indefinite message" do
    # arrange
    block = build(:therapist_block, :unlimited)

    # act
    result = block.blocked_message

    # assert
    expect(result).to eq("Seu perfil está bloqueado por tempo indeterminado. Entre em contato com o suporte.")
  end
end   end end ```

spec/models/user_blocked_spec.rb:

```ruby describe User do describe “#blocked?” do context “when user has an active block” do it “returns true” do # arrange block = create(:therapist_block)

    # act
    result = block.user.blocked?

    # assert
    expect(result).to be true
  end
end

context "when user has an unlimited block" do
  it "returns true" do
    # arrange
    block = create(:therapist_block, :unlimited)

    # act
    result = block.user.blocked?

    # assert
    expect(result).to be true
  end
end

context "when user block is expired" do
  it "returns false" do
    # arrange
    block = create(:therapist_block, :expired)

    # act
    result = block.user.reload.blocked?

    # assert
    expect(result).to be false
  end
end

context "when user has no block" do
  it "returns false" do
    # arrange
    user = create(:user)

    # act
    result = user.blocked?

    # assert
    expect(result).to be false
  end
end   end end ```
  • [ ] Step 4: Run to verify it fails

bash make run.test path="spec/models/therapist_block_spec.rb spec/models/user_blocked_spec.rb"

Expected: FAIL — uninitialized constant TherapistBlock

  • [ ] Step 5: Implementation

app/models/therapist_block.rb:

```ruby class TherapistBlock < ApplicationRecord include RansackableAttrs

CANCEL_REASON = “Sistema: Cancelada por bloqueio da terapeuta.”

belongs_to :user belongs_to :created_by, class_name: “AdminUser”, optional: true

enum :future_meetings_action, {keep: 0, cancel: 1}, prefix: :meetings

scope :active, -> { where(expires_at: nil).or(where(expires_at: Time.current..)) }

validates :reason, presence: true validate :expires_at_in_the_future, if: -> { expires_at.present? && expires_at_changed? } validate :user_is_professional, if: -> { user.present? } validate :single_active_block_per_user, if: -> { user.present? && active? }

def active? = expires_at.nil?   expires_at >= Time.current

def blocked_message period = expires_at ? “até #{expires_at.strftime(“%d/%m/%Y”)}” : “por tempo indeterminado”

"Seu perfil está bloqueado #{period}. Entre em contato com o suporte."   end

def future_meetings Meeting.with_participant(user).unavailable_statuses.where(start_at: Time.current..) end

def canceled_meetings Meeting.with_participant(user).canceled.where(cancel_reason: CANCEL_REASON) end

private

def expires_at_in_the_future errors.add(:expires_at, “precisa ser no futuro”) if expires_at < Time.current end

def user_is_professional errors.add(:user, “precisa ser um profissional”) unless user.professional? end

def single_active_block_per_user return unless self.class.active.where(user_id:).where.not(id:).exists?

errors.add(:user, "já possui um bloqueio ativo")   end end ```

app/models/user.rb (perto dos outros has_many):

ruby has_many :therapist_blocks, dependent: :destroy

E perto de onboarding_already_been_approved?:

```ruby def active_therapist_block therapist_blocks.active.order(created_at: :desc).first end

def blocked? = active_therapist_block.present? ```

  • [ ] Step 6: Run to verify it passes

bash make run.test path="spec/models/therapist_block_spec.rb spec/models/user_blocked_spec.rb"

Expected: PASS

  • [ ] Step 7: Commit

bash git add db/migrate db/schema.rb app/models/therapist_block.rb app/models/user.rb spec/factories/therapist_blocks.rb spec/models/therapist_block_spec.rb spec/models/user_blocked_spec.rb git commit -m "feat: add TherapistBlock model"


Task 2: Agenda, busca e pro bono

Files: - Modify: app/use_cases/search_therapists/update_by_profile.rb - Test: spec/use_cases/search_therapists/update_by_profile_spec.rb

Interfaces: - Consumes: User#blocked? (Task 1)

  • [ ] Step 1: Write the failing test (novo context dentro de describe "#call", reaproveitando o helper setup_approved_onboarding do arquivo)

```ruby context “when PRO user is blocked” do it “removes the SearchTherapist record” do # arrange pro_plan = SubscriptionPlan.pro || create(:subscription_plan, slug: “pro”) profile = create(:user_profile, :published) user = profile.user create(:subscription, user: user, subscription_plan: pro_plan, status: :active) create(:availability, user: user) setup_approved_onboarding(user) described_class.call(profile) create(:therapist_block, user: user)

      # act
      described_class.call(profile.reload)

      # assert
      expect(SearchTherapist.exists?(profile_id: profile.id)).to be false
    end
  end

  context "when PRO user block is expired" do
    it "creates the SearchTherapist record" do
      # arrange
      pro_plan = SubscriptionPlan.pro || create(:subscription_plan, slug: "pro")
      profile = create(:user_profile, :published)
      user = profile.user
      create(:subscription, user: user, subscription_plan: pro_plan, status: :active)
      setup_approved_onboarding(user)
      create(:therapist_block, :expired, user: user)
      # simulates the therapist republishing after the block expired (Task 4 unpublishes on block creation)
      profile.update_columns(published: true, published_at: Time.current) # rubocop:disable Rails/SkipsModelValidations

      # act
      described_class.call(profile.reload)

      # assert
      expect(SearchTherapist.exists?(profile_id: profile.id)).to be true
    end
  end ```
  • [ ] Step 2: Run to verify it fails

bash make run.test path=spec/use_cases/search_therapists/update_by_profile_spec.rb

Expected: FAIL — expected false, got true em “when PRO user is blocked”

  • [ ] Step 3: Implementation em #valid?, logo após a checagem de onboarding:

ruby return false if user.blocked?

  • [ ] Step 4: Run to verify it passes

bash make run.test path=spec/use_cases/search_therapists/update_by_profile_spec.rb

Expected: PASS

  • [ ] Step 5: Commit

bash git add app/use_cases/search_therapists/update_by_profile.rb spec/use_cases/search_therapists/update_by_profile_spec.rb git commit -m "feat: hide blocked therapists from search"


Task 3: Bloquear a publicação do perfil

Files: - Modify: app/models/user_profile.rb - Test: spec/models/user_profile_spec.rb - Create: spec/requests/api/v1/user_profiles_update_blocked_spec.rb

Interfaces: - Consumes: User#blocked?, User#active_therapist_block, TherapistBlock#blocked_message (Task 1)

  • [ ] Step 1: Write the failing tests

Em spec/models/user_profile_spec.rb, novo describe:

```ruby describe “publishing a blocked therapist” do context “when therapist has an active block” do it “does not publish and returns the blocked message” do # arrange profile = create(:user_profile, :unpublished) create(:therapist_block, :unlimited, user: profile.user)

    # act
    result = profile.update(published: true)

    # assert
    expect(result).to be false
    expect(profile.errors[:base]).to include("Seu perfil está bloqueado por tempo indeterminado. Entre em contato com o suporte.")
  end
end

context "when therapist is published and blocked" do
  it "allows unpublishing" do
    # arrange
    profile = create(:user_profile, :published)
    create(:therapist_block, user: profile.user)

    # act
    result = profile.update(published: false)

    # assert
    expect(result).to be true
  end
end   end ```

spec/requests/api/v1/user_profiles_update_blocked_spec.rb (sem mock):

```ruby describe “Update user profile when therapist is blocked” do include_context “when professional is logged in”

it “returns unprocessable entity with the blocked message” do # arrange current_user_profile.update_columns(published: false, published_at: nil) # rubocop:disable Rails/SkipsModelValidations create(:therapist_block, user: current_user, expires_at: Time.zone.parse(“2099-01-05 10:00”))

# act
logged_put(api_v1_profile_path, params: {user_profile: {published: true}})

# assert
expect(response).to have_http_status(:unprocessable_entity)
expect(json_body[:errors][:base]).to eq(["Seu perfil está bloqueado até 05/01/2099. Entre em contato com o suporte."])   end end ```
  • [ ] Step 2: Run to verify it fails

bash make run.test path="spec/models/user_profile_spec.rb spec/requests/api/v1/user_profiles_update_blocked_spec.rb"

Expected: FAIL — expected false, got true e expected 422, got 200

  • [ ] Step 3: Implementation no topo de can_publish_unpublish_profile:

```ruby def can_publish_unpublish_profile if published? && user.blocked? errors.add(:base, user.active_therapist_block.blocked_message) return end

return if published_was # If already published, can unpublish ```

Usar :base porque o ResponseJson usa full_message, que prefixaria o nome do atributo em :published.

  • [ ] Step 4: Run to verify it passes

bash make run.test path="spec/models/user_profile_spec.rb spec/requests/api/v1/user_profiles_update_blocked_spec.rb"

Expected: PASS

  • [ ] Step 5: Commit

bash git add app/models/user_profile.rb spec/models/user_profile_spec.rb spec/requests/api/v1/user_profiles_update_blocked_spec.rb git commit -m "feat: refuse publishing blocked therapist profile"


Task 4: Aplicar o bloqueio (TherapistBlocks::Apply) + callbacks

Files: - Create: app/use_cases/therapist_blocks/apply.rb - Modify: app/models/therapist_block.rb - Create: spec/use_cases/therapist_blocks/apply_spec.rb

Interfaces: - Consumes: TherapistBlock#future_meetings, #meetings_cancel?, CANCEL_REASON (Task 1); Meetings::Cancel, SearchTherapists::RefreshByProfile, SearchTherapists::EnqueueRefreshByProfile (existentes) - Produces: TherapistBlocks::Apply.call(therapist_block:)

  • [ ] Step 1: Write the failing tests

```ruby module TherapistBlocks describe Apply do describe “#call” do context “when block is created” do it “unpublishes the therapist profile” do # arrange profile = create(:user_profile, :published)

      # act
      create(:therapist_block, user: profile.user)

      # assert
      expect(profile.reload.published).to be false
      expect(profile.published_at).to be_nil
    end
  end

  context "when future_meetings_action is keep" do
    it "keeps future meetings scheduled" do
      # arrange
      professional = create(:user_profile).user
      meeting = create(:scheduled_meeting, user_client: create(:user_client, professional:))
      create(:meeting_professional, meeting:, user: professional)

      # act
      create(:therapist_block, user: professional)

      # assert
      expect(meeting.reload.status).to eq("scheduled")
    end
  end

  context "when future_meetings_action is cancel" do
    it "cancels future pending and scheduled meetings without voucher" do
      # arrange
      professional = create(:user_profile).user
      user_client = create(:user_client, professional:)
      scheduled = create(:scheduled_meeting, user_client:)
      pending = create(:pending_meeting, user_client:)
      create(:meeting_professional, meeting: scheduled, user: professional)
      create(:meeting_professional, meeting: pending, user: professional)

      # act
      create(:therapist_block, :cancel_meetings, user: professional)

      # assert
      expect(scheduled.reload.status).to eq("canceled")
      expect(pending.reload.status).to eq("canceled")
      expect(scheduled.cancel_reason).to eq(TherapistBlock::CANCEL_REASON)
      expect(Voucher.where(meeting: [scheduled, pending])).to be_empty
    end

    it "does not touch finished meetings or other therapists meetings" do
      # arrange
      professional = create(:user_profile).user
      other_professional = create(:user_profile).user
      finished = create(:meeting, status: :finished, user_client: create(:user_client, professional:))
      other = create(:scheduled_meeting, user_client: create(:user_client, professional: other_professional))
      create(:meeting_professional, meeting: finished, user: professional)
      create(:meeting_professional, meeting: other, user: other_professional)

      # act
      create(:therapist_block, :cancel_meetings, user: professional)

      # assert
      expect(finished.reload.status).to eq("finished")
      expect(other.reload.status).to eq("scheduled")
    end

    it "lists canceled meetings on the block" do
      # arrange
      professional = create(:user_profile).user
      meeting = create(:scheduled_meeting, user_client: create(:user_client, professional:))
      create(:meeting_professional, meeting:, user: professional)

      # act
      block = create(:therapist_block, :cancel_meetings, user: professional)

      # assert
      expect(block.canceled_meetings).to contain_exactly(meeting)
    end
  end
end   end end ```
  • [ ] Step 2: Run to verify it fails

bash make run.test path=spec/use_cases/therapist_blocks/apply_spec.rb

Expected: FAIL — expected false, got true (perfil continua publicado) e sessões continuam scheduled

  • [ ] Step 3: Implementation

app/use_cases/therapist_blocks/apply.rb:

```ruby module TherapistBlocks class Apply < UseCaseBase required_attributes(:therapist_block)

def call
  unpublish_profile
  cancel_future_meetings if context.therapist_block.meetings_cancel?

  SearchTherapists::RefreshByProfile.call(context.therapist_block.user_id)
end

private

def unpublish_profile
  context.therapist_block.user.profile&.update_columns(published: false, published_at: nil) # rubocop:disable Rails/SkipsModelValidations
end

def cancel_future_meetings
  context.therapist_block.future_meetings.find_each do |meeting|
    Meetings::Cancel.call(meeting:, user: nil, cancel_reason: TherapistBlock::CANCEL_REASON)
  end
end   end end ```

update_columns evita as validações e callbacks do perfil. O refresh é feito explicitamente em seguida, de forma síncrona, para a agenda fechar na hora.

Em app/models/therapist_block.rb, depois das validações:

ruby after_create_commit -> { TherapistBlocks::Apply.call(therapist_block: self) } after_update_commit :refresh_search_therapist after_destroy_commit :refresh_search_therapist

E no bloco private:

ruby def refresh_search_therapist SearchTherapists::EnqueueRefreshByProfile.call(user_id) end

  • [ ] Step 4: Run to verify it passes

bash make run.test path="spec/use_cases/therapist_blocks/apply_spec.rb spec/models/therapist_block_spec.rb spec/models/user_blocked_spec.rb"

Expected: PASS

  • [ ] Step 5: Commit

bash git add app/use_cases/therapist_blocks/apply.rb app/models/therapist_block.rb spec/use_cases/therapist_blocks/apply_spec.rb git commit -m "feat: apply therapist block on creation"


Task 5: Barrar pedido novo com terapeuta bloqueada

Files: - Modify: app/use_cases/orders/create_by_user_validation.rb - Modify: spec/use_cases/orders/create_by_user_validation_spec.rb

Interfaces: - Consumes: User#blocked? (Task 1)

  • [ ] Step 1: Write the failing test

O spec existente usa instance_double(User) para o profissional. Primeiro ajustar o let para instance_double(User, blocked?: false), sem mudar comportamento. Depois adicionar:

```ruby context “when professional is blocked” do it “is not valid” do # arrange blocked = create(:therapist_block) patient = create(:user_profile).user validation = described_class.new( user: patient, professional: blocked.user, calculated_price: {quantity: 1, unit_price: 100, calculation_basis: :normal}, order_params: {meetings_attributes: [], payment_method: “credit_card”} )

    # act
    result = validation.valid?

    # assert
    expect(result).to be false
    expect(validation.errors[:base]).to include("Este terapeuta não está disponível para agendamentos no momento.")
  end
end ```
  • [ ] Step 2: Run to verify it fails

bash make run.test path=spec/use_cases/orders/create_by_user_validation_spec.rb

Expected: FAIL — mensagem não incluída em errors[:base]

  • [ ] Step 3: Implementation

Adicionar :check_professional_not_blocked! na lista do validate e:

```ruby def check_professional_not_blocked! return unless professional&.blocked?

  errors.add(:base, "Este terapeuta não está disponível para agendamentos no momento.")
end ```
  • [ ] Step 4: Run to verify it passes

bash make run.test path=spec/use_cases/orders/create_by_user_validation_spec.rb

Expected: PASS

  • [ ] Step 5: Commit

bash git add app/use_cases/orders/create_by_user_validation.rb spec/use_cases/orders/create_by_user_validation_spec.rb git commit -m "feat: refuse orders for blocked therapists"


Task 6: Resgate de voucher (API barra, Avo passa)

Files: - Modify: app/use_cases/vouchers/redeem_validation.rb - Modify: app/use_cases/vouchers/redeem.rb - Modify: app/avo/actions/meetings/reschedule.rb - Create: spec/use_cases/vouchers/redeem_validation_spec.rb - Create: spec/requests/api/v1/voucher_redemptions_create_blocked_spec.rb - Modify: spec/avo/actions/meetings/reschedule_spec.rb

Interfaces: - Consumes: User#blocked? (Task 1); Vouchers::RedeemFlow (existente) - Produces: Vouchers::RedeemFlow.call(..., by_admin: true) ignora o bloqueio

  • [ ] Step 1: Write the failing tests

spec/use_cases/vouchers/redeem_validation_spec.rb:

```ruby module Vouchers describe RedeemValidation do context “when professional is blocked” do it “is not valid” do # arrange professional = create(:user_profile).user meeting = create(:canceled_meeting, user_client: create(:user_client, professional:)) voucher = create(:voucher, meeting:) create(:therapist_block, user: professional) start_at = 3.days.from_now validation = described_class.new(voucher:, date: start_at.to_date.to_s, hour: “14”)

    # act
    result = validation.valid?

    # assert
    expect(result).to be false
    expect(validation.errors[:base]).to include("Este terapeuta não está disponível para agendamentos no momento.")
  end
end

context "when professional is blocked and redeemed by admin" do
  it "is valid" do
    # arrange
    professional = create(:user_profile).user
    meeting = create(:canceled_meeting, user_client: create(:user_client, professional:))
    voucher = create(:voucher, meeting:)
    create(:therapist_block, user: professional)
    start_at = 3.days.from_now
    validation = described_class.new(voucher:, date: start_at.to_date.to_s, hour: "14", by_admin: true)

    # act
    result = validation.valid?

    # assert
    expect(result).to be true
  end
end   end end ```

spec/requests/api/v1/voucher_redemptions_create_blocked_spec.rb (sem mock):

```ruby describe “Redeem voucher when therapist is blocked” do include_context “when patient is logged in with professional”

it “returns unprocessable entity” do # arrange meeting = create(:meeting_with_order, owner: current_user, user_client: create(:user_client, patient: current_user, professional: current_professional)) voucher = create(:voucher, meeting:) create(:therapist_block, user: current_professional) start_at = 3.days.from_now

# act
logged_post(api_v1_voucher_redemptions_path(voucher.pid),
  params: {voucher: {date: start_at.strftime("%Y-%m-%d"), hour: "14"}})

# assert
expect(response).to have_http_status(:unprocessable_entity)
expect(voucher.reload.redeemed_at).to be_nil   end end ```

Em spec/avo/actions/meetings/reschedule_spec.rb, novo exemplo, copiando o arrange do primeiro exemplo do arquivo e adicionando o bloqueio:

```ruby context “when professional is blocked” do it “reschedules the meeting anyway” do # arrange admin_user = create(:admin_user, :developer) professional = create(:user_profile).user patient = create(:user_profile).user user_client = create(:user_client, professional:, patient:) meeting = create(:scheduled_meeting, user_client:, start_at: 2.days.from_now) create(:meeting_patient, meeting:, user: patient) create(:meeting_professional, meeting:, user: professional) create(:therapist_block, user: professional) resource = Avo::Resources::Meeting.new.hydrate(record: meeting) action = described_class.new(record: meeting, resource: resource, user: admin_user, view: :show) new_date = 3.days.from_now.to_date.to_s fields = ActionController::Parameters.new({date: new_date, hour: “14”})

    mock_callable_class(Messenger::Sender::SMS)

    # act
    action.handle(current_user: admin_user, fields:, resource:)

    # assert
    expect(meeting.reload.status).to eq("scheduled")
    expect(meeting.start_at.to_date.to_s).to eq(new_date)
  end
end ```

Nesse exemplo, o create(:therapist_block, user: professional) não cancela a sessão, porque o default é keep.

  • [ ] Step 2: Run to verify it fails

bash make run.test path="spec/use_cases/vouchers/redeem_validation_spec.rb spec/requests/api/v1/voucher_redemptions_create_blocked_spec.rb spec/avo/actions/meetings/reschedule_spec.rb"

Expected: FAIL — unknown attribute by_admin / validação passa / request retorna 200. O spec do Avo deve passar já agora: é a regressão que garante o caminho do admin depois da mudança.

  • [ ] Step 3: Implementation

app/use_cases/vouchers/redeem_validation.rb:

```ruby module Vouchers class RedeemValidation < Meetings::DateHourBaseValidation attr_accessor :voucher, :date, :hour, :by_admin

validates :voucher, presence: true

validate :voucher_availability!
validate :check_professional_not_blocked!, unless: :by_admin

def to_context = {redeemed_at: Time.current, start_at:, end_at:}

private

def voucher_availability!
  errors.add(:base, :expired) if voucher.expired?

  @message_error = "Voucher não pôde ser resgatado" if errors.any?
end

def check_professional_not_blocked!
  return unless voucher&.professional&.blocked?

  errors.add(:base, "Este terapeuta não está disponível para agendamentos no momento.")
  @message_error = "Voucher não pôde ser resgatado"
end   end end ```

app/use_cases/vouchers/redeem.rb:

ruby validate(Vouchers::RedeemValidation, :voucher, :date, :hour, :by_admin)

app/avo/actions/meetings/reschedule.rb, na chamada existente:

ruby ucase = Vouchers::RedeemFlow.call( user: meeting.owner, pid: voucher.pid, date: fields[:date].to_s, hour: fields[:hour].to_s, by_admin: true )

  • [ ] Step 4: Run to verify it passes

bash make run.test path="spec/use_cases/vouchers/redeem_validation_spec.rb spec/requests/api/v1/voucher_redemptions_create_blocked_spec.rb spec/avo/actions/meetings/reschedule_spec.rb spec/requests/api/v1/voucher_redemptions_create_spec.rb"

Expected: PASS

  • [ ] Step 5: Commit

bash git add app/use_cases/vouchers app/avo/actions/meetings/reschedule.rb spec/use_cases/vouchers spec/requests/api/v1/voucher_redemptions_create_blocked_spec.rb spec/avo/actions/meetings/reschedule_spec.rb git commit -m "feat: refuse voucher redeem for blocked therapist"


Task 7: Avo — resource, policy, scope e menu

Files: - Create: app/avo/resources/therapist_block.rb - Create: app/controllers/avo/therapist_blocks_controller.rb - Create: app/policies/therapist_block_policy.rb - Create: app/avo/scopes/therapist_blocks/active.rb - Modify: config/initializers/avo.rb - Modify: app/avo/resources/user.rb - Modify: spec/features/avo/resources_index_spec.rb

Interfaces: - Consumes: tudo de TherapistBlock (Tasks 1 e 4)

  • [ ] Step 1: Write the failing test — em spec/features/avo/resources_index_spec.rb, adicionar à lista avo_paths:

ruby "resources/therapist_blocks",

  • [ ] Step 2: Run to verify it fails

bash make run.test path=spec/features/avo/resources_index_spec.rb

Expected: FAIL — rota resources/therapist_blocks não existe

  • [ ] Step 3: Implementation

app/controllers/avo/therapist_blocks_controller.rb:

ruby class Avo::TherapistBlocksController < Avo::ResourcesController end

app/policies/therapist_block_policy.rb:

```ruby class TherapistBlockPolicy < ApplicationPolicy class Scope < Scope def resolve = scope.all end

def authorized_user? = user.developer? || user.manager? alias_method :index?, :authorized_user? alias_method :show?, :authorized_user? alias_method :new?, :authorized_user? alias_method :create?, :authorized_user? alias_method :edit?, :authorized_user? alias_method :update?, :authorized_user? alias_method :destroy?, :authorized_user? alias_method :act_on?, :authorized_user? end ```

app/avo/scopes/therapist_blocks/active.rb:

ruby class Avo::Scopes::TherapistBlocks::Active < Avo::Advanced::Scopes::BaseScope self.name = -> { "Ativos (#{query.active.count})" } self.scope = -> { query.active } self.visible = -> { true } end

app/avo/resources/therapist_block.rb:

```ruby class Avo::Resources::TherapistBlock < Avo::BaseResource CANCEL_WARNING = “Cancelar: as sessões futuras serão canceladas sem voucher. “ \ “Alinhe com o financeiro o estorno manual dos clientes na ZeusPay.”

self.description = “Terapeutas bloqueadas: agenda fechada, fora da busca e perfil despublicado” self.includes = [:user, :created_by] self.model_class = ::TherapistBlock

def fields field :id, as: :id

field :user, as: :belongs_to, name: "Terapeuta",
  required: true,
  searchable: true,
  readonly: -> { view.edit? },
  attach_scope: -> { query.where(person_type: :professional) }

field :reason, as: :textarea, name: "Motivo", required: true

field :expires_at, as: :date_time, name: "Bloqueado até",
  help: "Deixe vazio para bloqueio por tempo indeterminado"

field :future_meetings_action, as: :select, name: "Sessões futuras",
  options: {"Manter" => "keep", "Cancelar (estorno manual)" => "cancel"},
  readonly: -> { view.edit? },
  help: CANCEL_WARNING

field :status, as: :text, name: "Status", hide_on: :forms do
  next "Expirado" unless record.active?

  record.expires_at ? "Ativo até #{record.expires_at.strftime("%d/%m/%Y")}" : "Ativo (indeterminado)"
end

field :created_by_id, as: :hidden, default: -> { current_user.id }, only_on: :new
field :created_by, as: :belongs_to, name: "Criado por", readonly: true, hide_on: :forms

field :canceled_meetings, as: :text, name: "Sessões canceladas (estornar na ZeusPay)",
  only_on: :show, as_html: true,
  visible: -> { resource.record.meetings_cancel? } do
  warning = "<p><strong>#{CANCEL_WARNING}</strong></p>"
  links = record.canceled_meetings.map do |meeting|
    url = Avo::Engine.routes.url_helpers.resources_meeting_path(meeting)
    "<li><a href=\"#{url}\">#{meeting.pid} — #{I18n.l(meeting.start_at, format: :short)}</a></li>"
  end

  "#{warning}<ul>#{links.join}</ul>"
end

field :created_at, as: :date_time, readonly: true, hide_on: :forms   end

def scopes scope Avo::Scopes::TherapistBlocks::Active end end ```

config/initializers/avo.rb, no grupo “Configurações”, depois de therapist_whitelist:

ruby resource :therapist_block if can_manage_whitelist?

app/avo/resources/user.rb, depois de field :subscriptions, as: :has_many:

ruby field :therapist_blocks, as: :has_many, visible: -> { @resource.record.therapist_blocks.exists? }

  • [ ] Step 4: Run to verify it passes

bash make run.test path=spec/features/avo/resources_index_spec.rb

Expected: PASS

Conferência manual no Avo em dev: - criar um bloqueio com Cancelar; - ver o aviso e a lista de sessões no show; - editar o prazo; - apagar o bloqueio.

  • [ ] Step 5: Commit

bash git add app/avo app/controllers/avo/therapist_blocks_controller.rb app/policies/therapist_block_policy.rb config/initializers/avo.rb spec/features/avo/resources_index_spec.rb git commit -m "feat: manage therapist blocks in Avo"


Task 8: Documentação + verificação final

Files: - Create: .project/docs/rules/therapists/therapist_blocklist.md - Modify: .project/docs/RULES.md - Modify: .project/docs/README.md

  • [ ] Step 1: Regra de negócio — .project/docs/rules/therapists/therapist_blocklist.md, no formato das outras regras (frontmatter com id: R-007, certainty: high; corpo em português). Ela registra:
    • os efeitos do bloqueio (agenda, busca, pro bono, publicação, pedido, voucher);
    • que o admin continua podendo reagendar pelo Avo;
    • a expiração (o perfil fica despublicado e ela republica);
    • as opções keep/cancel;
    • o estorno manual pela ZeusPay.
  • [ ] Step 2: Índices — adicionar a linha R-007 em RULES.md e na tabela de regras do README.md, e incluir plans/ na lista de pastas existentes do README.md.
  • [ ] Step 3: Verificação completa

bash make run.lint make run.test

Expected: lint limpo e suíte verde.

  • [ ] Step 4: Commit

bash git add .project/docs git commit -m "docs: add therapist blocklist rule"


Cobertura da spec

Requisito da spec Task
Model, active, mensagens, validações 1
Agenda, busca e pro bono fechados 2
Publicação recusada com 422 em errors.base 3
Despublicar ao bloquear + cancelar sessões (keep/cancel) 4
Pedido novo barrado 5
Resgate de voucher barrado na API e liberado no Avo 6
Reagendamento via API barrado já coberto pela checagem de TherapistAvailableTime existente (Task 2 esvazia os horários)
Avo: resource, aviso de estorno, lista de sessões, filtro de ativos, histórico no usuário 7
Documentação 8