from datetime import datetime, timezone 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 from app.schemas.InventoryPos import ( CrmWarehouseCreate, CrmSupplierCreate, CrmInventoryStockAdjust, CrmPosSessionOpen, CrmPosSessionClose ) from app.core.events.event_publisher import publish_business_event 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: pos_session = CrmPosSession( pos_session_id=str(ulid.ULID()), tenant_id=self.tenant_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=datetime.now(timezone.utc), 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 list_pos_sessions(self, status: Optional[str] = None, location_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) 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() if s.opened_at else None, "closed_at": s.closed_at.isoformat() if s.closed_at else None, "notes": s.notes } for s in sessions ]