From fbccafcfe0997f22973781bec6ce83a9349e0009 Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Wed, 30 Sep 2026 09:43:52 +0530 Subject: [PATCH 1/5] allow search facet to read json object fields --- app/features/search/repository.py | 52 ++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/app/features/search/repository.py b/app/features/search/repository.py index 3455f45..181e020 100644 --- a/app/features/search/repository.py +++ b/app/features/search/repository.py @@ -39,12 +39,29 @@ def _string_value(value: Any) -> str | None: return None -def _flatten_projection_values(value: Any) -> list[str]: +def _flatten_projection_values(value: Any, json_path: Any = None) -> list[str]: if value is None: return [] if isinstance(value, list): result: list[str] = [] for item in value: + result.extend(_flatten_projection_values(item, json_path)) + return result + if isinstance(value, dict): + if json_path: + paths = [json_path] if isinstance(json_path, str) else list(json_path) + extracted: list[str] = [] + for p in paths: + sub_val = value.get(p) + if sub_val is not None: + extracted.extend(_flatten_projection_values(sub_val)) + if extracted: + return extracted + direct = _string_value(value) + if direct: + return [direct] + result = [] + for item in value.values(): result.extend(_flatten_projection_values(item)) return result direct = _string_value(value) @@ -290,9 +307,30 @@ class SearchRepository: values.append(row["value_date"].isoformat()) return values - def _project_value(self, raw: Any, strategy: str) -> list[ProjectionValue]: + def _project_value( + self, + raw: Any, + strategy: str, + metadata: dict[str, Any] | None = None, + ) -> list[ProjectionValue]: strategy = strategy.strip().lower() - raw_values = _flatten_projection_values(raw) + json_path = (metadata or {}).get("json_path") or (metadata or {}).get("json_key") + raw_values = _flatten_projection_values(raw, json_path=json_path) + if strategy in ("multivalue", "comma_delimited", "delimited"): + split_values: list[str] = [] + for item in raw_values: + if "," in item or ";" in item: + for token in item.replace(";", ",").split(","): + cleaned = token.strip().rstrip(".").strip() + if cleaned: + cleaned = cleaned[:1].upper() + cleaned[1:] + split_values.append(cleaned) + else: + cleaned = item.strip().rstrip(".").strip() + if cleaned: + cleaned = cleaned[:1].upper() + cleaned[1:] + split_values.append(cleaned) + raw_values = split_values projected: list[ProjectionValue] = [] seen: set[str] = set() for label in raw_values: @@ -406,7 +444,13 @@ class SearchRepository: ) values: list[ProjectionValue] = [] for raw in raw_rows: - values.extend(self._project_value(raw, mapping.mapping_strategy)) + values.extend( + self._project_value( + raw, + mapping.mapping_strategy, + metadata=mapping.metadata, + ) + ) seen: set[str] = set() for value in values: From 23725880e392bd36f9b323914f44b7a0a7d3866f Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Sat, 3 Oct 2026 17:12:16 +0530 Subject: [PATCH 2/5] fix(cart): validate coupons strictly against database and check active/expiry status --- app/features/cart/repository.py | 25 ++++++++++++++++++------- app/features/cart/schema.py | 1 + app/features/cart/service.py | 4 ++-- app/features/payments/pricing.py | 7 ++++--- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/app/features/cart/repository.py b/app/features/cart/repository.py index 8089876..43739a6 100644 --- a/app/features/cart/repository.py +++ b/app/features/cart/repository.py @@ -45,20 +45,31 @@ class CartRepository: items.append(PricingItem(code=plan.code, name=plan.name, category=self._category(plan), price=price)) return items - async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None: - if not code: - return None + async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]: + if not code or not code.strip(): + return None, None + clean_code = code.strip().upper() now = datetime.now(timezone.utc) - coupon = (await self.session.execute(select(Coupon).where(Coupon.code == code.strip().upper(), Coupon.is_active.is_(True), Coupon.start_date <= now, Coupon.end_date >= now))).scalar_one_or_none() + coupon = (await self.session.execute(select(Coupon).where(Coupon.code == clean_code))).scalar_one_or_none() if not coupon: - return None + return None, "Invalid or expired coupon code." + if not coupon.is_active: + return None, "This coupon code is currently inactive." + s_date = coupon.start_date.replace(tzinfo=timezone.utc) if coupon.start_date.tzinfo is None else coupon.start_date + e_date = coupon.end_date.replace(tzinfo=timezone.utc) if coupon.end_date.tzinfo is None else coupon.end_date + if now < s_date: + return None, "This coupon code is not active yet." + if now > e_date: + return None, "Invalid or expired coupon code." + if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit: + return None, "Coupon usage limit reached." metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {} value = Decimal(coupon.value) - if coupon.discount_type == "flat": + if coupon.discount_type in {"flat", "flat_amount"}: currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None if isinstance(currency_values, dict) and currency.upper() in currency_values: value = Decimal(str(currency_values[currency.upper()])) - return PricingCoupon(code=coupon.code, category=coupon.coupon_category, discount_type=coupon.discount_type, value=value, description=coupon.description, max_discount_limit=Decimal(coupon.max_discount_limit)) + return PricingCoupon(code=coupon.code, category=coupon.coupon_category, discount_type=coupon.discount_type, value=value, description=coupon.description, max_discount_limit=Decimal(coupon.max_discount_limit)), None async def get_owned_categories(self, user_id: UUID) -> list[str]: rows = (await self.session.execute(select(UserEntitlement, Module).join(Module, Module.id == UserEntitlement.module_id).where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE))).all() diff --git a/app/features/cart/schema.py b/app/features/cart/schema.py index fb9eb4a..f94048d 100644 --- a/app/features/cart/schema.py +++ b/app/features/cart/schema.py @@ -22,6 +22,7 @@ class CartCalculationResponse(BaseModel): bundle_discount_amount: float coupon_applied: str coupon_discount_amount: float + coupon_error: str | None = None total_discounts: float convenience_fee_rate: float convenience_fee: float diff --git a/app/features/cart/service.py b/app/features/cart/service.py index b8ab883..1538c0a 100644 --- a/app/features/cart/service.py +++ b/app/features/cart/service.py @@ -16,7 +16,7 @@ class CartService: resolved = {i.code.upper() for i in items} missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved] raise ValueError(f"Unknown/inactive plan code or currency mismatch: {', '.join(missing)}") - coupon = await self.repository.get_coupon(request.coupon_code, currency) + coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency) owned = await self.repository.get_owned_categories(user_id) if user_id else request.owned_category_names first = await self.repository.is_first_purchase(user_id) if user_id else request.is_first_purchase - return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first)) + return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first, coupon_error=coupon_error)) diff --git a/app/features/payments/pricing.py b/app/features/payments/pricing.py index 0f32e1e..2afa258 100644 --- a/app/features/payments/pricing.py +++ b/app/features/payments/pricing.py @@ -27,7 +27,7 @@ class PricingCoupon: class PricingEngine: """Preserves the legacy bundle/loyalty/fee rules while sourcing prices from commerce.access_plans.""" - def calculate(self, *, items: list[PricingItem], owned_categories: list[str], coupon: PricingCoupon | None, currency: str, is_first_purchase: bool) -> dict[str, Any]: + def calculate(self, *, items: list[PricingItem], owned_categories: list[str], coupon: PricingCoupon | None, currency: str, is_first_purchase: bool, coupon_error: str | None = None) -> dict[str, Any]: curr = currency.upper() base = sum((item.price for item in items), Decimal("0")) categories = {item.category for item in items} @@ -56,9 +56,9 @@ class PricingEngine: coupon_text = "None" if coupon: coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -") - if coupon.discount_type == "flat": + if coupon.discount_type in {"flat", "flat_amount"}: coupon_discount = min(coupon.value, after_bundle) - elif coupon.discount_type == "percentage": + elif coupon.discount_type in {"percentage", "percent"}: coupon_discount = after_bundle * (coupon.value / Decimal("100")) if coupon.max_discount_limit > 0: coupon_discount = min(coupon_discount, coupon.max_discount_limit) @@ -74,6 +74,7 @@ class PricingEngine: "bundle_discount_amount": float(q(bundle)), "coupon_applied": coupon_text, "coupon_discount_amount": float(q(coupon_discount)), + "coupon_error": coupon_error, "total_discounts": float(q(bundle + coupon_discount)), "convenience_fee_rate": float(fee_rate * 100), "convenience_fee": float(fee), From a9604759b9bf061b0bd55c9ed92a22ca94dd5095 Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Mon, 5 Oct 2026 15:43:00 +0530 Subject: [PATCH 3/5] fix(cart): resolve currency-specific access plans dynamically for cart calculation and checkout --- app/features/cart/repository.py | 69 ++++++++++++++++++----- app/features/checkout/service.py | 8 ++- tests/test_cart_currency.py | 95 ++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+), 15 deletions(-) create mode 100644 tests/test_cart_currency.py diff --git a/app/features/cart/repository.py b/app/features/cart/repository.py index 8089876..2f11120 100644 --- a/app/features/cart/repository.py +++ b/app/features/cart/repository.py @@ -25,24 +25,65 @@ class CartRepository: if code.startswith("THERAPEUTIC"): return "Therapeutics" return str(metadata.get("access_group") or "General") - async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]: + async def get_plan_matches(self, codes: list[str], currency: str) -> dict[str, tuple[AccessPlan, Decimal]]: + curr = currency.strip().upper() normalized = [c.strip().upper() for c in codes if c.strip()] - rows = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_(normalized), AccessPlan.is_active.is_(True)))).scalars().all() + if not normalized: + return {} + + curr_rows = (await self.session.execute( + select(AccessPlan.currency_code).where(AccessPlan.is_active.is_(True)).distinct() + )).scalars().all() + known_currencies = {c.upper() for c in curr_rows if c} + known_currencies.add(curr) + + candidates: set[str] = set() + code_candidates_map: dict[str, list[str]] = {} + for code in normalized: + cands: list[str] = [] + base = code + parts = code.rsplit("_", 1) + if len(parts) == 2 and parts[1] in known_currencies: + base = parts[0] + + for cand in [f"{base}_{curr}", code, base]: + if cand not in cands: + cands.append(cand) + code_candidates_map[code] = cands + candidates.update(cands) + + rows = (await self.session.execute( + select(AccessPlan).where(AccessPlan.code.in_(candidates), AccessPlan.is_active.is_(True)) + )).scalars().all() by_code = {p.code.upper(): p for p in rows} + + matches: dict[str, tuple[AccessPlan, Decimal]] = {} + for code in normalized: + cands = code_candidates_map[code] + for cand in cands: + plan = by_code.get(cand) + if not plan: + continue + metadata = plan.metadata_json or {} + prices = metadata.get("prices") if isinstance(metadata, dict) else None + if isinstance(prices, dict) and curr in prices: + matches[code] = (plan, Decimal(str(prices[curr]))) + break + elif plan.currency_code.upper() == curr: + fee = plan.total_fee if plan.total_fee is not None else plan.module_fee + matches[code] = (plan, Decimal(str(fee))) + break + + return matches + + async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]: + matches = await self.get_plan_matches(codes, currency) + normalized = [c.strip().upper() for c in codes if c.strip()] items: list[PricingItem] = [] for code in normalized: - plan = by_code.get(code) - if not plan: - continue - metadata = plan.metadata_json or {} - prices = metadata.get("prices") if isinstance(metadata, dict) else None - if isinstance(prices, dict) and currency.upper() in prices: - price = Decimal(str(prices[currency.upper()])) - elif plan.currency_code.upper() == currency.upper(): - price = Decimal(plan.total_fee) - else: - continue - items.append(PricingItem(code=plan.code, name=plan.name, category=self._category(plan), price=price)) + if code in matches: + plan, price = matches[code] + items.append(PricingItem(code=code, name=plan.name, category=self._category(plan), price=price)) return items async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None: diff --git a/app/features/checkout/service.py b/app/features/checkout/service.py index 053be3c..be8280f 100644 --- a/app/features/checkout/service.py +++ b/app/features/checkout/service.py @@ -32,7 +32,13 @@ class CheckoutService: pass receipt = f"rcpt_{uuid.uuid4().hex[:12]}" order = rzp.create_order(amount=calc.grand_total, currency=calc.currency, receipt=receipt, notes={"user_id": str(user.id), "cart_item_codes": ",".join(request.cart_item_codes), "coupon_code": request.coupon_code or ""}) - plans = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_([c.upper() for c in request.cart_item_codes]), AccessPlan.is_active.is_(True)))).scalars().all() + plan_matches = await self.cart_service.repository.get_plan_matches(request.cart_item_codes, request.currency) + seen_plan_ids = set() + plans: list[AccessPlan] = [] + for plan, _ in plan_matches.values(): + if plan.id not in seen_plan_ids: + seen_plan_ids.add(plan.id) + plans.append(plan) now = datetime.now(timezone.utc) pricing_meta = {"base_subtotal": calc.base_subtotal, "total_discounts": calc.total_discounts, "grand_total": calc.grand_total, "taxable_amount": calc.taxable_amount, "gst_amount": calc.gst_amount, "currency": calc.currency} for plan in plans: diff --git a/tests/test_cart_currency.py b/tests/test_cart_currency.py new file mode 100644 index 0000000..6d66528 --- /dev/null +++ b/tests/test_cart_currency.py @@ -0,0 +1,95 @@ +import asyncio +import unittest +from decimal import Decimal +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession +from sqlalchemy.pool import NullPool +from app.core.config import settings +from app.features.cart.repository import CartRepository +from app.features.cart.service import CartService +from app.features.cart.schema import CartCalculationRequest + +class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.engine = create_async_engine(settings.database_url, poolclass=NullPool) + self.session_factory = async_sessionmaker(bind=self.engine, class_=AsyncSession, expire_on_commit=False) + self.session = self.session_factory() + self.repo = CartRepository(self.session) + self.service = CartService(self.repo) + + async def asyncTearDown(self): + await self.session.close() + await self.engine.dispose() + + async def test_resolve_points_acu_usd(self): + items = await self.repo.get_items(["POINTS_ACU"], "USD") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "POINTS_ACU") + self.assertEqual(items[0].price, Decimal("5.00")) + + async def test_resolve_points_acu_inr(self): + items = await self.repo.get_items(["POINTS_ACU"], "INR") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "POINTS_ACU") + self.assertEqual(items[0].price, Decimal("300.00")) + + async def test_resolve_suffixed_code_usd(self): + items = await self.repo.get_items(["POINTS_ACU_USD"], "USD") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "POINTS_ACU_USD") + self.assertEqual(items[0].price, Decimal("5.00")) + + async def test_resolve_lifetime_all_usd(self): + items = await self.repo.get_items(["LIFETIME_ALL"], "USD") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "LIFETIME_ALL") + self.assertEqual(items[0].price, Decimal("350.00")) + + async def test_resolve_lifetime_all_inr(self): + items = await self.repo.get_items(["LIFETIME_ALL"], "INR") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "LIFETIME_ALL") + self.assertEqual(items[0].price, Decimal("15000.00")) + + async def test_calculate_usd_cart(self): + calc = await self.service.calculate(CartCalculationRequest( + cart_item_codes=["POINTS_ACU"], + currency="USD" + )) + self.assertEqual(calc.currency, "USD") + self.assertEqual(calc.base_subtotal, 5.0) + self.assertEqual(calc.convenience_fee, 0.15) + self.assertEqual(calc.grand_total, 5.15) + self.assertEqual(len(calc.cart_items), 1) + self.assertEqual(calc.cart_items[0].code, "POINTS_ACU") + + async def test_calculate_inr_cart(self): + calc = await self.service.calculate(CartCalculationRequest( + cart_item_codes=["POINTS_ACU"], + currency="INR" + )) + self.assertEqual(calc.currency, "INR") + self.assertEqual(calc.base_subtotal, 300.0) + self.assertEqual(calc.convenience_fee, 6.0) + self.assertEqual(calc.gst_amount, 1.08) + self.assertEqual(calc.grand_total, 307.08) + + async def test_multi_item_usd_cart(self): + calc = await self.service.calculate(CartCalculationRequest( + cart_item_codes=["POINTS_ACU", "POINTS_EAR"], + currency="USD" + )) + self.assertEqual(calc.currency, "USD") + self.assertEqual(calc.base_subtotal, 8.0) + self.assertEqual(calc.convenience_fee, 0.24) + self.assertEqual(calc.grand_total, 8.24) + self.assertEqual(len(calc.cart_items), 2) + + async def test_unknown_plan_raises_error(self): + with self.assertRaises(ValueError): + await self.service.calculate(CartCalculationRequest( + cart_item_codes=["NON_EXISTENT_PLAN_XYZ"], + currency="USD" + )) + +if __name__ == "__main__": + unittest.main() From 98450ac4ecf8657f70d8b2a94ed3567954dfd6ff Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Mon, 5 Oct 2026 15:43:00 +0530 Subject: [PATCH 4/5] fix(cart): resolve currency-specific access plans dynamically for cart calculation and checkout --- app/features/cart/repository.py | 69 ++++++++++++++++++----- app/features/checkout/service.py | 8 ++- tests/test_cart_currency.py | 95 ++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+), 15 deletions(-) create mode 100644 tests/test_cart_currency.py diff --git a/app/features/cart/repository.py b/app/features/cart/repository.py index 8089876..2f11120 100644 --- a/app/features/cart/repository.py +++ b/app/features/cart/repository.py @@ -25,24 +25,65 @@ class CartRepository: if code.startswith("THERAPEUTIC"): return "Therapeutics" return str(metadata.get("access_group") or "General") - async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]: + async def get_plan_matches(self, codes: list[str], currency: str) -> dict[str, tuple[AccessPlan, Decimal]]: + curr = currency.strip().upper() normalized = [c.strip().upper() for c in codes if c.strip()] - rows = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_(normalized), AccessPlan.is_active.is_(True)))).scalars().all() + if not normalized: + return {} + + curr_rows = (await self.session.execute( + select(AccessPlan.currency_code).where(AccessPlan.is_active.is_(True)).distinct() + )).scalars().all() + known_currencies = {c.upper() for c in curr_rows if c} + known_currencies.add(curr) + + candidates: set[str] = set() + code_candidates_map: dict[str, list[str]] = {} + for code in normalized: + cands: list[str] = [] + base = code + parts = code.rsplit("_", 1) + if len(parts) == 2 and parts[1] in known_currencies: + base = parts[0] + + for cand in [f"{base}_{curr}", code, base]: + if cand not in cands: + cands.append(cand) + code_candidates_map[code] = cands + candidates.update(cands) + + rows = (await self.session.execute( + select(AccessPlan).where(AccessPlan.code.in_(candidates), AccessPlan.is_active.is_(True)) + )).scalars().all() by_code = {p.code.upper(): p for p in rows} + + matches: dict[str, tuple[AccessPlan, Decimal]] = {} + for code in normalized: + cands = code_candidates_map[code] + for cand in cands: + plan = by_code.get(cand) + if not plan: + continue + metadata = plan.metadata_json or {} + prices = metadata.get("prices") if isinstance(metadata, dict) else None + if isinstance(prices, dict) and curr in prices: + matches[code] = (plan, Decimal(str(prices[curr]))) + break + elif plan.currency_code.upper() == curr: + fee = plan.total_fee if plan.total_fee is not None else plan.module_fee + matches[code] = (plan, Decimal(str(fee))) + break + + return matches + + async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]: + matches = await self.get_plan_matches(codes, currency) + normalized = [c.strip().upper() for c in codes if c.strip()] items: list[PricingItem] = [] for code in normalized: - plan = by_code.get(code) - if not plan: - continue - metadata = plan.metadata_json or {} - prices = metadata.get("prices") if isinstance(metadata, dict) else None - if isinstance(prices, dict) and currency.upper() in prices: - price = Decimal(str(prices[currency.upper()])) - elif plan.currency_code.upper() == currency.upper(): - price = Decimal(plan.total_fee) - else: - continue - items.append(PricingItem(code=plan.code, name=plan.name, category=self._category(plan), price=price)) + if code in matches: + plan, price = matches[code] + items.append(PricingItem(code=code, name=plan.name, category=self._category(plan), price=price)) return items async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None: diff --git a/app/features/checkout/service.py b/app/features/checkout/service.py index 053be3c..be8280f 100644 --- a/app/features/checkout/service.py +++ b/app/features/checkout/service.py @@ -32,7 +32,13 @@ class CheckoutService: pass receipt = f"rcpt_{uuid.uuid4().hex[:12]}" order = rzp.create_order(amount=calc.grand_total, currency=calc.currency, receipt=receipt, notes={"user_id": str(user.id), "cart_item_codes": ",".join(request.cart_item_codes), "coupon_code": request.coupon_code or ""}) - plans = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_([c.upper() for c in request.cart_item_codes]), AccessPlan.is_active.is_(True)))).scalars().all() + plan_matches = await self.cart_service.repository.get_plan_matches(request.cart_item_codes, request.currency) + seen_plan_ids = set() + plans: list[AccessPlan] = [] + for plan, _ in plan_matches.values(): + if plan.id not in seen_plan_ids: + seen_plan_ids.add(plan.id) + plans.append(plan) now = datetime.now(timezone.utc) pricing_meta = {"base_subtotal": calc.base_subtotal, "total_discounts": calc.total_discounts, "grand_total": calc.grand_total, "taxable_amount": calc.taxable_amount, "gst_amount": calc.gst_amount, "currency": calc.currency} for plan in plans: diff --git a/tests/test_cart_currency.py b/tests/test_cart_currency.py new file mode 100644 index 0000000..6d66528 --- /dev/null +++ b/tests/test_cart_currency.py @@ -0,0 +1,95 @@ +import asyncio +import unittest +from decimal import Decimal +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession +from sqlalchemy.pool import NullPool +from app.core.config import settings +from app.features.cart.repository import CartRepository +from app.features.cart.service import CartService +from app.features.cart.schema import CartCalculationRequest + +class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.engine = create_async_engine(settings.database_url, poolclass=NullPool) + self.session_factory = async_sessionmaker(bind=self.engine, class_=AsyncSession, expire_on_commit=False) + self.session = self.session_factory() + self.repo = CartRepository(self.session) + self.service = CartService(self.repo) + + async def asyncTearDown(self): + await self.session.close() + await self.engine.dispose() + + async def test_resolve_points_acu_usd(self): + items = await self.repo.get_items(["POINTS_ACU"], "USD") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "POINTS_ACU") + self.assertEqual(items[0].price, Decimal("5.00")) + + async def test_resolve_points_acu_inr(self): + items = await self.repo.get_items(["POINTS_ACU"], "INR") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "POINTS_ACU") + self.assertEqual(items[0].price, Decimal("300.00")) + + async def test_resolve_suffixed_code_usd(self): + items = await self.repo.get_items(["POINTS_ACU_USD"], "USD") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "POINTS_ACU_USD") + self.assertEqual(items[0].price, Decimal("5.00")) + + async def test_resolve_lifetime_all_usd(self): + items = await self.repo.get_items(["LIFETIME_ALL"], "USD") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "LIFETIME_ALL") + self.assertEqual(items[0].price, Decimal("350.00")) + + async def test_resolve_lifetime_all_inr(self): + items = await self.repo.get_items(["LIFETIME_ALL"], "INR") + self.assertEqual(len(items), 1) + self.assertEqual(items[0].code, "LIFETIME_ALL") + self.assertEqual(items[0].price, Decimal("15000.00")) + + async def test_calculate_usd_cart(self): + calc = await self.service.calculate(CartCalculationRequest( + cart_item_codes=["POINTS_ACU"], + currency="USD" + )) + self.assertEqual(calc.currency, "USD") + self.assertEqual(calc.base_subtotal, 5.0) + self.assertEqual(calc.convenience_fee, 0.15) + self.assertEqual(calc.grand_total, 5.15) + self.assertEqual(len(calc.cart_items), 1) + self.assertEqual(calc.cart_items[0].code, "POINTS_ACU") + + async def test_calculate_inr_cart(self): + calc = await self.service.calculate(CartCalculationRequest( + cart_item_codes=["POINTS_ACU"], + currency="INR" + )) + self.assertEqual(calc.currency, "INR") + self.assertEqual(calc.base_subtotal, 300.0) + self.assertEqual(calc.convenience_fee, 6.0) + self.assertEqual(calc.gst_amount, 1.08) + self.assertEqual(calc.grand_total, 307.08) + + async def test_multi_item_usd_cart(self): + calc = await self.service.calculate(CartCalculationRequest( + cart_item_codes=["POINTS_ACU", "POINTS_EAR"], + currency="USD" + )) + self.assertEqual(calc.currency, "USD") + self.assertEqual(calc.base_subtotal, 8.0) + self.assertEqual(calc.convenience_fee, 0.24) + self.assertEqual(calc.grand_total, 8.24) + self.assertEqual(len(calc.cart_items), 2) + + async def test_unknown_plan_raises_error(self): + with self.assertRaises(ValueError): + await self.service.calculate(CartCalculationRequest( + cart_item_codes=["NON_EXISTENT_PLAN_XYZ"], + currency="USD" + )) + +if __name__ == "__main__": + unittest.main() From e6ecf4610bf04878211d494f55d56990a098064f Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Mon, 5 Oct 2026 17:23:15 +0530 Subject: [PATCH 5/5] fix(auth): require non-whitespace special character in password validation --- app/features/auth/security.py | 2 +- tests/test_password_validation.py | 39 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tests/test_password_validation.py diff --git a/app/features/auth/security.py b/app/features/auth/security.py index baedf6b..17a131f 100644 --- a/app/features/auth/security.py +++ b/app/features/auth/security.py @@ -56,7 +56,7 @@ def validate_password_strength(password: str) -> None: raise WeakPasswordError( "Password must contain at least one number." ) - if not any(not c.isalnum() for c in password): + if not any(not c.isalnum() and not c.isspace() for c in password): raise WeakPasswordError( "Password must contain at least one special character." ) diff --git a/tests/test_password_validation.py b/tests/test_password_validation.py new file mode 100644 index 0000000..b49e38a --- /dev/null +++ b/tests/test_password_validation.py @@ -0,0 +1,39 @@ +import unittest +from app.features.auth.security import validate_password_strength +from app.features.auth.errors import WeakPasswordError + +class TestPasswordValidation(unittest.TestCase): + def test_space_instead_of_special_char_fails(self): + with self.assertRaises(WeakPasswordError) as ctx: + validate_password_strength("Siraj 12345") + self.assertIn("special character", str(ctx.exception)) + + def test_too_short_fails(self): + with self.assertRaises(WeakPasswordError) as ctx: + validate_password_strength("Short1!") + self.assertIn("8 characters", str(ctx.exception)) + + def test_no_uppercase_fails(self): + with self.assertRaises(WeakPasswordError) as ctx: + validate_password_strength("lowercase1!") + self.assertIn("uppercase", str(ctx.exception)) + + def test_no_digit_fails(self): + with self.assertRaises(WeakPasswordError) as ctx: + validate_password_strength("NoNumbers!") + self.assertIn("number", str(ctx.exception)) + + def test_no_special_char_fails(self): + with self.assertRaises(WeakPasswordError) as ctx: + validate_password_strength("NoSpecial123") + self.assertIn("special character", str(ctx.exception)) + + def test_valid_passwords_pass(self): + # Must not raise any exceptions + validate_password_strength("Siraj@12345") + validate_password_strength("ValidPassword123!") + validate_password_strength("P@ssw0rd2026") + validate_password_strength("Strong#Pass1") + +if __name__ == "__main__": + unittest.main()