175 lines
8.5 KiB
Python
175 lines
8.5 KiB
Python
from datetime import datetime, timezone
|
|
import ulid
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import select, func
|
|
from typing import List, Optional, Any
|
|
from fastapi import HTTPException
|
|
|
|
from app.models.RefundModel import RefundRequest, RefundMedia, RefundEntityType, RefundStatus, RefundPaymentMethod
|
|
from app.schemas.RefundSchema import RefundRequestCreate, RefundRequestApprove, RefundRequestReject
|
|
from app.models.ServiceModel import ServiceJob
|
|
from app.models.OrderModel import Order
|
|
from app.core.events.event_publisher import publish_business_event
|
|
|
|
class RefundService:
|
|
def __init__(self, db: Session, tenant_id: str = "tenant_default"):
|
|
self.db = db
|
|
self.tenant_id = tenant_id
|
|
|
|
def request_refund(self, data: RefundRequestCreate, user_id: str) -> RefundRequest:
|
|
# Validate based on Entity Type
|
|
if data.entity_type == RefundEntityType.SERVICE:
|
|
# Row-level lock on ServiceJob
|
|
stmt = select(ServiceJob).where(ServiceJob.job_id == data.entity_id).with_for_update()
|
|
service_job = self.db.execute(stmt).scalar_one_or_none()
|
|
|
|
if not service_job:
|
|
raise HTTPException(status_code=404, detail="Service Job not found")
|
|
|
|
if not data.part_number_verification:
|
|
raise HTTPException(status_code=400, detail="Part number verification is mandatory for Service refunds")
|
|
|
|
# Strict Part Number Match (Normalize whitespace only)
|
|
if not service_job.replaced_part_numbers or data.part_number_verification.strip() not in [p.strip() for p in service_job.replaced_part_numbers]:
|
|
raise HTTPException(status_code=400, detail="Part number does not match any replaced part numbers.")
|
|
|
|
# Calculate Refundable Amount (exclude fulfillment fee/delivery charge)
|
|
# Service payment/order logic is handled through quotes or ecom_sales, assuming base_price for now if total not tracked in service_job
|
|
# In a real app we'd fetch the exact payment/invoice record, but for validation cap:
|
|
# Assuming max refundable is the amount paid minus delivery fee.
|
|
# Example: Max refundable = total_paid - fulfillment_fee
|
|
# We will assume a simple rule for now: check against total existing refunds.
|
|
|
|
stmt_refunds = select(func.sum(RefundRequest.amount)).where(
|
|
RefundRequest.entity_id == data.entity_id,
|
|
RefundRequest.status.in_([RefundStatus.PENDING, RefundStatus.APPROVED, RefundStatus.PROCESSING, RefundStatus.REFUNDED])
|
|
)
|
|
already_refunded = self.db.execute(stmt_refunds).scalar() or 0.0
|
|
|
|
# Here we would fetch actual total_paid from ServicePayment or Order.
|
|
# We'll mock total_paid as 99999 for this example if it's not explicitly in ServiceJob
|
|
total_paid = float(service_job.base_price_snapshot or 0) + float(service_job.inspection_fee_snapshot or 0)
|
|
refundable_amount = total_paid - float(service_job.fulfillment_fee or 0.0)
|
|
|
|
if already_refunded + data.amount > refundable_amount:
|
|
raise HTTPException(status_code=400, detail=f"Refund request exceeds maximum allowable amount. Max refundable: {refundable_amount - already_refunded}")
|
|
|
|
elif data.entity_type == RefundEntityType.SALES:
|
|
# Row-level lock on Order
|
|
stmt = select(Order).where(Order.order_id == data.entity_id).with_for_update()
|
|
order = self.db.execute(stmt).scalar_one_or_none()
|
|
|
|
if not order:
|
|
raise HTTPException(status_code=404, detail="Order not found")
|
|
|
|
stmt_refunds = select(func.sum(RefundRequest.amount)).where(
|
|
RefundRequest.entity_id == data.entity_id,
|
|
RefundRequest.status.in_([RefundStatus.PENDING, RefundStatus.APPROVED, RefundStatus.PROCESSING, RefundStatus.REFUNDED])
|
|
)
|
|
already_refunded = self.db.execute(stmt_refunds).scalar() or 0.0
|
|
total_paid = float(order.final_amount)
|
|
refundable_amount = total_paid - float(order.shipping_cost)
|
|
|
|
if already_refunded + data.amount > refundable_amount:
|
|
raise HTTPException(status_code=400, detail=f"Refund request exceeds maximum allowable amount. Max refundable: {refundable_amount - already_refunded}")
|
|
else:
|
|
raise HTTPException(status_code=400, detail="Invalid entity type")
|
|
|
|
# Create Refund Request
|
|
now = datetime.now(timezone.utc)
|
|
refund_req = RefundRequest(
|
|
refund_id=str(ulid.ULID()),
|
|
tenant_id=self.tenant_id,
|
|
location_id=data.location_id,
|
|
entity_type=data.entity_type,
|
|
entity_id=data.entity_id,
|
|
amount=data.amount,
|
|
payment_method=data.payment_method,
|
|
status=RefundStatus.PENDING,
|
|
reason=data.reason,
|
|
part_number_verification=data.part_number_verification,
|
|
requested_by=user_id,
|
|
requested_at=now
|
|
)
|
|
self.db.add(refund_req)
|
|
|
|
# Add Media
|
|
for media_item in data.media:
|
|
media = RefundMedia(
|
|
id=str(ulid.ULID()),
|
|
refund_id=refund_req.refund_id,
|
|
file_url=media_item.file_url,
|
|
file_type=media_item.file_type,
|
|
media_filename=media_item.media_filename,
|
|
uploaded_by=user_id,
|
|
uploaded_at=now
|
|
)
|
|
self.db.add(media)
|
|
|
|
self.db.commit()
|
|
self.db.refresh(refund_req)
|
|
|
|
publish_business_event(
|
|
event_type="REFUND_REQUESTED",
|
|
payload={"refund_id": refund_req.refund_id, "amount": refund_req.amount},
|
|
tenant_id=self.tenant_id,
|
|
aggregate_id=refund_req.refund_id
|
|
)
|
|
return refund_req
|
|
|
|
def approve_refund(self, refund_id: str, data: RefundRequestApprove, user_id: str) -> RefundRequest:
|
|
stmt = select(RefundRequest).where(RefundRequest.refund_id == refund_id, RefundRequest.tenant_id == self.tenant_id)
|
|
refund = self.db.execute(stmt).scalar_one_or_none()
|
|
|
|
if not refund or refund.status != RefundStatus.PENDING:
|
|
raise HTTPException(status_code=400, detail="Refund not found or not in PENDING state")
|
|
|
|
if refund.requested_by == user_id:
|
|
raise HTTPException(
|
|
status_code=403,
|
|
detail="Segregation of Duties Violation: You cannot approve a refund request that you created."
|
|
)
|
|
|
|
refund.approved_by = user_id
|
|
refund.approved_at = datetime.now(timezone.utc)
|
|
if data.admin_notes:
|
|
refund.admin_notes = data.admin_notes
|
|
|
|
if refund.payment_method == RefundPaymentMethod.ONLINE:
|
|
# Trigger Razorpay API logic here securely
|
|
# mock transition to PROCESSING
|
|
refund.status = RefundStatus.PROCESSING
|
|
else:
|
|
refund.status = RefundStatus.REFUNDED
|
|
refund.refunded_at = datetime.now(timezone.utc)
|
|
|
|
self.db.commit()
|
|
self.db.refresh(refund)
|
|
return refund
|
|
|
|
def reject_refund(self, refund_id: str, data: RefundRequestReject, user_id: str) -> RefundRequest:
|
|
stmt = select(RefundRequest).where(RefundRequest.refund_id == refund_id, RefundRequest.tenant_id == self.tenant_id)
|
|
refund = self.db.execute(stmt).scalar_one_or_none()
|
|
|
|
if not refund or refund.status != RefundStatus.PENDING:
|
|
raise HTTPException(status_code=400, detail="Refund not found or not in PENDING state")
|
|
|
|
refund.status = RefundStatus.REJECTED
|
|
refund.rejected_by = user_id
|
|
refund.rejected_at = datetime.now(timezone.utc)
|
|
refund.rejection_reason = data.rejection_reason
|
|
if data.admin_notes:
|
|
refund.admin_notes = data.admin_notes
|
|
|
|
self.db.commit()
|
|
self.db.refresh(refund)
|
|
return refund
|
|
|
|
def list_refunds(self, entity_type: Optional[str] = None, status: Optional[str] = None) -> List[RefundRequest]:
|
|
stmt = select(RefundRequest).where(RefundRequest.tenant_id == self.tenant_id)
|
|
if entity_type:
|
|
stmt = stmt.where(RefundRequest.entity_type == entity_type)
|
|
if status:
|
|
stmt = stmt.where(RefundRequest.status == status)
|
|
|
|
return list(self.db.execute(stmt).scalars().all())
|