import ulid from decimal import Decimal from typing import Optional, Dict, Any, List from datetime import datetime, timedelta, timezone from sqlalchemy.orm import Session from sqlalchemy import select, and_, desc from app.models.SettingModel import Setting from app.models.WalletModel import CustomerWallet, WalletTransaction from app.models.OrderModel import Order from app.models.ServiceModel import ServiceJob from app.models.ServicePaymentModel import ServicePayment from app.core.events.notification_events import dispatch_internal_notification class CreditService: @staticmethod def get_credit_settings(db: Session) -> Dict[str, Any]: """ Retrieves dynamically configured store credit settings with safe production defaults. """ defaults = { "credits_enabled": True, "credits_sales_percentage": 5.0, "credits_sales_return_window_days": 7, "credits_service_percentage": 5.0, "credits_service_claim_window_days": 3, "credits_minimum_order_value": 0.0, "credits_expiry_days": 365, } setting_keys = list(defaults.keys()) records = db.execute(select(Setting).where(Setting.setting_key.in_(setting_keys))).scalars().all() result = dict(defaults) for record in records: if isinstance(record.setting_value, dict) and "value" in record.setting_value: val = record.setting_value["value"] # Convert string numbers to float/int if needed if record.setting_key in ["credits_sales_percentage", "credits_service_percentage", "credits_minimum_order_value"]: result[record.setting_key] = float(val) elif record.setting_key in ["credits_sales_return_window_days", "credits_service_claim_window_days", "credits_expiry_days"]: result[record.setting_key] = int(val) elif record.setting_key == "credits_enabled": result[record.setting_key] = bool(val) else: result[record.setting_key] = val return result @staticmethod def update_credit_settings(db: Session, updates: Dict[str, Any]) -> Dict[str, Any]: """ Updates credit configuration in the settings table. """ for key, val in updates.items(): setting = db.execute(select(Setting).where(Setting.setting_key == key)).scalar_one_or_none() if setting: setting.setting_value = {"value": val} else: db.add(Setting( setting_id=str(ulid.ULID()), setting_key=key, group="credits", type="json", setting_value={"value": val}, is_public=True )) db.commit() return CreditService.get_credit_settings(db) @staticmethod def get_or_create_wallet(db: Session, customer_id: str) -> CustomerWallet: """ Fetches an existing customer wallet or initializes a new one. """ wallet = db.execute( select(CustomerWallet).where(CustomerWallet.customer_id == customer_id) ).scalar_one_or_none() if not wallet: wallet = CustomerWallet( wallet_id=str(ulid.ULID()), customer_id=customer_id, active_balance=Decimal("0.00"), pending_balance=Decimal("0.00"), lifetime_earned=Decimal("0.00"), lifetime_redeemed=Decimal("0.00"), currency="INR", is_locked=False, ) db.add(wallet) db.commit() db.refresh(wallet) return wallet @classmethod def create_pending_credit_for_order(cls, db: Session, order_id: str) -> Optional[WalletTransaction]: """ Generates a PENDING store credit transaction when an e-commerce order is marked DELIVERED. Matures after the dynamically configured return window days. """ settings = cls.get_credit_settings(db) if not settings["credits_enabled"]: return None # Check for existing credit transaction for this order existing = db.execute( select(WalletTransaction).where( and_( WalletTransaction.reference_type == "ORDER", WalletTransaction.reference_id == order_id, WalletTransaction.transaction_type == "EARN" ) ) ).scalar_one_or_none() if existing: return existing order = db.get(Order, order_id) if not order or not order.customer_id: return None final_amt = Decimal(str(order.final_amount or 0.0)) min_order_val = Decimal(str(settings["credits_minimum_order_value"])) if final_amt < min_order_val or final_amt <= 0: return None sales_pct = Decimal(str(settings["credits_sales_percentage"])) if sales_pct <= 0: return None credit_amount = round(final_amt * (sales_pct / Decimal("100")), 2) if credit_amount <= 0: return None return_window_days = int(settings["credits_sales_return_window_days"]) now = datetime.now(timezone.utc) matures_at = now + timedelta(days=return_window_days) wallet = cls.get_or_create_wallet(db, order.customer_id) tx = WalletTransaction( transaction_id=str(ulid.ULID()), wallet_id=wallet.wallet_id, customer_id=order.customer_id, transaction_type="EARN", reference_type="ORDER", reference_id=order.order_id, reference_no=order.order_no, base_amount=final_amt, percentage_applied=sales_pct, credit_amount=credit_amount, status="PENDING", matures_at=matures_at, description=f"Earned {sales_pct}% store credit on Order {order.order_no} (Matures in {return_window_days} days)", ) db.add(tx) # Update pending balance wallet.pending_balance = (wallet.pending_balance or Decimal("0.00")) + credit_amount db.commit() db.refresh(tx) # Dispatch internal event notification dispatch_internal_notification( "CREDIT_PENDING_GENERATED", f"Pending store credit of ₹{credit_amount} created for customer on Order {order.order_no}. Matures on {matures_at.strftime('%Y-%m-%d')}.", context={ "customer_id": order.customer_id, "order_id": order.order_id, "order_no": order.order_no, "credit_amount": float(credit_amount), "matures_at": matures_at.isoformat() } ) return tx @classmethod def create_pending_credit_for_service(cls, db: Session, job_id: str) -> Optional[WalletTransaction]: """ Generates a PENDING store credit transaction when a repair service job is DELIVERED / COMPLETED. Matures after the dynamically configured claim window days. """ settings = cls.get_credit_settings(db) if not settings["credits_enabled"]: return None # Prevent duplicate credit transaction existing = db.execute( select(WalletTransaction).where( and_( WalletTransaction.reference_type == "SERVICE_JOB", WalletTransaction.reference_id == job_id, WalletTransaction.transaction_type == "EARN" ) ) ).scalar_one_or_none() if existing: return existing job = db.get(ServiceJob, job_id) if not job or not job.customer_id: return None # Determine eligible base amount from captured payments or base price snapshot captured_payments = db.execute( select(ServicePayment).where( and_( ServicePayment.service_job_id == job_id, ServicePayment.status.in_(["CAPTURED", "PAID"]) ) ) ).scalars().all() if captured_payments: base_amt = sum(Decimal(str(p.amount)) for p in captured_payments) elif job.base_price_snapshot: base_amt = Decimal(str(job.base_price_snapshot)) else: base_amt = Decimal("0.00") min_order_val = Decimal(str(settings["credits_minimum_order_value"])) if base_amt < min_order_val or base_amt <= 0: return None service_pct = Decimal(str(settings["credits_service_percentage"])) if service_pct <= 0: return None credit_amount = round(base_amt * (service_pct / Decimal("100")), 2) if credit_amount <= 0: return None claim_window_days = int(settings["credits_service_claim_window_days"]) now = datetime.now(timezone.utc) matures_at = now + timedelta(days=claim_window_days) wallet = cls.get_or_create_wallet(db, job.customer_id) tx = WalletTransaction( transaction_id=str(ulid.ULID()), wallet_id=wallet.wallet_id, customer_id=job.customer_id, transaction_type="EARN", reference_type="SERVICE_JOB", reference_id=job.job_id, reference_no=job.job_no, base_amount=base_amt, percentage_applied=service_pct, credit_amount=credit_amount, status="PENDING", matures_at=matures_at, description=f"Earned {service_pct}% store credit on Service Job {job.job_no} (Matures in {claim_window_days} days)", ) db.add(tx) wallet.pending_balance = (wallet.pending_balance or Decimal("0.00")) + credit_amount db.commit() db.refresh(tx) dispatch_internal_notification( "CREDIT_PENDING_GENERATED", f"Pending store credit of ₹{credit_amount} created for customer on Service Job {job.job_no}. Matures on {matures_at.strftime('%Y-%m-%d')}.", context={ "customer_id": job.customer_id, "job_id": job.job_id, "job_no": job.job_no, "credit_amount": float(credit_amount), "matures_at": matures_at.isoformat() } ) return tx @classmethod def void_pending_credit(cls, db: Session, reference_type: str, reference_id: str, reason: str = "Order returned/cancelled") -> bool: """ Voids any active PENDING credit transaction when an order is returned or cancelled within the window. """ pending_txs = db.execute( select(WalletTransaction).where( and_( WalletTransaction.reference_type == reference_type, WalletTransaction.reference_id == reference_id, WalletTransaction.status == "PENDING" ) ) ).scalars().all() if not pending_txs: return False now = datetime.now(timezone.utc) for tx in pending_txs: tx.status = "VOIDED" tx.voided_at = now tx.void_reason = reason wallet = db.get(CustomerWallet, tx.wallet_id) if wallet: wallet.pending_balance = max(Decimal("0.00"), (wallet.pending_balance or Decimal("0.00")) - tx.credit_amount) db.commit() return True @classmethod def process_maturing_credits(cls, db: Session) -> Dict[str, Any]: """ Scheduled background worker sweep: Transitions all PENDING credits where matures_at <= NOW into MATURED spendable credits. Verifies the originating Order or Service was not refunded / returned before maturing. """ now = datetime.now(timezone.utc) pending_txs = db.execute( select(WalletTransaction).where( and_( WalletTransaction.status == "PENDING", WalletTransaction.matures_at <= now ) ) ).scalars().all() matured_count = 0 voided_count = 0 for tx in pending_txs: wallet = db.get(CustomerWallet, tx.wallet_id) if not wallet: continue # Verification: Check if reference order or service was cancelled/returned is_valid = True void_reason = "" if tx.reference_type == "ORDER": order = db.get(Order, tx.reference_id) if not order or order.status in ["CANCELLED", "RETURNED"] or order.payment_status in ["REFUNDED", "PAYMENT_FAILED"]: is_valid = False void_reason = f"Order status is {order.status if order else 'DELETED'}" elif tx.reference_type == "SERVICE_JOB": job = db.get(ServiceJob, tx.reference_id) if not job or job.status in ["CANCELLED", "REFUNDED"]: is_valid = False void_reason = f"Service job status is {job.status if job else 'DELETED'}" if not is_valid: tx.status = "VOIDED" tx.voided_at = now tx.void_reason = void_reason wallet.pending_balance = max(Decimal("0.00"), (wallet.pending_balance or Decimal("0.00")) - tx.credit_amount) voided_count += 1 else: # Mature transaction and transfer funds from pending to active spendable balance tx.status = "MATURED" tx.matured_at = now wallet.pending_balance = max(Decimal("0.00"), (wallet.pending_balance or Decimal("0.00")) - tx.credit_amount) wallet.active_balance = (wallet.active_balance or Decimal("0.00")) + tx.credit_amount wallet.lifetime_earned = (wallet.lifetime_earned or Decimal("0.00")) + tx.credit_amount matured_count += 1 dispatch_internal_notification( "CREDIT_MATURED_UNLOCKED", f"Store credit of ₹{tx.credit_amount} has matured and is now active in customer wallet.", context={ "customer_id": tx.customer_id, "credit_amount": float(tx.credit_amount), "reference_no": tx.reference_no } ) db.commit() return { "processed_total": len(pending_txs), "matured_count": matured_count, "voided_count": voided_count, "timestamp": now.isoformat() } @classmethod def get_wallet_summary(cls, db: Session, customer_id: str) -> Dict[str, Any]: """ Returns full customer wallet state with transaction ledger history. """ wallet = cls.get_or_create_wallet(db, customer_id) transactions = db.execute( select(WalletTransaction) .where(WalletTransaction.wallet_id == wallet.wallet_id) .order_by(desc(WalletTransaction.created_at)) ).scalars().all() return { "wallet_id": wallet.wallet_id, "customer_id": wallet.customer_id, "active_balance": float(wallet.active_balance), "pending_balance": float(wallet.pending_balance), "lifetime_earned": float(wallet.lifetime_earned), "lifetime_redeemed": float(wallet.lifetime_redeemed), "currency": wallet.currency, "is_locked": wallet.is_locked, "transactions": [ { "transaction_id": tx.transaction_id, "transaction_type": tx.transaction_type, "reference_type": tx.reference_type, "reference_id": tx.reference_id, "reference_no": tx.reference_no, "base_amount": float(tx.base_amount), "percentage_applied": float(tx.percentage_applied) if tx.percentage_applied else None, "credit_amount": float(tx.credit_amount), "status": tx.status, "matures_at": tx.matures_at.isoformat() if tx.matures_at else None, "matured_at": tx.matured_at.isoformat() if tx.matured_at else None, "voided_at": tx.voided_at.isoformat() if tx.voided_at else None, "void_reason": tx.void_reason, "description": tx.description, "created_at": tx.created_at.isoformat() if tx.created_at else None, } for tx in transactions ] } @classmethod def adjust_wallet_balance_manual( cls, db: Session, customer_id: str, amount: Decimal, adjustment_type: str, reason: str, admin_user: str ) -> WalletTransaction: """ Admin action: Manually add or deduct active store credit for a customer. adjustment_type: 'CREDIT' or 'DEBIT' """ wallet = cls.get_or_create_wallet(db, customer_id) now = datetime.now(timezone.utc) if adjustment_type == "DEBIT" and wallet.active_balance < amount: from fastapi import HTTPException raise HTTPException(status_code=400, detail="Insufficient active store credit balance for debit adjustment") tx = WalletTransaction( transaction_id=str(ulid.ULID()), wallet_id=wallet.wallet_id, customer_id=customer_id, transaction_type="ADJUSTMENT", reference_type="MANUAL_ADMIN", reference_id=admin_user, reference_no=f"ADMIN-{admin_user[:8]}", base_amount=amount, percentage_applied=None, credit_amount=amount if adjustment_type == "CREDIT" else -amount, status="MATURED", matures_at=now, matured_at=now, description=f"Manual Admin Adjustment ({adjustment_type}): {reason}", ) db.add(tx) if adjustment_type == "CREDIT": wallet.active_balance += amount wallet.lifetime_earned += amount else: wallet.active_balance -= amount wallet.lifetime_redeemed += amount db.commit() db.refresh(tx) return tx @classmethod def redeem_credits( cls, db: Session, customer_id: str, amount: Decimal, order_id: str, order_no: str ) -> Optional[WalletTransaction]: """ Redeems active store credits during e-commerce checkout. Atomically debits wallet active_balance and logs an immutable REDEEM transaction. """ from fastapi import HTTPException if amount <= Decimal("0.00"): return None # Lock wallet row for update wallet = db.execute( select(CustomerWallet) .where(CustomerWallet.customer_id == customer_id) .with_for_update() ).scalar_one_or_none() if not wallet: raise HTTPException(status_code=400, detail="Customer wallet not found.") if wallet.is_locked: raise HTTPException(status_code=400, detail="Customer wallet is currently locked. Credits cannot be redeemed.") if wallet.active_balance < amount: raise HTTPException( status_code=400, detail=f"Insufficient active store credits. Available: ₹{wallet.active_balance}, Requested: ₹{amount}" ) now = datetime.now(timezone.utc) tx = WalletTransaction( transaction_id=str(ulid.ULID()), wallet_id=wallet.wallet_id, customer_id=customer_id, transaction_type="REDEEM", reference_type="SALES_ORDER", reference_id=order_id, reference_no=order_no, base_amount=amount, percentage_applied=None, credit_amount=-amount, status="COMPLETED", matures_at=now, matured_at=now, description=f"Redeemed store credits on checkout order {order_no}", ) db.add(tx) wallet.active_balance -= amount wallet.lifetime_redeemed += amount return tx @classmethod def refund_redeemed_credits( cls, db: Session, customer_id: str, order_id: str, order_no: str ) -> Optional[WalletTransaction]: """ Refunds previously redeemed credits back to the customer's active wallet balance if an order that used credits is cancelled. """ redeem_tx = db.execute( select(WalletTransaction).where( and_( WalletTransaction.customer_id == customer_id, WalletTransaction.reference_type == "SALES_ORDER", WalletTransaction.reference_id == order_id, WalletTransaction.transaction_type == "REDEEM", WalletTransaction.status == "COMPLETED" ) ) ).scalar_one_or_none() if not redeem_tx: return None # Check if already refunded already_refunded = db.execute( select(WalletTransaction).where( and_( WalletTransaction.customer_id == customer_id, WalletTransaction.reference_type == "SALES_ORDER", WalletTransaction.reference_id == order_id, WalletTransaction.transaction_type == "REFUND" ) ) ).scalar_one_or_none() if already_refunded: return already_refunded refund_amt = abs(redeem_tx.credit_amount) wallet = db.execute( select(CustomerWallet) .where(CustomerWallet.customer_id == customer_id) .with_for_update() ).scalar_one_or_none() if not wallet: return None now = datetime.now(timezone.utc) refund_tx = WalletTransaction( transaction_id=str(ulid.ULID()), wallet_id=wallet.wallet_id, customer_id=customer_id, transaction_type="REFUND", reference_type="SALES_ORDER", reference_id=order_id, reference_no=order_no, base_amount=refund_amt, percentage_applied=None, credit_amount=refund_amt, status="COMPLETED", matures_at=now, matured_at=now, description=f"Refund of redeemed credits for cancelled order {order_no}", ) db.add(refund_tx) wallet.active_balance += refund_amt wallet.lifetime_redeemed = max(Decimal("0.00"), wallet.lifetime_redeemed - refund_amt) return refund_tx