from datetime import datetime, timezone, timedelta from sqlalchemy.orm import Session from sqlalchemy import select from typing import List, Optional, Dict, Any import ulid from app.models.InventoryPosModel import CrmWarehouse, CrmSupplier, CrmInventoryStock, CrmPosSession, PosTerminal from app.schemas.InventoryPos import ( CrmWarehouseCreate, CrmSupplierCreate, CrmInventoryStockAdjust, CrmPosSessionOpen, CrmPosSessionClose, PosSessionExtend ) from app.core.events.event_publisher import publish_business_event from app.models.InventoryPosModel import PosSessionExtension class InventoryPosService: def __init__(self, db: Session, tenant_id: str = "tenant_default"): self.db = db self.tenant_id = tenant_id # --- WAREHOUSE MANAGEMENT --- def create_warehouse(self, data: CrmWarehouseCreate) -> CrmWarehouse: if data.is_primary: # Reset any existing primary warehouse stmt_reset = select(CrmWarehouse).where(CrmWarehouse.tenant_id == self.tenant_id, CrmWarehouse.is_primary == True) existing = self.db.execute(stmt_reset).scalars().all() for w in existing: w.is_primary = False warehouse = CrmWarehouse( warehouse_id=str(ulid.ULID()), tenant_id=self.tenant_id, name=data.name, code=data.code, address=data.address, city=data.city, state=data.state, is_primary=data.is_primary or False ) self.db.add(warehouse) self.db.commit() self.db.refresh(warehouse) return warehouse def list_warehouses(self) -> List[CrmWarehouse]: stmt = select(CrmWarehouse).where(CrmWarehouse.tenant_id == self.tenant_id, CrmWarehouse.deleted_at.is_(None)) return list(self.db.execute(stmt).scalars().all()) # --- SUPPLIER REGISTRY --- def create_supplier(self, data: CrmSupplierCreate) -> CrmSupplier: supplier = CrmSupplier( supplier_id=str(ulid.ULID()), tenant_id=self.tenant_id, company_name=data.company_name, contact_name=data.contact_name, phone=data.phone, email=data.email, gstin=data.gstin, address=data.address ) self.db.add(supplier) self.db.commit() self.db.refresh(supplier) return supplier def list_suppliers(self) -> List[CrmSupplier]: stmt = select(CrmSupplier).where(CrmSupplier.tenant_id == self.tenant_id, CrmSupplier.deleted_at.is_(None)) return list(self.db.execute(stmt).scalars().all()) # --- STOCK LEVEL ADJUSTMENTS & LOW STOCK ALERTS --- def adjust_stock(self, data: CrmInventoryStockAdjust) -> CrmInventoryStock: stmt = select(CrmInventoryStock).where( CrmInventoryStock.tenant_id == self.tenant_id, CrmInventoryStock.warehouse_id == data.warehouse_id, CrmInventoryStock.sku == data.sku ) stock = self.db.execute(stmt).scalar_one_or_none() if not stock: stock = CrmInventoryStock( stock_id=str(ulid.ULID()), tenant_id=self.tenant_id, warehouse_id=data.warehouse_id, sku=data.sku, quantity_on_hand=max(0, data.quantity_change), quantity_reserved=0, reorder_threshold=data.reorder_threshold or 5 ) self.db.add(stock) else: stock.quantity_on_hand = max(0, stock.quantity_on_hand + data.quantity_change) if data.reorder_threshold is not None: stock.reorder_threshold = data.reorder_threshold self.db.commit() self.db.refresh(stock) publish_business_event( event_type="INVENTORY_STOCK_ADJUSTED", payload={"stock_id": stock.stock_id, "sku": stock.sku, "new_quantity": stock.quantity_on_hand}, tenant_id=self.tenant_id, aggregate_id=stock.stock_id ) if stock.quantity_on_hand <= stock.reorder_threshold: publish_business_event( event_type="LOW_STOCK_ALERT", payload={"sku": stock.sku, "quantity": stock.quantity_on_hand, "threshold": stock.reorder_threshold}, tenant_id=self.tenant_id, aggregate_id=stock.stock_id ) return stock def list_stock(self, warehouse_id: Optional[str] = None) -> List[Dict[str, Any]]: stmt = select(CrmInventoryStock).where(CrmInventoryStock.tenant_id == self.tenant_id, CrmInventoryStock.deleted_at.is_(None)) if warehouse_id: stmt = stmt.where(CrmInventoryStock.warehouse_id == warehouse_id) stocks = list(self.db.execute(stmt).scalars().all()) return [ { "stock_id": s.stock_id, "tenant_id": s.tenant_id, "warehouse_id": s.warehouse_id, "sku": s.sku, "quantity_on_hand": s.quantity_on_hand, "quantity_reserved": s.quantity_reserved, "reorder_threshold": s.reorder_threshold, "is_low_stock": s.quantity_on_hand <= s.reorder_threshold } for s in stocks ] # --- POS TERMINAL SESSIONS --- def list_terminals(self, location_id: Optional[str] = None) -> List[PosTerminal]: stmt = select(PosTerminal).where(PosTerminal.tenant_id == self.tenant_id, PosTerminal.deleted_at.is_(None)) if location_id: stmt = stmt.where(PosTerminal.location_id == location_id) return list(self.db.execute(stmt).scalars().all()) def create_terminal(self, location_id: str, code: str, name: str) -> PosTerminal: terminal = PosTerminal( terminal_id=str(ulid.ULID()), tenant_id=self.tenant_id, location_id=location_id, code=code, name=name, is_active=True ) self.db.add(terminal) self.db.commit() self.db.refresh(terminal) return terminal def open_pos_session(self, user_id: str, data: CrmPosSessionOpen) -> CrmPosSession: now = datetime.now(timezone.utc) pos_session = CrmPosSession( pos_session_id=str(ulid.ULID()), tenant_id=self.tenant_id, user_id=user_id, opened_by_user_id=user_id, location_id=data.location_id, terminal_id=data.terminal_id, warehouse_id=data.warehouse_id, opening_cash=data.opening_cash if data.opening_cash is not None else 0.0, status="OPEN", opened_at=now, session_duration_minutes=540, expires_at=now + timedelta(minutes=540), notes=data.notes ) self.db.add(pos_session) self.db.commit() self.db.refresh(pos_session) publish_business_event( event_type="POS_SESSION_OPENED", payload={"pos_session_id": pos_session.pos_session_id, "user_id": user_id, "opening_cash": pos_session.opening_cash}, tenant_id=self.tenant_id, aggregate_id=pos_session.pos_session_id ) return pos_session def close_pos_session(self, pos_session_id: str, data: CrmPosSessionClose) -> Optional[CrmPosSession]: stmt = select(CrmPosSession).where( CrmPosSession.pos_session_id == pos_session_id, CrmPosSession.tenant_id == self.tenant_id ) pos_session = self.db.execute(stmt).scalar_one_or_none() if not pos_session: return None pos_session.closing_cash = data.closing_cash pos_session.expected_cash = (pos_session.opening_cash or 0.0) + (pos_session.cash_sales or 0.0) pos_session.cash_variance = (data.closing_cash or 0.0) - pos_session.expected_cash pos_session.status = "CLOSED" pos_session.closed_at = datetime.now(timezone.utc) if data.notes: pos_session.notes = data.notes self.db.commit() self.db.refresh(pos_session) return pos_session def extend_pos_session(self, pos_session_id: str, user_id: str, data: PosSessionExtend) -> Optional[CrmPosSession]: stmt = select(CrmPosSession).where( CrmPosSession.pos_session_id == pos_session_id, CrmPosSession.tenant_id == self.tenant_id ) pos_session = self.db.execute(stmt).scalar_one_or_none() if not pos_session or pos_session.status != "OPEN": return None # Check max extensions (e.g. 1) ext_count = self.db.execute(select(PosSessionExtension).where(PosSessionExtension.session_id == pos_session_id)).scalars().all() if len(ext_count) >= 1: raise ValueError("Maximum extension limit reached.") extension = PosSessionExtension( id=str(ulid.ULID()), session_id=pos_session.pos_session_id, extension_minutes=data.extension_minutes, extended_by=user_id, reason=data.reason, created_at=datetime.now(timezone.utc) ) self.db.add(extension) pos_session.expires_at = pos_session.expires_at + timedelta(minutes=data.extension_minutes) self.db.commit() self.db.refresh(pos_session) publish_business_event( event_type="POS_SESSION_EXTENDED", payload={"pos_session_id": pos_session.pos_session_id, "extended_by": user_id, "minutes": data.extension_minutes}, tenant_id=self.tenant_id, aggregate_id=pos_session.pos_session_id ) return pos_session def list_pos_sessions(self, status: Optional[str] = None, location_id: Optional[str] = None, user_id: Optional[str] = None) -> List[Dict[str, Any]]: stmt = select(CrmPosSession).where(CrmPosSession.tenant_id == self.tenant_id, CrmPosSession.deleted_at.is_(None)) if status: stmt = stmt.where(CrmPosSession.status == status) if location_id: stmt = stmt.where(CrmPosSession.location_id == location_id) if user_id: stmt = stmt.where(CrmPosSession.opened_by_user_id == user_id) sessions = list(self.db.execute(stmt).scalars().all()) return [ { "session_id": s.pos_session_id, "pos_session_id": s.pos_session_id, "tenant_id": s.tenant_id, "location_id": s.location_id, "terminal_id": s.terminal_id, "warehouse_id": s.warehouse_id, "user_id": s.opened_by_user_id, "opened_by_user_id": s.opened_by_user_id, "cashier_user_id": s.opened_by_user_id, "opening_cash": s.opening_cash, "opening_balance": s.opening_cash, "closing_cash": s.closing_cash, "closing_balance": s.closing_cash or 0.0, "expected_cash": s.expected_cash, "cash_variance": s.cash_variance, "ecom_sales_count": s.ecom_sales_count or 0, "ecom_sales_amount": s.ecom_sales_amount or 0.0, "service_sales_count": s.service_sales_count or 0, "service_sales_amount": s.service_sales_amount or 0.0, "courier_charges": s.courier_charges or 0.0, "cash_sales": s.cash_sales or 0.0, "upi_sales": s.upi_sales or 0.0, "card_sales": s.card_sales or 0.0, "other_sales": s.other_sales or 0.0, "status": s.status, "opened_at": s.opened_at.isoformat() + "Z" if s.opened_at else None, "closed_at": s.closed_at.isoformat() + "Z" if s.closed_at else None, "session_duration_minutes": s.session_duration_minutes, "expires_at": s.expires_at.isoformat() + "Z" if s.expires_at else None, "notes": s.notes } for s in sessions ] def record_sale_in_active_session(self, user_id: str, amount: float, domain: str, payment_method: str, cash_amount: float = 0.0, digital_amount: float = 0.0, digital_method: Optional[str] = None) -> bool: stmt = select(CrmPosSession).where( CrmPosSession.opened_by_user_id == user_id, CrmPosSession.status == "OPEN", CrmPosSession.tenant_id == self.tenant_id ) session = self.db.execute(stmt).scalar_one_or_none() if not session: return False if domain == "ECOM": session.ecom_sales_count += 1 session.ecom_sales_amount += amount elif domain == "SERVICE": session.service_sales_count += 1 session.service_sales_amount += amount pm = payment_method.upper() if pm == "MIXED_PAYMENT": session.cash_sales += cash_amount if digital_method: dm = digital_method.upper() if dm == "UPI": session.upi_sales += digital_amount elif dm in ["CARD", "CC", "DC"]: session.card_sales += digital_amount else: session.other_sales += digital_amount else: session.other_sales += digital_amount elif pm == "CASH": session.cash_sales += amount elif pm == "UPI": session.upi_sales += amount elif pm in ["CARD", "CC", "DC"]: session.card_sales += amount else: session.other_sales += amount self.db.commit() return True