Commit Graph

39 Commits

Author SHA1 Message Date
Stephon Brown
5d96a614ba [PM-37820] Update Missing Tax Logic for US Customers (#7719)
* fix(billing): guard US customers from missing tax ID warning when automatic tax flag is enabled

  US has no customer-facing VAT/Tax ID equivalent, so the warning should never appear for US customers regardless of the PM37597 flag state.

* fix(billing): fix provider warnings test asserting buggy US tax ID warning behavior
2026-05-27 11:27:13 -04:00
cyprain-okeke
d07a941896 [PM-37092] feat: Add business plan migration handler to SubscriptionUpdatedHandler (#7707)
* feat(billing): add Organization.ChangePlan extension for structural plan shape

Pure helper that writes plan-derived structural columns (PlanType, Plan,
Use* capability flags, UsersGetPremium, MaxCollections) without touching
customer-purchase columns. Preserves the existing UseKeyConnector carve-out.
Behavior-preserving extraction of the field-copy block at lines 287-310
of UpgradeOrganizationPlanCommand.UpgradePlanAsync.

* refactor(billing): use Organization.ChangePlan in UpgradePlanAsync

Replaces the inline structural field-copy block with a call to the new
ChangePlan helper. Customer-purchase columns (Seats, MaxStorageGb,
Enabled, UseSecretsManager) and the PremiumAccessAddon override on
UsersGetPremium stay inline at the call site. Behavior-preserving.

* feat(billing): register Teams 2020 -> current migration paths

Appends Teams2020AnnualToCurrent (byte 3) and Teams2020MonthlyToCurrent
(byte 4) to MigrationPathId and the MigrationPaths registry. Required for
the business migration handler to resolve cohorts mapped to Teams source
plans; without these entries MigrationPaths.FromId returns null and the
handler no-ops on Teams orgs in Cohort A1. Snapshot tests updated.

* chore(billing): inject migration cohort repositories into SubscriptionUpdatedHandler

Adds IOrganizationPlanMigrationCohortRepository and
IOrganizationPlanMigrationCohortAssignmentRepository as constructor
dependencies in preparation for HandleScheduleTriggeredBusinessMigrationAsync.
No behavior change.

* feat(billing): scaffold business plan Phase-2 migration handler

Adds HandleScheduleTriggeredBusinessMigrationAsync as a sibling call in
HandleAsync's organization branch, gated on PM35215_BusinessPlanPriceMigration.
Initial implementation short-circuits when ScheduleId is null. Locks the
no-op behaviour with NoScheduleId + FeatureFlagOff tests. Full handler body
lands in subsequent commits.

* feat(billing): gate business migration handler on registered source price IDs

Builds the source-price allowlist from MigrationPaths.All, using the
seat-vs-non-seat pattern (HasNonSeatBasedPasswordManagerPlan). All four
Track A 2020 plans register automatically. Skips when the previous
subscription items don't include any registered 2020 source price.

* feat(billing): resolve cohort via assignment row for business migration handler

Reads assignment by organization id (DB is source of truth), then resolves
the cohort and migration path. Stripe subscription.Metadata['migration_cohort_id']
remains stamped by PriceIncreaseScheduler for dashboard attribution but is
not consulted by the handler. Skips with a warning when the assignment is
missing, the cohort is missing, or MigrationPathId references an unregistered
path. Idempotent: skips with info-level log when assignment.MigratedDate is
already set, before any further DB reads.

* feat(billing): defensive target-price sanity check for business migration

After resolving the target plan from cohort.MigrationPath.ToPlan, verifies
the current subscription items contain the target's PM price ID (seat-aware).
Skips with a warning on mismatch to protect against operator data errors or
off-path schedule transitions.

* feat(billing): apply plan shape and mark assignment migrated on Phase 2

Completes HandleScheduleTriggeredBusinessMigrationAsync: loads the org,
calls Organization.ChangePlan(targetPlan), persists via ReplaceAsync, and
sets assignment.MigratedDate + RevisionDate before persisting the
assignment. Happy-path coverage for all four Track A pairs (Teams +
Enterprise, monthly + annual). Teams tests assert the UseScim flip - the
load-bearing capability gain for Teams 2020 -> current.

* Add more unit test

* fix: add UTF-8 BOM to .cs files for editorconfig charset compliance

* Add exception handle

* Code refactoring

* Add more unit testing

* Resolve the pr comment
2026-05-27 10:51:44 +00:00
Alex Morask
b1395aafbe [PM-37083] feat: Add per-phase price resolution to UpdateOrganizationSubscriptionCommand (#7695)
* [PM-37083] feat: Add per-phase price resolution to UpdateOrganizationSubscriptionCommand

Resolve source vs. target plan pricing per schedule phase so item changes
target the correct phase-specific price ID. Move cohort metadata onto the
schedule phases themselves to avoid Stripe normalization triggered by
direct subscription metadata updates. Filter the schedule-aware update
path to phases where EndDate > now, and drop the feature-flag gate on
PriceIncreaseScheduler.Release so schedule existence is the gate.

* Add defensive guard for source-priced single-phase migration schedules
2026-05-22 11:32:13 -05:00
cyprain-okeke
761d8d055a [PM-36964] Add per-org migration cohort assignment to the Admin portal (#7681)
* [PM-36949] Add OrganizationPlanMigrationCohort schema and Core domain types

Add the foundation for cohort-based plan migrations:
- Two tables: OrganizationPlanMigrationCohort and OrganizationPlanMigrationCohortAssignment
- Two views and nine stored procedures (four CRUD on cohort, four CRUD plus
  ReadByOrganizationId on assignment)
- Single Migrator script for MSSQL deployment
- Core entities, MigrationPath value object and its registry, and bare repository
  interfaces under Bit.Core.Billing.Organizations.PlanMigration

The cohort table holds the human-managed metadata (name, discount coupons,
MigrationPathId byte) and the assignment table records each organization's
position in the migration lifecycle (scheduled, migrated, churn-mitigated).
Both Update SPs follow the accept-but-don't-assign pattern: immutable columns
(OrganizationId, CohortId, CreatedAt) are parameters but not SET clauses.

* [PM-36949] Add Dapper repositories for plan migration cohort tables

OrganizationPlanMigrationCohortRepository inherits the base Repository<T, TId>
CRUD methods unchanged. OrganizationPlanMigrationCohortAssignmentRepository
also relies on the base for CRUD and adds GetByOrganizationIdAsync which
returns at most one row (the UNIQUE constraint on OrganizationId at the
database layer guarantees this).

* [PM-36949] Add EF Core configurations, repositories, and provider migrations for plan migration cohort tables

- EF models wrap the Core entities; the assignment model exposes nav properties
  for Organization and Cohort so the FK + cascade-delete is inferred by EF.
- EntityTypeConfiguration classes pin ID generation to application code
  (ValueGeneratedNever) and declare the UNIQUE indexes plus the composite
  (CohortId, ScheduledAt, MigratedAt) index.
- Repositories follow the OrganizationInstallationRepository template; the
  assignment repo adds GetByOrganizationIdAsync to mirror the SP exposed on
  the MSSQL side.
- DatabaseContext gets two DbSet properties; auto-discovery picks up the
  configuration classes.
- Generated migrations for MySQL, Postgres, and SQLite create matching schemas;
  EF truncates FK and index names on providers with 64-char identifier limits,
  which is consistent with the rest of the codebase.

* [PM-36949] Wire up DI and add tests for plan migration cohort repositories

Register both Dapper and EF Core repositories in their respective service
collection extensions, following the existing AddSingleton convention in
these files.

Add tests:
- MigrationPathIdsSnapshotTests guards the immortal byte IDs that downstream
  code pins on. The class- and method-level comments document why these
  values can never be renumbered.
- MigrationPathTests covers the FromId round-trip and the null-on-unknown
  behavior the registry promises to callers.
- OrganizationPlanMigrationCohortRepositoryTests exercises CRUD, the UNIQUE
  Name constraint, and verifies that ReplaceAsync ignores CreatedAt
  mutations (per the accept-but-don't-assign Update SP).
- OrganizationPlanMigrationCohortAssignmentRepositoryTests exercises CRUD,
  GetByOrganizationIdAsync, the UNIQUE OrganizationId constraint,
  cascade-delete from both Organization and Cohort, and verifies that
  ReplaceAsync ignores OrganizationId, CohortId, and CreatedAt mutations.

* [PM-36949] Use PlanType and MigrationPathId enums on MigrationPath

Replace the byte Id with a byte-backed MigrationPathId enum and replace
the string FromPlan/ToPlan fields with PlanType. Persistence is
unchanged -- EF normalises enum-backed properties to their underlying
type in the model snapshot, and Dapper handles enum-to-byte parameter
mapping automatically.

* [PM-36949] Add *.lscache to .gitignore

* [PM-36949] fix: Override ReplaceAsync on EF cohort repositories for immutability parity

The Dapper _Update SPs accept-but-don't-assign certain columns (CreatedAt
on cohort; OrganizationId, CohortId, and CreatedAt on assignment), but
the base EF Repository<T,TEntity,Guid>.ReplaceAsync uses SetValues which
writes every scalar. Override on both repos and mark the immutable
properties as IsModified = false so MySQL/Postgres/Sqlite match MSSQL
behavior. Mirrors the existing DeviceRepository.ReplaceAsync pattern.

* [PM-36949] fix: Bound cohort string columns and widen Name to 255 chars

Add [MaxLength] attributes to the three cohort string properties so the
EF providers (MySQL/Postgres/Sqlite) enforce the same limits as MSSQL,
where the columns were already NVARCHAR-capped. Widen Name from 64 to
255 chars across MSSQL DDL, both _Create/_Update SP signatures, the
Migrator script, the entity, and all three regenerated EF migrations.
Coupon codes stay at 64 (Stripe IDs are short).

* [PM-36949] test: Lock FromPlan and ToPlan per MigrationPath

The snapshot test class doc says "byte N means a specific FromPlan ->
ToPlan transition forever", but only the byte value was being asserted.
A silent refactor of the registry's PlanType references would not have
been caught. Add per-path FromPlan/ToPlan assertions to close the gap.

* [PM-36949] chore: Apply dotnet format

* [PM-36949] test: Use LaxDateTimeComparer for round-tripped DateTimes

Postgres timestamp and MySQL datetime(6) store microsecond precision (6
fractional digits), but .NET DateTime is 100ns ticks (7 digits). Exact
Assert.Equal fails by a single tick on round-trip. Switch the three
DateTime comparisons in ReplaceAsync_UpdatesMutableColumns_AndIgnoresImmutableOnes
to LaxDateTimeComparer.Default -- the same 2ms-tolerance comparer used
by SendRepositoryTests and InstallationRepositoryTests for the same
precision issue.

* Add implementation for dropdown

* Reconcile dropdown work with renamed PM-36949 schema

After merging origin/main, the cohort schema now uses *Date suffixes
(ScheduledDate / MigratedDate / ChurnDiscountAppliedDate / CreationDate).
Rename references in the dropdown work, restore IsLocked() on the merged
entity, and re-add GetManyAsync() to the cohort repository (interface +
Dapper + EF) since the merge took main's pre-dropdown versions.

Also remove the six superseded provider migration files (20260515*) -- the
20260518* renames from origin/main are now the only cohort migrations.

* Fix UTF-8 BOM on cohort assignment unit test file

* Resolve the FF and permission issue

* Extract migration cohort resolution into a helper

Addresses PR feedback to keep the Edit action focused: the cohort
resolution/validation now lives in ResolveMigrationCohortAssignmentChangeAsync
and returns a MigrationCohortAssignmentChange record. The endpoint still
owns the page return.

---------

Co-authored-by: Alex Morask <amorask@bitwarden.com>
Co-authored-by: Alex Morask <144709477+amorask-bitwarden@users.noreply.github.com>
2026-05-21 15:17:00 +01:00
Stephon Brown
779320aabe [PM-37598] Update Tax Id Warning Logic with Feature Flag (#7677)
* feat(billing): inject feature service into billing warning queries

* test(billing): add provider tax warning tests for automatic tax flag

* test(billing): add organization tax warning tests for automatic tax flag

* feat(billing): modify provider tax id warning based on automatic tax feature flag

* feat(billing): modify organization tax id warning based on automatic tax feature flag

* refactor(billing): clean up unused usings and file encoding

* test(billing): add tax id verification warnings for providers

* test(billing): add tax id verification warnings for organizations
2026-05-20 10:02:51 -04:00
Stephon Brown
e5419a7662 [PM-37597] Set Automatic Tax and Prevent Tax Exempt Mutations (#7662)
* feat(billing): add feature flag for automatic tax enforcement

* refactor(billing): remove unused SubscriptionUpdateOptionsExtensions

* refactor(billing): inject IFeatureService into billing services and commands

* feat(billing): conditionalize customer tax exemption logic with feature flag

* feat(billing): conditionally enable Stripe automatic tax in OrganizationBillingService

* test(billing): add unit tests for Stripe automatic tax feature flag

* fix(billing): Run dotnet format

* test(Premium): use class-level IFeatureService mock in UpgradePremiumToOrganizationCommandTests

* refactor(billing): consolidate customer return conditions for automatic tax

* refactor(billing): broaden postal code validation for organization creation

* refactor(billing): remove PM37597 feature flag for automatic tax logic

* Revert "refactor(billing): broaden postal code validation for organization creation"

This reverts commit cddbda838c.

* fix(test): remove outdated test
2026-05-19 13:18:06 -05:00
Alex Morask
d009a52f43 [PM-36949] feat: Add OrganizationPlanMigrationCohort and Assignment tables with bare repositories (#7644)
* [PM-36949] Add OrganizationPlanMigrationCohort schema and Core domain types

Add the foundation for cohort-based plan migrations:
- Two tables: OrganizationPlanMigrationCohort and OrganizationPlanMigrationCohortAssignment
- Two views and nine stored procedures (four CRUD on cohort, four CRUD plus
  ReadByOrganizationId on assignment)
- Single Migrator script for MSSQL deployment
- Core entities, MigrationPath value object and its registry, and bare repository
  interfaces under Bit.Core.Billing.Organizations.PlanMigration

The cohort table holds the human-managed metadata (name, discount coupons,
MigrationPathId byte) and the assignment table records each organization's
position in the migration lifecycle (scheduled, migrated, churn-mitigated).
Both Update SPs follow the accept-but-don't-assign pattern: immutable columns
(OrganizationId, CohortId, CreatedAt) are parameters but not SET clauses.

* [PM-36949] Add Dapper repositories for plan migration cohort tables

OrganizationPlanMigrationCohortRepository inherits the base Repository<T, TId>
CRUD methods unchanged. OrganizationPlanMigrationCohortAssignmentRepository
also relies on the base for CRUD and adds GetByOrganizationIdAsync which
returns at most one row (the UNIQUE constraint on OrganizationId at the
database layer guarantees this).

* [PM-36949] Add EF Core configurations, repositories, and provider migrations for plan migration cohort tables

- EF models wrap the Core entities; the assignment model exposes nav properties
  for Organization and Cohort so the FK + cascade-delete is inferred by EF.
- EntityTypeConfiguration classes pin ID generation to application code
  (ValueGeneratedNever) and declare the UNIQUE indexes plus the composite
  (CohortId, ScheduledAt, MigratedAt) index.
- Repositories follow the OrganizationInstallationRepository template; the
  assignment repo adds GetByOrganizationIdAsync to mirror the SP exposed on
  the MSSQL side.
- DatabaseContext gets two DbSet properties; auto-discovery picks up the
  configuration classes.
- Generated migrations for MySQL, Postgres, and SQLite create matching schemas;
  EF truncates FK and index names on providers with 64-char identifier limits,
  which is consistent with the rest of the codebase.

* [PM-36949] Wire up DI and add tests for plan migration cohort repositories

Register both Dapper and EF Core repositories in their respective service
collection extensions, following the existing AddSingleton convention in
these files.

Add tests:
- MigrationPathIdsSnapshotTests guards the immortal byte IDs that downstream
  code pins on. The class- and method-level comments document why these
  values can never be renumbered.
- MigrationPathTests covers the FromId round-trip and the null-on-unknown
  behavior the registry promises to callers.
- OrganizationPlanMigrationCohortRepositoryTests exercises CRUD, the UNIQUE
  Name constraint, and verifies that ReplaceAsync ignores CreatedAt
  mutations (per the accept-but-don't-assign Update SP).
- OrganizationPlanMigrationCohortAssignmentRepositoryTests exercises CRUD,
  GetByOrganizationIdAsync, the UNIQUE OrganizationId constraint,
  cascade-delete from both Organization and Cohort, and verifies that
  ReplaceAsync ignores OrganizationId, CohortId, and CreatedAt mutations.

* [PM-36949] Use PlanType and MigrationPathId enums on MigrationPath

Replace the byte Id with a byte-backed MigrationPathId enum and replace
the string FromPlan/ToPlan fields with PlanType. Persistence is
unchanged -- EF normalises enum-backed properties to their underlying
type in the model snapshot, and Dapper handles enum-to-byte parameter
mapping automatically.

* [PM-36949] Add *.lscache to .gitignore

* [PM-36949] fix: Override ReplaceAsync on EF cohort repositories for immutability parity

The Dapper _Update SPs accept-but-don't-assign certain columns (CreatedAt
on cohort; OrganizationId, CohortId, and CreatedAt on assignment), but
the base EF Repository<T,TEntity,Guid>.ReplaceAsync uses SetValues which
writes every scalar. Override on both repos and mark the immutable
properties as IsModified = false so MySQL/Postgres/Sqlite match MSSQL
behavior. Mirrors the existing DeviceRepository.ReplaceAsync pattern.

* [PM-36949] fix: Bound cohort string columns and widen Name to 255 chars

Add [MaxLength] attributes to the three cohort string properties so the
EF providers (MySQL/Postgres/Sqlite) enforce the same limits as MSSQL,
where the columns were already NVARCHAR-capped. Widen Name from 64 to
255 chars across MSSQL DDL, both _Create/_Update SP signatures, the
Migrator script, the entity, and all three regenerated EF migrations.
Coupon codes stay at 64 (Stripe IDs are short).

* [PM-36949] test: Lock FromPlan and ToPlan per MigrationPath

The snapshot test class doc says "byte N means a specific FromPlan ->
ToPlan transition forever", but only the byte value was being asserted.
A silent refactor of the registry's PlanType references would not have
been caught. Add per-path FromPlan/ToPlan assertions to close the gap.

* [PM-36949] chore: Apply dotnet format

* [PM-36949] test: Use LaxDateTimeComparer for round-tripped DateTimes

Postgres timestamp and MySQL datetime(6) store microsecond precision (6
fractional digits), but .NET DateTime is 100ns ticks (7 digits). Exact
Assert.Equal fails by a single tick on round-trip. Switch the three
DateTime comparisons in ReplaceAsync_UpdatesMutableColumns_AndIgnoresImmutableOnes
to LaxDateTimeComparer.Default -- the same 2ms-tolerance comparer used
by SendRepositoryTests and InstallationRepositoryTests for the same
precision issue.

* [PM-36949] refactor: Rename DateTime columns to Date suffix per naming convention

Addresses PR review feedback. Also tightens DATETIME2(7) / NVARCHAR(N) spacing
per the SQL style guide, drops *.lscache from .gitignore (handled by #7648),
and regenerates EF migrations for MySQL, Postgres, and SQLite.

* Apply dotnet format to regenerated migrations

* [PM-36949] chore: Align NULL/NOT NULL columns in cohort tables
2026-05-18 12:34:55 -05:00
cyprain-okeke
b0dd1c9d16 [PM 34174]Do not show renewal reminder banners to exempt organizations (#7483)
* expose the ExemptFromBillingAutomation to client

* Fix the failing database

* Rename the file to resolve chronological order error

* Renamed the migration file name

* fix the failing database

* Suppress warnings for exempt orgs at the query level

Gate InactiveSubscription and ResellerRenewal warnings inside
GetOrganizationWarningsQuery on Organization.ExemptFromBillingAutomation
instead of plumbing the field through the profile response, view models,
EF queries, and SQL views.

* Add the ExemptFromBillingAutomation property

---------

Co-authored-by: Alex Morask <144709477+amorask-bitwarden@users.noreply.github.com>
2026-05-14 18:22:08 +01:00
Rui Tomé
52d9a9cc88 [PM-35253] Add organization ability UseInviteLinks (#7489)
* Add UseInviteLinks to Organization SQL schema and views

* Add Migrator scripts for UseInviteLinks column and data migration

* Add EF migrations for UseInviteLinks on Organization

* Wire UseInviteLinks through organization domain and repositories

* Add HasInviteLinks plan support and UseInviteLinks license handling

* Expose UseInviteLinks and HasInviteLinks on organization and plan API models

* Update tests for UseInviteLinks and invite-links plan feature

* Update migration script with missing update to Organization_ReadManyByIds

* Move UseInviteLinks column after ExemptFromBillingAutomation

* Bump date on migration scripts
2026-04-30 10:13:50 +01:00
Kyle Denney
2820ecc567 [PM-34813] fix system coupons regression (#7515)
* [PM-34813] fix system coupons regression

refactor customer setup class to split system coupons from discount coupons so that they can be applied systematically
2026-04-22 16:42:44 -05:00
cyprain-okeke
bbc1a315e2 billing/pm-24665/license-file-generation-should-fail-for-unpaid-subscription (#7444)
* Add changes for unpaid subscriptions

* Remove the unpaid status and update the test

* Add changes for premium user

* Fix the lint error

* remove subscriptionInfo and use subscription

* Fix file encoding issue

* SubscriptionLicenseValidator.cs is deleted

* Fix the lint error
2026-04-21 13:58:16 +01:00
Kyle Denney
18525843bb [PM-26043] Fix bug: can't add secrets manager to legacy plans (#7414)
* [PM-26043] refactored AddSecretsManagerSubscriptionCommand

move to billing, fix bug unable to add secrets manager to legacy plan by moving all validation into command and skipping the disabled check

* forgot BillingCommandResult is being deprecated

* cleanup

* add unit test coverage

* one more test

* pr feedback

* forgot to fix in actual code file
2026-04-10 09:46:30 -05:00
Alex Morask
a5052d8d0f fix(billing): skip ended schedule phases when updating storage (#7420) 2026-04-08 09:51:03 -05:00
Alex Morask
aa1aa58190 fix(billing): use top-level ProrationBehavior on schedule updates for immediate storage invoicing (#7410) 2026-04-07 15:09:21 -05:00
Alex Morask
11605dd551 feat(billing): make storage commands schedule-aware for price migration (#7350) 2026-03-31 08:32:03 -05:00
Alex Morask
212a0609c0 [PM-33415] [PM-33418] Fix add-on item proration and Families > Teams/Enterprise upgrade seat count (#7259)
* fix(billing): replace per-change IsStructural with changeset-level ChargeImmediately flag

* fix(billing): set seat quantity when upgrading from non-seat-based to seat-based plan
2026-03-20 09:29:45 -05:00
Kyle Denney
2efacd596d [PM-30101] add multiple coupon support to server preview/purchase (#7229)
* [PM-30101] add multiple coupon support to server preview/purchase

* pr feedback
2026-03-19 09:07:49 -05:00
Stephon Brown
8302509bf9 [PM-31645] Implement Swiss Tax Logic (#7186)
* feat(tax): introduce direct tax country utilities and Switzerland constant

* refactor(tax): use `TaxHelpers.IsDirectTaxCountry` for country checks

* feat(tax): implement customer tax exempt status alignment

* test(tax): add comprehensive unit tests for tax exempt alignment logic

* tests(billing): clarify tests

* fix(billing): run dotnet format

* fix(billing): run dotnet format

* fix(billing): Prevent NullReferenceException when accessing customer country

* test(billing): Add Stripe adapter mocks for AdjustSubscription scenarios

* refactor(billing): apply null-conditional operator for address country access

* feat(billing): update missing tax exemption determinations

* test(billing): add unit tests for tax exemption updates

* fix(billing) run dotnet format

* fix(billing): add nullability

* style(files): normalize file encoding for billing utilities

* refactor(TaxHelpers): simplify tax exempt status determination

* test(Tax): update tax exempt determination tests

* fix(billing): revert postal code validation

* test(billing): update tax exempt tests

* fix(billing): run dotnet format
2026-03-17 14:09:41 -04:00
Alex Morask
ed861d89f8 [PM-32581] Refactor organization subscription update process (#7132)
* chore: add CLAUDE.local.md and .worktrees to gitignore

* feat(billing): add Stripe interval and payment behavior constants and feature flag

* feat(billing): add OrganizationSubscriptionChangeSet model and unit tests

* refactor(billing): rename UpdateOrganizationSubscriptionCommand to BulkUpdateOrganizationSubscriptionsCommand

* feat(billing): add UpdateOrganizationSubscriptionCommand with tests

* feat(billing): use UpdateOrganizationSubscriptionCommand in BulkUpdateOrganizationSubscriptions behind feature flag

* feat(billing): use UpdateOrganizationSubscriptionCommand in SetUpSponsorshipCommand behind feature flag

* feat(billing): add UpgradeOrganizationPlanVNextCommand with tests and feature flag gate

* feat(billing): use UpdateOrganizationSubscriptionCommand in OrganizationService.AdjustSeatsAsync behind feature flag

* feat(billing): use UpdateOrganizationSubscriptionCommand in UpdateSecretsManagerSubscriptionCommand behind feature flag

* feat(billing): use UpdateOrganizationSubscriptionCommand in BillingHelpers.AdjustStorageAsync behind feature flag

* chore: run dotnet format

* fix(billing): missed optional owner in OrganizationBillingService.Finalize after merge

* refactor(billing): address PR feedback on UpdateOrganizationSubscription
2026-03-09 15:37:51 -05:00
cyprain-okeke
153c175ed8 Add coupon support to invoice preview and subscription creation (#6994)
* Add coupon support to invoice preview and subscription creation

* Fix the build lint error

* Resolve the initial review comments

* fix  the failing test

* fix the build lint error

* Fix the failing test

* Resolve the unaddressed issues

* Fixed the deconstruction error

* Fix the lint issue

* Fix the lint error

* Fix the lint error

* Fix the build lint error

* lint error resolved

* remove the setting file

* rename the variable name  validatedCoupon

* Remove the owner property

* Update OrganizationBillingService tests to align with recent refactoring

- Remove GetMetadata tests as method no longer exists
- Remove Owner property references from OrganizationSale (removed in d7613365ed)
- Update coupon validation to use SubscriptionDiscountRepository instead of SubscriptionDiscountService
- Add missing imports for SubscriptionDiscount entities
- Rename test for clarity: Finalize_WithNullOwner_SkipsValidation → Finalize_WithCouponOutsideDateRange_IgnoresCouponAndProceeds

All tests passing (14/14)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix the lint error

* Making the owner non nullable

* fix the failing unit test

* Make the owner nullable

* Fix the bug for coupon in Stripe with no audience restrictions(PM-32756)

* Return validation message for invalid coupon

* Update the valid token message

* Fix the failing unit test

* Remove the duplicate method

* Fix the failing build and test

* Resolve the failing test

* Add delete of invalid coupon

* Add the expired error message

* Delete on invalid coupon in stripe

* Fix the lint errors

* return null if we get exception from stripe

* remove the auto-delete change

* fix the failing test

* Fix the lint build error

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-05 17:08:40 +01:00
Thomas Rittson
e3c392badb [PM-32131] Add UseMyItems organization ability (#7014)
Purpose: UseMyItems is a new organization ability / plan flag
which is automatically enabled where UsePolicies is enabled,
but can be selectively disabled to disable My Items creation
when the Organization Data Ownership policy is turned on.

- new organization table column with all sprocs and views updated
- data migration to enable the feature for all organizations that already use policies (replicating existing behaviour)
- data and api models updated
- added to organization license file so it can be preserved in self-hosted instances
- note that we don't have a plan feature defined for this yet, so it is set based on UsePolicies to match the migration logic. Billing Team have a ticket to add this
2026-02-24 19:52:28 -07:00
Conner Turnbull
12d18ebb2c [PM-27731] Updated organization licenses to save the correct values from the token (#6546)
* Updated organization licenses to save the correct values from the token

* Added additional test cases around licenses

* Added missing properties from Organization to UpdateOrganizationLicenseCommand.UpdateLicenseAsync()

* Add tests to validate license property synchronization pipeline

* `dotnet format`
2026-01-13 09:32:02 -05:00
cd-bitwarden
afd47ad085 [SM-1570] Adding new item to organization license to disable SM ads for users (#6482)
* Adding new item to organization license

* fixing whitespace issues

* fixing missing comment

* fixing merge conflicts

* merge fix

* db merge fixes

* fix

* Updating SM to Sm, and adding more view refreshes

* fixing merge conflicts

* Redoing migration

* Update OrganizationLicense.cs

* Update OrganizationLicense.cs

* fixes

* fixes

* fixing db issues

* fix

* rearranging sql after merge conflicts

* Merge conflicts with dbscripts are fixed, adding missing usedisableSMadsForUsers where needed

* removing incorrect merge fix

* fixes

* adding feature flag to disable sm ads

---------

Co-authored-by: Conner Turnbull <cturnbull@bitwarden.com>
2026-01-07 09:42:10 -07:00
Kyle Denney
99e1326039 [PM-24616] refactor stripe adapter (#6527)
* move billing services+tests to billing namespaces

* reorganized methods in file and added comment headers

* renamed StripeAdapter methods for better clarity

* clean up redundant qualifiers

* Upgrade Stripe.net to v48.4.0

* Update PreviewTaxAmountCommand

* Remove unused UpcomingInvoiceOptionExtensions

* Added SubscriptionExtensions with GetCurrentPeriodEnd

* Update PremiumUserBillingService

* Update OrganizationBillingService

* Update GetOrganizationWarningsQuery

* Update BillingHistoryInfo

* Update SubscriptionInfo

* Remove unused Sql Billing folder

* Update StripeAdapter

* Update StripePaymentService

* Update InvoiceCreatedHandler

* Update PaymentFailedHandler

* Update PaymentSucceededHandler

* Update ProviderEventService

* Update StripeEventUtilityService

* Update SubscriptionDeletedHandler

* Update SubscriptionUpdatedHandler

* Update UpcomingInvoiceHandler

* Update ProviderSubscriptionResponse

* Remove unused Stripe Subscriptions Admin Tool

* Update RemoveOrganizationFromProviderCommand

* Update ProviderBillingService

* Update RemoveOrganizatinoFromProviderCommandTests

* Update PreviewTaxAmountCommandTests

* Update GetCloudOrganizationLicenseQueryTests

* Update GetOrganizationWarningsQueryTests

* Update StripePaymentServiceTests

* Update ProviderBillingControllerTests

* Update ProviderEventServiceTests

* Update SubscriptionDeletedHandlerTests

* Update SubscriptionUpdatedHandlerTests

* Resolve Billing test failures

I completely removed tests for the StripeEventService as they were using a system I setup a while back that read JSON files of the Stripe event structure. I did not anticipate how frequently these structures would change with each API version and the cost of trying to update these specific JSON files to test a very static data retrieval service far outweigh the benefit.

* Resolve Core test failures

* Run dotnet format

* Remove unused provider migration

* Fixed failing tests

* Run dotnet format

* Replace the old webhook secret key with new one (#6223)

* Fix compilation failures in additions

* Run dotnet format

* Bump Stripe API version

* Fix recent addition: CreatePremiumCloudHostedSubscriptionCommand

* Fix new code in main according to Stripe update

* Fix InvoiceExtensions

* Bump SDK version to match API Version

* cleanup

* fixing items missed after the merge

* use expression body for all simple returns

* forgot fixes, format, and pr feedback

* claude pr feedback

* pr feedback and cleanup

* more claude feedback

---------

Co-authored-by: Alex Morask <amorask@bitwarden.com>
Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
2025-12-12 15:32:43 -06:00
Vijay Oommen
599fbc0efd [PM-28616] Add flag UsePhishingBlocker to dbo.Organization (#6625)
* PM-28616 Add flag UsePhishingBlocker to dbo.Organization

* PM-28616 updated as per comments from claude

* PM-28616 updated ToLicense Method to copy the license file

* PM-28616 allow phishing blocker to be imported via license files for self-hosted

* PM-28616 updated PR comments - added more views to be refreshed

* PM-28616 removed proeprty from constructor as it is not used anymore. We have moved to claims based properties
2025-12-01 13:31:36 -05:00
Alex Morask
f595818ede [PM-24549] Remove feature flag: use-pricing-service (#6567)
* Remove feature flag and move StaticStore plans to MockPlans for tests

* Remove old plan models / move sponsored plans out of StaticStore

* Run dotnet format

* Add pricing URI to Development appsettings for local development and integration tests

* Updated Api Integration tests to get current plan type

* Run dotnet format

* Fix failing tests
2025-11-19 09:53:30 -06:00
Alex Morask
691047039b [PM-27849] Check for sm-standalone on subscription (#6545)
* Fix coupon check

* Fixed in FF off scenario

* Run dotnet format
2025-11-11 16:01:48 -06:00
Alex Morask
9c51c9971b [PM-21638] Stripe .NET v48 (#6202)
* Upgrade Stripe.net to v48.4.0

* Update PreviewTaxAmountCommand

* Remove unused UpcomingInvoiceOptionExtensions

* Added SubscriptionExtensions with GetCurrentPeriodEnd

* Update PremiumUserBillingService

* Update OrganizationBillingService

* Update GetOrganizationWarningsQuery

* Update BillingHistoryInfo

* Update SubscriptionInfo

* Remove unused Sql Billing folder

* Update StripeAdapter

* Update StripePaymentService

* Update InvoiceCreatedHandler

* Update PaymentFailedHandler

* Update PaymentSucceededHandler

* Update ProviderEventService

* Update StripeEventUtilityService

* Update SubscriptionDeletedHandler

* Update SubscriptionUpdatedHandler

* Update UpcomingInvoiceHandler

* Update ProviderSubscriptionResponse

* Remove unused Stripe Subscriptions Admin Tool

* Update RemoveOrganizationFromProviderCommand

* Update ProviderBillingService

* Update RemoveOrganizatinoFromProviderCommandTests

* Update PreviewTaxAmountCommandTests

* Update GetCloudOrganizationLicenseQueryTests

* Update GetOrganizationWarningsQueryTests

* Update StripePaymentServiceTests

* Update ProviderBillingControllerTests

* Update ProviderEventServiceTests

* Update SubscriptionDeletedHandlerTests

* Update SubscriptionUpdatedHandlerTests

* Resolve Billing test failures

I completely removed tests for the StripeEventService as they were using a system I setup a while back that read JSON files of the Stripe event structure. I did not anticipate how frequently these structures would change with each API version and the cost of trying to update these specific JSON files to test a very static data retrieval service far outweigh the benefit.

* Resolve Core test failures

* Run dotnet format

* Remove unused provider migration

* Fixed failing tests

* Run dotnet format

* Replace the old webhook secret key with new one (#6223)

* Fix compilation failures in additions

* Run dotnet format

* Bump Stripe API version

* Fix recent addition: CreatePremiumCloudHostedSubscriptionCommand

* Fix new code in main according to Stripe update

* Fix InvoiceExtensions

* Bump SDK version to match API Version

* Fix provider invoice generation validation

* More QA fixes

* Fix tests

* QA defect resolutions

* QA defect resolutions

* Run dotnet format

* Fix tests

---------

Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
2025-10-21 14:07:55 -05:00
Jared McCannon
dbce45291c [PM-26361] Add User Auto Confirmation (#6436)
* Adding AutoConfrim and migrations.

* Add value to Admin Page and update sproc to correct name.

* Correcting license constant.

* Adding feature check back in.

* Fixing sprocs :face_palm:

* Remove Coalesce

* Adding property to plan and model constructor

* Correcting name of column.  Cascading change throughout. Updating response models. Updating sprocs and views. Updating migrations

* fixing sproc

* Fixing up license stuff.

* Updating org view

* Code review changes and renames :face_palm:

* Refershing additional views

* Last two fixes.
2025-10-20 07:27:18 -05:00
Kyle Denney
fedc6b865b [PM-25379] Refactor org metadata (#6441)
* ignore serena

* removing unused properties from org metadata

* removing further properties that can already be fetched on the client side using available data

* new vnext endpoint for org metadata plus caching metadata first pass

including new feature flag

# Conflicts:
#	src/Core/Constants.cs

* [PM-25379] decided against cache and new query shouldn't use the service

* pr feedback

removing unneeded response model

* run dotnet format
2025-10-13 10:49:55 -05:00
Kyle Denney
3272586e31 Revert "[PM-25379] Refactor org metadata (#6418)" (#6439)
This reverts commit 3bef57259d.
2025-10-10 09:06:58 -05:00
Alex Morask
c9970a0782 Resolve tax estimation for Families scenarios (#6437) 2025-10-10 08:19:45 -05:00
Kyle Denney
3bef57259d [PM-25379] Refactor org metadata (#6418)
* ignore serena

* removing unused properties from org metadata

* removing further properties that can already be fetched on the client side using available data

* new vnext endpoint for org metadata plus caching metadata first pass

including new feature flag

# Conflicts:
#	src/Core/Constants.cs

* [PM-25379] decided against cache and new query shouldn't use the service

* pr feedback

removing unneeded response model

* run dotnet format
2025-10-09 15:50:07 -05:00
Alex Morask
34f5ffd981 [PM-26692] Count unverified setup intent as payment method during organization subscription creation (#6433)
* Updated check that determines whether org has payment method to include bank account when determining how to set trial_settings

* Run dotnet format
2025-10-09 13:20:28 -05:00
Alex Morask
61265c7533 [PM-25463] Work towards complete usage of Payments domain (#6363)
* Use payment domain

* Run dotnet format and remove unused code

* Fix swagger

* Stephon's feedback

* Run dotnet format
2025-10-01 10:26:39 -05:00
Alex Morask
14b307c15b [PM-25205] Don't respond with a tax ID warning for US customers (#6310)
* Don't respond with a Tax ID warning for US customers

* Only show provider tax ID warning for non-US based providers
2025-09-19 10:26:22 -05:00
Alex Morask
3dd5accb56 [PM-24964] Stripe-hosted bank account verification (#6263)
* Implement bank account hosted URL verification with webhook handling notification

* Fix tests

* Run dotnet format

* Remove unused VerifyBankAccount operation

* Stephon's feedback

* Removing unused test

* TEMP: Add logging for deployment check

* Run dotnet format

* fix test

* Revert "fix test"

This reverts commit b8743ab3b5.

* Revert "Run dotnet format"

This reverts commit 5c861b0b72.

* Revert "TEMP: Add logging for deployment check"

This reverts commit 0a88acd6a1.

* Resolve GetPaymentMethodQuery order of operations
2025-09-09 12:22:42 -05:00
Alex Morask
bd133b936c [PM-22145] Tax ID notifications for Organizations and Providers (#6185)
* Add TaxRegistrationsListAsync to StripeAdapter

* Update GetOrganizationWarningsQuery, add GetProviderWarningsQuery to support tax ID warning

* Add feature flag to control web display

* Run dotnet format'
2025-08-18 09:42:51 -05:00
Alex Morask
2d1f914eae [PM-24067] Check for unverified bank account in free trial / inactive subscription warning (#6117)
* [NO LOGIC] Move query to core

* Check for unverified bank account in free trial and inactive subscription warnings

* Run dotnet format

* fix test

* Run dotnet format

* Remove errant file
2025-07-24 09:59:23 -05:00