import sys import os from decimal import Decimal # Ensure backend root is on python path sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) import app.models.db_base from app.core.database.db_session import SessionLocal from app.models.EcomCustomerModel import EcomCustomer, CustomerAddress from app.models.CartModel import Cart from app.models.ProductModel import Product, ProductVariant from app.models.OrderModel import Order from app.models.WalletModel import CustomerWallet, WalletTransaction from app.services.CreditService import CreditService from app.services.OrderService import OrderService def run_storefront_credit_tests(): db = SessionLocal() try: print("\n=== STARTING STOREFRONT CREDIT INTEGRATION TEST SUITE ===") # 1. Setup / find test customer customer = db.query(EcomCustomer).filter(EcomCustomer.email == "test_storefront_wallet@ifixkart.com").first() if not customer: import ulid customer = EcomCustomer( customer_id=str(ulid.ULID()), first_name="Test", last_name="Shopper", email="test_storefront_wallet@ifixkart.com", phone="919988776655", is_active=True ) db.add(customer) db.commit() db.refresh(customer) print(f"[TEST 1] Verified Customer: {customer.customer_id}") # 2. Check / Grant initial active credits wallet = CreditService.get_or_create_wallet(db, customer.customer_id) # Give 300 active credits CreditService.adjust_wallet_balance_manual( db=db, customer_id=customer.customer_id, amount=Decimal("300.00"), adjustment_type="CREDIT", reason="Test seed active credits", admin_user="system_test@ifixkart.com" ) wallet = CreditService.get_or_create_wallet(db, customer.customer_id) assert wallet.active_balance >= Decimal("300.00"), f"Expected >= 300 active balance, got {wallet.active_balance}" initial_active = wallet.active_balance print(f"[TEST 2] Active Wallet Balance seeded: ₹{initial_active}") # 3. Setup customer address import ulid addr = db.query(CustomerAddress).filter(CustomerAddress.customer_id == customer.customer_id).first() if not addr: addr = CustomerAddress( address_id=str(ulid.ULID()), customer_id=customer.customer_id, address_type="SHIPPING", full_name="Test Shopper", phone="919988776655", street_address="123 Commerce St", city="Bangalore", state="Karnataka", pincode="560001", is_default=True ) db.add(addr) db.commit() db.refresh(addr) # 4. Find an active product variant with stock variant = db.query(ProductVariant).filter(ProductVariant.price > 100).first() assert variant is not None, "Product variant must exist in DB" # 5. Populate Cart import json cart = db.query(Cart).filter(Cart.customer_id == customer.customer_id).first() if not cart: cart = Cart( cart_id=str(ulid.ULID()), customer_id=customer.customer_id ) db.add(cart) cart.items_json = json.dumps([{"variant_id": variant.variant_id, "qty": 1}]) db.commit() # 6. Create Checkout Order with use_wallet_credits = True print("[TEST 3] Creating Checkout Order with use_wallet_credits=True...") order_res = OrderService.create_ecommerce_order( db=db, customer=customer, address_id=addr.address_id, payment_method="COD", use_wallet_credits=True ) assert order_res["credits_applied"] > 0, "Expected credits_applied > 0" assert order_res["discount_amount"] == order_res["credits_applied"] print(f"[TEST 3 PASSED] Order created: {order_res['order_no']}, Total: ₹{order_res['total_amount']}, Credits Applied: ₹{order_res['credits_applied']}, Final: ₹{order_res['final_amount']}") # 7. Verify wallet active_balance was debited db.refresh(wallet) expected_active = initial_active - Decimal(str(order_res["credits_applied"])) assert wallet.active_balance == expected_active, f"Expected {expected_active}, got {wallet.active_balance}" print(f"[TEST 4 PASSED] Wallet active_balance correctly debited to ₹{wallet.active_balance}") # 8. Check REDEEM transaction in ledger redeem_tx = db.query(WalletTransaction).filter( WalletTransaction.customer_id == customer.customer_id, WalletTransaction.reference_id == order_res["order_id"], WalletTransaction.transaction_type == "REDEEM" ).first() assert redeem_tx is not None, "REDEEM transaction must be logged" assert redeem_tx.credit_amount == -Decimal(str(order_res["credits_applied"])) print(f"[TEST 5 PASSED] REDEEM ledger entry confirmed: {redeem_tx.transaction_id} ({redeem_tx.credit_amount})") # 9. Test Refund of redeemed credits upon Order Cancellation print("[TEST 6] Testing refund of redeemed credits on Order cancellation...") refund_tx = CreditService.refund_redeemed_credits( db=db, customer_id=customer.customer_id, order_id=order_res["order_id"], order_no=order_res["order_no"] ) assert refund_tx is not None, "REFUND transaction must be generated" db.commit() db.refresh(wallet) assert wallet.active_balance == initial_active, f"Wallet active_balance should be restored to {initial_active}, got {wallet.active_balance}" print(f"[TEST 6 PASSED] Refund successfully restored wallet active_balance to ₹{wallet.active_balance}") # 10. Check get_wallet_summary summary = CreditService.get_wallet_summary(db, customer.customer_id) assert "active_balance" in summary assert "pending_balance" in summary assert "transactions" in summary print(f"[TEST 7 PASSED] get_wallet_summary returned {len(summary['transactions'])} transactions") print("\nALL STOREFRONT CREDIT INTEGRATION TESTS PASSED (100% SUCCESS)!") finally: db.close() if __name__ == "__main__": run_storefront_credit_tests()