- New models: WarrantyModel, WalletModel, SystemConfigModel - New schemas: WarrantySchema, RefundSchema, SystemConfig, CrmTaskCalendar, NotificationTemplate, NotificationGateway, RepairErp, ReviewModeration, InventoryPos, MultiDashboard, BillingFinance - New services: WarrantyService, RefundService, CrmService, CrmTaskCalendarService, DeliveryService, EmailTemplateService, InventoryPosService, MultiDashboardService, NotificationGatewayService, RepairErpService, ReviewModerationService, SystemConfigService, TemplateService, CreditService - Updated routers: AdminOrder, BillingFinance, Cart, Catalog, Checkout, Crm, InventoryPos, NotificationGateway, RolePermission, ServiceJob, Settings, Storefront, UserCreation - Updated models: Inventory, Notification, Order, Product, Service, Setting, SystemConfig, User - Updated core: database init, invoice generator, main app - Added WarrantyRouter with full CRUD and claim flow
187 lines
7.6 KiB
Python
187 lines
7.6 KiB
Python
import sys
|
|
import ulid
|
|
from decimal import Decimal
|
|
from datetime import datetime, timedelta, timezone
|
|
import app.models.db_base
|
|
|
|
from app.core.database.db_session import SessionLocal
|
|
from app.models.EcomCustomerModel import EcomCustomer
|
|
from app.models.OrderModel import Order
|
|
from app.models.ServiceModel import ServiceJob
|
|
from app.models.WalletModel import CustomerWallet, WalletTransaction
|
|
from app.services.CreditService import CreditService
|
|
|
|
def run_tests():
|
|
db = SessionLocal()
|
|
try:
|
|
print("=== Test 1: Settings Retrieval & Dynamic Update ===")
|
|
settings = CreditService.get_credit_settings(db)
|
|
print("Initial Settings:", settings)
|
|
assert "credits_sales_percentage" in settings
|
|
assert "credits_sales_return_window_days" in settings
|
|
assert "credits_service_percentage" in settings
|
|
assert "credits_service_claim_window_days" in settings
|
|
print("✓ Initial settings verified.")
|
|
|
|
# Dynamically update settings to 5% sales, 7 days return, 5% service, 3 days claim
|
|
CreditService.update_credit_settings(db, {
|
|
"credits_sales_percentage": 5.0,
|
|
"credits_sales_return_window_days": 7,
|
|
"credits_service_percentage": 5.0,
|
|
"credits_service_claim_window_days": 3
|
|
})
|
|
updated_settings = CreditService.get_credit_settings(db)
|
|
assert updated_settings["credits_sales_percentage"] == 5.0
|
|
assert updated_settings["credits_sales_return_window_days"] == 7
|
|
assert updated_settings["credits_service_percentage"] == 5.0
|
|
assert updated_settings["credits_service_claim_window_days"] == 3
|
|
print("✓ Settings dynamic update verified.")
|
|
|
|
print("\n=== Test 2: Create Test Customer & Wallet ===")
|
|
import time
|
|
test_email = f"test_credit_cust_{ulid.ULID()}@ifixkart.com"
|
|
customer = EcomCustomer(
|
|
customer_id=str(ulid.ULID()),
|
|
email=test_email,
|
|
first_name="Test",
|
|
last_name="CreditUser",
|
|
phone=f"99{str(int(time.time() * 1000))[-8:]}"
|
|
)
|
|
db.add(customer)
|
|
db.commit()
|
|
|
|
wallet = CreditService.get_or_create_wallet(db, customer.customer_id)
|
|
assert wallet.active_balance == Decimal("0.00")
|
|
assert wallet.pending_balance == Decimal("0.00")
|
|
print("✓ Customer and Wallet initialized successfully.")
|
|
|
|
print("\n=== Test 3: Sales Order Completion -> Pending Credit ===")
|
|
# Create an Order with final amount ₹2000
|
|
order = Order(
|
|
order_id=str(ulid.ULID()),
|
|
order_no=f"ORD-TEST-{str(ulid.ULID())}",
|
|
customer_id=customer.customer_id,
|
|
total_amount=Decimal("2000.00"),
|
|
final_amount=Decimal("2000.00"),
|
|
status="ORDER_CREATED",
|
|
payment_status="PAYMENT_CAPTURED"
|
|
)
|
|
db.add(order)
|
|
db.commit()
|
|
|
|
# Simulate Order Marked DELIVERED
|
|
order.status = "DELIVERED"
|
|
db.commit()
|
|
tx = CreditService.create_pending_credit_for_order(db, order.order_id)
|
|
|
|
assert tx is not None
|
|
assert tx.status == "PENDING"
|
|
# 5% of 2000 = 100.00
|
|
assert tx.credit_amount == Decimal("100.00")
|
|
assert tx.reference_type == "ORDER"
|
|
assert tx.reference_id == order.order_id
|
|
|
|
# Verify pending balance incremented on customer wallet
|
|
db.refresh(wallet)
|
|
assert wallet.pending_balance == Decimal("100.00")
|
|
assert wallet.active_balance == Decimal("0.00")
|
|
print(f"✓ Pending credit created: ₹{tx.credit_amount} (5% of ₹2000), matures_at: {tx.matures_at}")
|
|
print(f"✓ Wallet: Pending=₹{wallet.pending_balance}, Active=₹{wallet.active_balance}")
|
|
|
|
print("\n=== Test 4: Maturity Sweep (Simulate Return Window Passing) ===")
|
|
# Backdate matures_at to 1 hour in the past to simulate return window expired
|
|
tx.matures_at = datetime.now(timezone.utc) - timedelta(hours=1)
|
|
db.commit()
|
|
|
|
# Run maturity sweep
|
|
result = CreditService.process_maturing_credits(db)
|
|
print("Maturity Sweep Result:", result)
|
|
assert result["matured_count"] >= 1
|
|
|
|
db.refresh(tx)
|
|
db.refresh(wallet)
|
|
assert tx.status == "MATURED"
|
|
assert tx.matured_at is not None
|
|
assert wallet.pending_balance == Decimal("0.00")
|
|
assert wallet.active_balance == Decimal("100.00")
|
|
assert wallet.lifetime_earned == Decimal("100.00")
|
|
print(f"✓ Credit matured successfully! Spendable Active Balance: ₹{wallet.active_balance}")
|
|
|
|
print("\n=== Test 5: Return / Voiding Simulation ===")
|
|
# Create another order of ₹1000 -> generates ₹50 pending credit
|
|
order2 = Order(
|
|
order_id=str(ulid.ULID()),
|
|
order_no=f"ORD-TEST-VOID-{str(ulid.ULID())}",
|
|
customer_id=customer.customer_id,
|
|
total_amount=Decimal("1000.00"),
|
|
final_amount=Decimal("1000.00"),
|
|
status="DELIVERED",
|
|
payment_status="PAYMENT_CAPTURED"
|
|
)
|
|
db.add(order2)
|
|
db.commit()
|
|
|
|
tx2 = CreditService.create_pending_credit_for_order(db, order2.order_id)
|
|
assert tx2 is not None
|
|
assert tx2.credit_amount == Decimal("50.00")
|
|
db.refresh(wallet)
|
|
assert wallet.pending_balance == Decimal("50.00")
|
|
|
|
# Now simulate customer returning the order within return window
|
|
CreditService.void_pending_credit(db, "ORDER", order2.order_id, reason="Customer returned item")
|
|
db.refresh(tx2)
|
|
db.refresh(wallet)
|
|
assert tx2.status == "VOIDED"
|
|
assert tx2.void_reason == "Customer returned item"
|
|
assert wallet.pending_balance == Decimal("0.00")
|
|
assert wallet.active_balance == Decimal("100.00") # Original active balance unchanged!
|
|
print("✓ Pending credit successfully voided upon order return with zero leakage.")
|
|
|
|
print("\n=== Test 6: Service Job Credit Flow ===")
|
|
from app.models.CustomerDeviceModel import CustomerDevice
|
|
device = CustomerDevice(
|
|
device_id=str(ulid.ULID()),
|
|
customer_id=customer.customer_id,
|
|
brand="Apple",
|
|
model="iPhone 14"
|
|
)
|
|
db.add(device)
|
|
db.commit()
|
|
|
|
job = ServiceJob(
|
|
job_id=str(ulid.ULID()),
|
|
job_no=f"JOB-TEST-{str(ulid.ULID())}",
|
|
customer_id=customer.customer_id,
|
|
device_id=device.device_id,
|
|
base_price_snapshot=Decimal("1500.00"),
|
|
status="COMPLETED"
|
|
)
|
|
db.add(job)
|
|
db.commit()
|
|
|
|
service_tx = CreditService.create_pending_credit_for_service(db, job.job_id)
|
|
assert service_tx is not None
|
|
# 5% of 1500 = 75.00
|
|
assert service_tx.credit_amount == Decimal("75.00")
|
|
assert service_tx.status == "PENDING"
|
|
assert service_tx.reference_type == "SERVICE_JOB"
|
|
db.refresh(wallet)
|
|
assert wallet.pending_balance == Decimal("75.00")
|
|
print(f"✓ Service job credit created: ₹{service_tx.credit_amount} (5% of ₹1500), matures in 3 days.")
|
|
|
|
print("\n=== Test 7: Full Wallet Ledger Summary ===")
|
|
summary = CreditService.get_wallet_summary(db, customer.customer_id)
|
|
print("Wallet Summary:", {k: v for k, v in summary.items() if k != "transactions"})
|
|
print(f"Total Transactions logged: {len(summary['transactions'])}")
|
|
assert summary["active_balance"] == 100.0
|
|
assert summary["pending_balance"] == 75.0
|
|
assert len(summary["transactions"]) == 3
|
|
print("✓ Wallet summary and ledger integrity verified.")
|
|
|
|
print("\n🎉 ALL TESTS PASSED SUCCESSFULLY!")
|
|
|
|
finally:
|
|
db.close()
|
|
|
|
if __name__ == "__main__":
|
|
run_tests()
|