- Backend: FastAPI app with all models, services, schemas, routes - Admin Panel: Next.js dashboard with all modules (CRM, POS, repairs, warranties, billing, notifications, etc.) - Ecommerce: storefront (submodule) + product catalog - AI Agents: .agents/ skill library for Antigravity IDE - Docs: architecture, billing, notification gateway markdown - Submodules: Backend/OpenWA, Ecommerce/File 2/storefront
356 lines
14 KiB
Python
356 lines
14 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import select
|
|
from typing import List, Optional, Dict, Any
|
|
import ulid
|
|
import random
|
|
|
|
from app.models.BillingFinanceModel import CrmBulkQuotation, CrmBulkQuotationItem, CrmGstInvoice, CrmInvoiceItem
|
|
from app.models.CrmModel import CrmCustomer, CrmLead
|
|
from app.schemas.BillingFinance import (
|
|
CrmBulkQuotationCreate, CrmGstInvoiceCreate, CrmRecordPayment
|
|
)
|
|
from app.core.events.event_publisher import publish_business_event
|
|
|
|
class BillingFinanceService:
|
|
def __init__(self, db: Session, tenant_id: str = "tenant_default"):
|
|
self.db = db
|
|
self.tenant_id = tenant_id
|
|
|
|
# --- BULK QUOTATION MANAGEMENT ---
|
|
def create_quotation(self, data: CrmBulkQuotationCreate) -> CrmBulkQuotation:
|
|
random_num = random.randint(100, 999)
|
|
quote_number = data.quote_number if data.quote_number else f"IFK-QT-2026-{random_num}"
|
|
valid_until = datetime.now(timezone.utc) + timedelta(days=data.valid_days or 7)
|
|
|
|
# Ensure Customer Exists
|
|
actual_customer_id = data.customer_id
|
|
if not actual_customer_id and data.customer_phone and data.customer_name:
|
|
# Look up customer by phone
|
|
existing_cust = self.db.query(CrmCustomer).filter(
|
|
CrmCustomer.phone == data.customer_phone,
|
|
CrmCustomer.tenant_id == self.tenant_id
|
|
).first()
|
|
|
|
if existing_cust:
|
|
actual_customer_id = existing_cust.customer_id
|
|
if data.customer_email and existing_cust.email != data.customer_email:
|
|
existing_cust.email = data.customer_email
|
|
self.db.add(existing_cust)
|
|
else:
|
|
# Create customer
|
|
new_cust = CrmCustomer(
|
|
customer_id=str(ulid.ULID()),
|
|
tenant_id=self.tenant_id,
|
|
name=data.customer_name,
|
|
phone=data.customer_phone,
|
|
email=data.customer_email,
|
|
is_dual_customer=True
|
|
)
|
|
self.db.add(new_cust)
|
|
self.db.flush()
|
|
actual_customer_id = new_cust.customer_id
|
|
|
|
if not actual_customer_id:
|
|
raise ValueError("customer_id or (customer_phone and customer_name) is required")
|
|
|
|
subtotal = 0.0
|
|
tax_total = 0.0
|
|
|
|
quotation_items = []
|
|
for it in data.items:
|
|
# Inclusive GST Calculation
|
|
gross_item_total = it.unit_price * it.quantity
|
|
item_tax_percent = it.tax_percent or 18.0
|
|
item_taxable = round((gross_item_total / (1 + item_tax_percent / 100.0)), 2)
|
|
item_tax = round((gross_item_total - item_taxable), 2)
|
|
item_total = gross_item_total
|
|
|
|
subtotal += item_taxable
|
|
tax_total += item_tax
|
|
|
|
q_item = CrmBulkQuotationItem(
|
|
item_id=str(ulid.ULID()),
|
|
sku=it.sku,
|
|
description=it.description,
|
|
quantity=it.quantity,
|
|
unit_price=it.unit_price,
|
|
tax_percent=it.tax_percent or 18.0,
|
|
total_price=item_total
|
|
)
|
|
quotation_items.append(q_item)
|
|
|
|
grand_total = max(0.0, round(subtotal + tax_total) - (data.discount_amount or 0.0))
|
|
|
|
quotation = CrmBulkQuotation(
|
|
quote_id=str(ulid.ULID()),
|
|
quote_number=quote_number,
|
|
tenant_id=self.tenant_id,
|
|
customer_id=actual_customer_id,
|
|
status="DRAFT",
|
|
valid_until=valid_until,
|
|
subtotal=subtotal,
|
|
discount_amount=data.discount_amount or 0.0,
|
|
tax_amount=tax_total,
|
|
grand_total=grand_total,
|
|
notes=data.notes,
|
|
items=quotation_items
|
|
)
|
|
self.db.add(quotation)
|
|
self.db.commit()
|
|
self.db.refresh(quotation)
|
|
|
|
publish_business_event(
|
|
event_type="BULK_QUOTE_CREATED",
|
|
payload={"quote_id": quotation.quote_id, "quote_number": quotation.quote_number, "grand_total": quotation.grand_total},
|
|
tenant_id=self.tenant_id,
|
|
aggregate_id=quotation.quote_id
|
|
)
|
|
return quotation
|
|
|
|
def list_quotations(self) -> List[CrmBulkQuotation]:
|
|
stmt = select(CrmBulkQuotation).where(CrmBulkQuotation.tenant_id == self.tenant_id, CrmBulkQuotation.deleted_at.is_(None))
|
|
return list(self.db.execute(stmt).scalars().all())
|
|
|
|
# --- GST TAX INVOICE MANAGEMENT ---
|
|
def create_invoice(self, data: CrmGstInvoiceCreate) -> CrmGstInvoice:
|
|
random_num = random.randint(1000, 9999)
|
|
invoice_number = f"IFK-INV-2026-{random_num}"
|
|
|
|
subtotal = 0.0
|
|
tax_total = 0.0
|
|
|
|
invoice_items = []
|
|
for it in data.items:
|
|
# Inclusive GST Calculation
|
|
gross_item_total = it.unit_price * it.quantity
|
|
item_tax_percent = it.tax_percent or 18.0
|
|
item_taxable = round((gross_item_total / (1 + item_tax_percent / 100.0)), 2)
|
|
item_tax = round((gross_item_total - item_taxable), 2)
|
|
item_total = gross_item_total
|
|
|
|
subtotal += item_taxable
|
|
tax_total += item_tax
|
|
|
|
inv_item = CrmInvoiceItem(
|
|
item_id=str(ulid.ULID()),
|
|
sku=it.sku,
|
|
description=it.description,
|
|
hsn_sac_code=it.hsn_sac_code or "8517",
|
|
imei_serial=it.imei_serial,
|
|
quantity=it.quantity,
|
|
unit_price=it.unit_price,
|
|
tax_percent=it.tax_percent or 18.0,
|
|
warranty_months=it.warranty_months or 6,
|
|
total_price=item_total
|
|
)
|
|
invoice_items.append(inv_item)
|
|
|
|
cgst = 0.0
|
|
sgst = 0.0
|
|
igst = 0.0
|
|
|
|
if getattr(data, 'is_interstate', False):
|
|
igst = tax_total
|
|
else:
|
|
cgst = round(tax_total / 2.0, 2)
|
|
sgst = round(tax_total / 2.0, 2)
|
|
|
|
grand_total = max(0.0, round(subtotal + tax_total) - (data.discount_amount or 0.0))
|
|
|
|
invoice = CrmGstInvoice(
|
|
invoice_id=str(ulid.ULID()),
|
|
invoice_number=invoice_number,
|
|
tenant_id=self.tenant_id,
|
|
customer_id=data.customer_id,
|
|
invoice_type=data.invoice_type or "RETAIL",
|
|
subtotal=subtotal,
|
|
discount_amount=data.discount_amount or 0.0,
|
|
cgst_amount=cgst,
|
|
sgst_amount=sgst,
|
|
igst_amount=igst,
|
|
grand_total=grand_total,
|
|
payment_status="UNPAID",
|
|
paid_amount=0.0,
|
|
notes=data.notes,
|
|
items=invoice_items
|
|
)
|
|
self.db.add(invoice)
|
|
|
|
# Update customer LTV
|
|
stmt_cust = select(CrmCustomer).where(CrmCustomer.customer_id == data.customer_id, CrmCustomer.tenant_id == self.tenant_id)
|
|
cust = self.db.execute(stmt_cust).scalar_one_or_none()
|
|
if cust:
|
|
cust.total_orders_count += 1
|
|
cust.total_lifetime_value_inr += grand_total
|
|
if cust.total_repairs_count > 0:
|
|
cust.is_dual_customer = True
|
|
|
|
self.db.commit()
|
|
self.db.refresh(invoice)
|
|
|
|
publish_business_event(
|
|
event_type="GST_INVOICE_GENERATED",
|
|
payload={"invoice_id": invoice.invoice_id, "invoice_number": invoice.invoice_number, "grand_total": invoice.grand_total},
|
|
tenant_id=self.tenant_id,
|
|
aggregate_id=invoice.invoice_id
|
|
)
|
|
return invoice
|
|
|
|
def convert_quote_to_invoice(self, quote_id: str) -> Dict[str, Any]:
|
|
stmt = select(CrmBulkQuotation).where(CrmBulkQuotation.quote_id == quote_id, CrmBulkQuotation.tenant_id == self.tenant_id)
|
|
quote = self.db.execute(stmt).scalar_one_or_none()
|
|
if not quote:
|
|
return {"error": "Quotation not found"}
|
|
|
|
quote.status = "CONVERTED"
|
|
|
|
# Categorize items into Sales (Products/Parts) vs Service (Repairs)
|
|
sales_items = []
|
|
service_items = []
|
|
|
|
for qi in quote.items:
|
|
sku_upper = (qi.sku or "").upper()
|
|
desc_lower = (qi.description or "").lower()
|
|
is_service = (
|
|
sku_upper.startswith("SVC") or
|
|
sku_upper.startswith("REPAIR") or
|
|
"repair" in desc_lower or
|
|
"service" in desc_lower or
|
|
"labor" in desc_lower
|
|
)
|
|
|
|
inv_item = CrmInvoiceItem(
|
|
item_id=str(ulid.ULID()),
|
|
sku=qi.sku,
|
|
description=qi.description,
|
|
hsn_sac_code="998729" if is_service else "8517",
|
|
quantity=qi.quantity,
|
|
unit_price=qi.unit_price,
|
|
tax_percent=qi.tax_percent or 18.0,
|
|
warranty_months=6,
|
|
total_price=qi.total_price
|
|
)
|
|
|
|
if is_service:
|
|
service_items.append(inv_item)
|
|
else:
|
|
sales_items.append(inv_item)
|
|
|
|
created_invoices = []
|
|
|
|
# Function to build an invoice helper
|
|
def build_and_add_invoice(items_list: list, inv_type: str, prefix: str) -> CrmGstInvoice:
|
|
subtotal = 0.0
|
|
tax_total = 0.0
|
|
for it in items_list:
|
|
gross = it.quantity * it.unit_price
|
|
taxable = round(gross / (1 + (it.tax_percent or 18.0) / 100.0), 2)
|
|
t = round(gross - taxable, 2)
|
|
subtotal += taxable
|
|
tax_total += t
|
|
|
|
grand_total = round(subtotal + tax_total)
|
|
cgst = round(tax_total / 2.0, 2)
|
|
sgst = round(tax_total / 2.0, 2)
|
|
|
|
inv_num = f"IFK-INV-{prefix}-2026-{random.randint(1000, 9999)}"
|
|
inv = CrmGstInvoice(
|
|
invoice_id=str(ulid.ULID()),
|
|
invoice_number=inv_num,
|
|
tenant_id=self.tenant_id,
|
|
customer_id=quote.customer_id,
|
|
invoice_type=inv_type,
|
|
subtotal=subtotal,
|
|
discount_amount=0.0,
|
|
cgst_amount=cgst,
|
|
sgst_amount=sgst,
|
|
igst_amount=0.0,
|
|
grand_total=grand_total,
|
|
payment_status="UNPAID",
|
|
paid_amount=0.0,
|
|
notes=f"Converted from Quote #{quote.quote_number} ({inv_type} portion)",
|
|
items=items_list
|
|
)
|
|
self.db.add(inv)
|
|
return inv
|
|
|
|
sales_inv = None
|
|
service_inv = None
|
|
|
|
if sales_items:
|
|
sales_inv = build_and_add_invoice(sales_items, "SALES", "SALE")
|
|
created_invoices.append(sales_inv)
|
|
|
|
if service_items:
|
|
service_inv = build_and_add_invoice(service_items, "SERVICE", "SRVC")
|
|
created_invoices.append(service_inv)
|
|
|
|
# Update customer LTV and Dual Customer stats
|
|
if quote.customer_id:
|
|
stmt_cust = select(CrmCustomer).where(CrmCustomer.customer_id == quote.customer_id, CrmCustomer.tenant_id == self.tenant_id)
|
|
cust = self.db.execute(stmt_cust).scalar_one_or_none()
|
|
if cust:
|
|
if sales_inv:
|
|
cust.total_orders_count += 1
|
|
cust.total_lifetime_value_inr += sales_inv.grand_total
|
|
if service_inv:
|
|
cust.total_repairs_count += 1
|
|
cust.total_lifetime_value_inr += service_inv.grand_total
|
|
if cust.total_orders_count > 0 and cust.total_repairs_count > 0:
|
|
cust.is_dual_customer = True
|
|
|
|
# Check if there is an associated lead to mark as CONVERTED
|
|
stmt_lead = select(CrmLead).where(
|
|
CrmLead.phone == quote.customer_id,
|
|
CrmLead.tenant_id == self.tenant_id,
|
|
CrmLead.status.in_(["QUALIFIED", "QUOTE_SENT", "QUOTE_DRAFT"])
|
|
)
|
|
associated_lead = self.db.execute(stmt_lead).scalars().first()
|
|
if associated_lead:
|
|
associated_lead.status = "CONVERTED"
|
|
|
|
self.db.commit()
|
|
for inv in created_invoices:
|
|
self.db.refresh(inv)
|
|
|
|
publish_business_event(
|
|
event_type="QUOTE_CONVERTED_TO_INVOICES",
|
|
payload={
|
|
"quote_id": quote.quote_id,
|
|
"invoices_count": len(created_invoices),
|
|
"invoice_ids": [i.invoice_id for i in created_invoices]
|
|
},
|
|
tenant_id=self.tenant_id,
|
|
aggregate_id=quote.quote_id
|
|
)
|
|
|
|
primary_invoice = created_invoices[0] if created_invoices else None
|
|
return primary_invoice
|
|
|
|
def list_invoices(self) -> List[CrmGstInvoice]:
|
|
stmt = select(CrmGstInvoice).where(CrmGstInvoice.tenant_id == self.tenant_id, CrmGstInvoice.deleted_at.is_(None))
|
|
return list(self.db.execute(stmt).scalars().all())
|
|
|
|
def record_payment(self, invoice_id: str, data: CrmRecordPayment) -> Optional[CrmGstInvoice]:
|
|
stmt = select(CrmGstInvoice).where(CrmGstInvoice.invoice_id == invoice_id, CrmGstInvoice.tenant_id == self.tenant_id)
|
|
invoice = self.db.execute(stmt).scalar_one_or_none()
|
|
if not invoice:
|
|
return None
|
|
|
|
invoice.paid_amount += data.payment_amount
|
|
if invoice.paid_amount >= invoice.grand_total:
|
|
invoice.payment_status = "PAID"
|
|
else:
|
|
invoice.payment_status = "PARTIAL"
|
|
|
|
self.db.commit()
|
|
self.db.refresh(invoice)
|
|
|
|
publish_business_event(
|
|
event_type="INVOICE_PAID",
|
|
payload={"invoice_id": invoice.invoice_id, "paid_amount": data.payment_amount, "status": invoice.payment_status},
|
|
tenant_id=self.tenant_id,
|
|
aggregate_id=invoice.invoice_id
|
|
)
|
|
return invoice
|