fix twelve channels search facets #4

Closed
shivani wants to merge 2 commits from twelve-channels into main
9 changed files with 255 additions and 33 deletions
Showing only changes of commit 074645822f - Show all commits

View File

@ -56,7 +56,7 @@ def validate_password_strength(password: str) -> None:
raise WeakPasswordError( raise WeakPasswordError(
"Password must contain at least one number." "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( raise WeakPasswordError(
"Password must contain at least one special character." "Password must contain at least one special character."
) )

View File

@ -25,40 +25,92 @@ class CartRepository:
if code.startswith("THERAPEUTIC"): return "Therapeutics" if code.startswith("THERAPEUTIC"): return "Therapeutics"
return str(metadata.get("access_group") or "General") 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()] 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:
by_code = {p.code.upper(): p for p in rows} return {}
items: list[PricingItem] = []
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: for code in normalized:
plan = by_code.get(code) 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: if not plan:
continue continue
metadata = plan.metadata_json or {} metadata = plan.metadata_json or {}
prices = metadata.get("prices") if isinstance(metadata, dict) else None prices = metadata.get("prices") if isinstance(metadata, dict) else None
if isinstance(prices, dict) and currency.upper() in prices: if isinstance(prices, dict) and curr in prices:
price = Decimal(str(prices[currency.upper()])) matches[code] = (plan, Decimal(str(prices[curr])))
elif plan.currency_code.upper() == currency.upper(): break
price = Decimal(plan.total_fee) elif plan.currency_code.upper() == curr:
else: fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
continue matches[code] = (plan, Decimal(str(fee)))
items.append(PricingItem(code=plan.code, name=plan.name, category=self._category(plan), price=price)) 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:
if code in matches:
plan, price = matches[code]
items.append(PricingItem(code=code, name=plan.name, category=self._category(plan), price=price))
return items return items
async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None: async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]:
if not code: if not code or not code.strip():
return None return None, None
clean_code = code.strip().upper()
now = datetime.now(timezone.utc) 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: 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 {} metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
value = Decimal(coupon.value) 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 currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
if isinstance(currency_values, dict) and currency.upper() in currency_values: if isinstance(currency_values, dict) and currency.upper() in currency_values:
value = Decimal(str(currency_values[currency.upper()])) 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]: 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() 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()

View File

@ -22,6 +22,7 @@ class CartCalculationResponse(BaseModel):
bundle_discount_amount: float bundle_discount_amount: float
coupon_applied: str coupon_applied: str
coupon_discount_amount: float coupon_discount_amount: float
coupon_error: str | None = None
total_discounts: float total_discounts: float
convenience_fee_rate: float convenience_fee_rate: float
convenience_fee: float convenience_fee: float

View File

@ -16,7 +16,7 @@ class CartService:
resolved = {i.code.upper() for i in items} resolved = {i.code.upper() for i in items}
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved] 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)}") 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 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 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))

View File

@ -32,7 +32,13 @@ class CheckoutService:
pass pass
receipt = f"rcpt_{uuid.uuid4().hex[:12]}" 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 ""}) 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) 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} 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: for plan in plans:

View File

@ -27,7 +27,7 @@ class PricingCoupon:
class PricingEngine: class PricingEngine:
"""Preserves the legacy bundle/loyalty/fee rules while sourcing prices from commerce.access_plans.""" """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() curr = currency.upper()
base = sum((item.price for item in items), Decimal("0")) base = sum((item.price for item in items), Decimal("0"))
categories = {item.category for item in items} categories = {item.category for item in items}
@ -56,9 +56,9 @@ class PricingEngine:
coupon_text = "None" coupon_text = "None"
if coupon: if coupon:
coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -") 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) 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")) coupon_discount = after_bundle * (coupon.value / Decimal("100"))
if coupon.max_discount_limit > 0: if coupon.max_discount_limit > 0:
coupon_discount = min(coupon_discount, coupon.max_discount_limit) coupon_discount = min(coupon_discount, coupon.max_discount_limit)
@ -74,6 +74,7 @@ class PricingEngine:
"bundle_discount_amount": float(q(bundle)), "bundle_discount_amount": float(q(bundle)),
"coupon_applied": coupon_text, "coupon_applied": coupon_text,
"coupon_discount_amount": float(q(coupon_discount)), "coupon_discount_amount": float(q(coupon_discount)),
"coupon_error": coupon_error,
"total_discounts": float(q(bundle + coupon_discount)), "total_discounts": float(q(bundle + coupon_discount)),
"convenience_fee_rate": float(fee_rate * 100), "convenience_fee_rate": float(fee_rate * 100),
"convenience_fee": float(fee), "convenience_fee": float(fee),

View File

@ -39,12 +39,29 @@ def _string_value(value: Any) -> str | None:
return 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: if value is None:
return [] return []
if isinstance(value, list): if isinstance(value, list):
result: list[str] = [] result: list[str] = []
for item in value: 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)) result.extend(_flatten_projection_values(item))
return result return result
direct = _string_value(value) direct = _string_value(value)
@ -290,9 +307,15 @@ class SearchRepository:
values.append(row["value_date"].isoformat()) values.append(row["value_date"].isoformat())
return values 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() 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"): if strategy in ("multivalue", "comma_delimited", "delimited"):
split_values: list[str] = [] split_values: list[str] = []
for item in raw_values: for item in raw_values:
@ -308,7 +331,6 @@ class SearchRepository:
cleaned = cleaned[:1].upper() + cleaned[1:] cleaned = cleaned[:1].upper() + cleaned[1:]
split_values.append(cleaned) split_values.append(cleaned)
raw_values = split_values raw_values = split_values
projected: list[ProjectionValue] = [] projected: list[ProjectionValue] = []
seen: set[str] = set() seen: set[str] = set()
for label in raw_values: for label in raw_values:
@ -422,7 +444,13 @@ class SearchRepository:
) )
values: list[ProjectionValue] = [] values: list[ProjectionValue] = []
for raw in raw_rows: 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() seen: set[str] = set()
for value in values: for value in values:

View File

@ -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()

View File

@ -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()