Skip to content

Commit

Permalink
(BSR)[API] fix: flush the deposit manually after object creation
Browse files Browse the repository at this point in the history
A database object should be manually flushed if the business logic
depends on a field that is populated by the server, like the creation
date. Furthermore, relying on autoflush is a bad practice because some
routes disable it in order to have more control on the SQLAlchemy session.
  • Loading branch information
dnguyen1-pass committed Jul 23, 2024
1 parent 05cbc24 commit b281ddc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/src/pcapi/core/finance/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2605,6 +2605,7 @@ def create_deposit(
expirationDate=granted_deposit.expiration_date,
)
db.session.add(deposit)
db.session.flush()

# Edge-cases: Validation of the registration occurred over a birthday
# Then we need to add recredit to compensate
Expand Down
21 changes: 21 additions & 0 deletions api/tests/core/finance/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3621,6 +3621,27 @@ def test_create_underage_deposit_and_recredit_sum_of_15_17(self, age, expected_a
assert deposit.amount == expected_amount
assert deposit.user.id == beneficiary.id

def test_create_underage_deposit_with_birthday_since_registration(self):
sixteen_years_ago = datetime.datetime.utcnow() - relativedelta(years=16)
beneficiary = users_factories.UserFactory(validatedBirthDate=sixteen_years_ago.date())
fraud_factories.BeneficiaryFraudCheckFactory(
user=beneficiary,
status=fraud_models.FraudCheckStatus.OK,
type=fraud_models.FraudCheckType.EDUCONNECT,
eligibilityType=users_models.EligibilityType.UNDERAGE,
resultContent=fraud_factories.EduconnectContentFactory(
registration_datetime=datetime.datetime.utcnow() - relativedelta(days=1)
),
)

with db.session.no_autoflush:
deposit = api.create_deposit(
beneficiary, "created by test", beneficiary.eligibility, age_at_registration=15
)

assert deposit.type == models.DepositType.GRANT_15_17
assert deposit.amount == Decimal(20 + 30)

@time_machine.travel("2022-09-05 09:00:00")
def test_create_18_years_old_deposit(self):
beneficiary = users_factories.UserFactory()
Expand Down

0 comments on commit b281ddc

Please sign in to comment.