236 lines
8.5 KiB
Python
236 lines
8.5 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
|
|
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 = f"IFK-QT-2026-{random_num}"
|
|
valid_until = datetime.now(timezone.utc) + timedelta(days=data.valid_days or 7)
|
|
|
|
subtotal = 0.0
|
|
tax_total = 0.0
|
|
|
|
quotation_items = []
|
|
for it in data.items:
|
|
item_subtotal = it.unit_price * it.quantity
|
|
item_tax = item_subtotal * (it.tax_percent / 100.0)
|
|
item_total = item_subtotal + item_tax
|
|
|
|
subtotal += item_subtotal
|
|
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, (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=data.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:
|
|
item_subtotal = it.unit_price * it.quantity
|
|
item_tax = item_subtotal * (it.tax_percent / 100.0)
|
|
item_total = item_subtotal + item_tax
|
|
|
|
subtotal += item_subtotal
|
|
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 data.is_interstate:
|
|
igst = tax_total
|
|
else:
|
|
cgst = tax_total / 2.0
|
|
sgst = tax_total / 2.0
|
|
|
|
grand_total = max(0.0, (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) -> Optional[CrmGstInvoice]:
|
|
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 None
|
|
|
|
quote.status = "CONVERTED"
|
|
|
|
invoice_items_create = [
|
|
CrmInvoiceItem(
|
|
item_id=str(ulid.ULID()),
|
|
sku=qi.sku,
|
|
description=qi.description,
|
|
hsn_sac_code="8517",
|
|
quantity=qi.quantity,
|
|
unit_price=qi.unit_price,
|
|
tax_percent=qi.tax_percent,
|
|
warranty_months=6,
|
|
total_price=qi.total_price
|
|
)
|
|
for qi in quote.items
|
|
]
|
|
|
|
tax_total = quote.tax_amount
|
|
invoice_number = f"IFK-INV-2026-{random.randint(1000, 9999)}"
|
|
|
|
invoice = CrmGstInvoice(
|
|
invoice_id=str(ulid.ULID()),
|
|
invoice_number=invoice_number,
|
|
tenant_id=self.tenant_id,
|
|
customer_id=quote.customer_id,
|
|
invoice_type="B2B",
|
|
subtotal=quote.subtotal,
|
|
discount_amount=quote.discount_amount,
|
|
cgst_amount=tax_total / 2.0,
|
|
sgst_amount=tax_total / 2.0,
|
|
igst_amount=0.0,
|
|
grand_total=quote.grand_total,
|
|
payment_status="UNPAID",
|
|
paid_amount=0.0,
|
|
notes=f"Converted from Bulk Quote #{quote.quote_number}",
|
|
items=invoice_items_create
|
|
)
|
|
self.db.add(invoice)
|
|
self.db.commit()
|
|
self.db.refresh(invoice)
|
|
return 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
|