Add supplier and imporve inventory frontend
This commit is contained in:
@@ -13,11 +13,10 @@ class AlertProcessorConfig(BaseServiceSettings):
|
||||
APP_NAME: str = "Alert Processor Service"
|
||||
DESCRIPTION: str = "Central alert and recommendation processor"
|
||||
|
||||
# Use the notification database for alert storage
|
||||
# This makes sense since alerts and notifications are closely related
|
||||
# Use dedicated database for alert storage
|
||||
DATABASE_URL: str = os.getenv(
|
||||
"NOTIFICATION_DATABASE_URL",
|
||||
"postgresql+asyncpg://notification_user:notification_pass123@notification-db:5432/notification_db"
|
||||
"ALERT_PROCESSOR_DATABASE_URL",
|
||||
"postgresql+asyncpg://alert_processor_user:alert_processor_pass123@alert-processor-db:5432/alert_processor_db"
|
||||
)
|
||||
|
||||
# Use dedicated Redis DB for alert processing
|
||||
|
||||
@@ -206,42 +206,47 @@ class AlertProcessorService:
|
||||
|
||||
async def store_item(self, item: dict) -> dict:
|
||||
"""Store alert or recommendation in database"""
|
||||
from sqlalchemy import text
|
||||
|
||||
query = text("""
|
||||
INSERT INTO alerts (
|
||||
id, tenant_id, item_type, alert_type, severity, status,
|
||||
service, title, message, actions, metadata,
|
||||
created_at
|
||||
) VALUES (:id, :tenant_id, :item_type, :alert_type, :severity, :status,
|
||||
:service, :title, :message, :actions, :metadata, :created_at)
|
||||
RETURNING *
|
||||
""")
|
||||
|
||||
from app.models.alerts import Alert, AlertSeverity, AlertStatus
|
||||
from sqlalchemy import select
|
||||
|
||||
async with self.db_manager.get_session() as session:
|
||||
result = await session.execute(
|
||||
query,
|
||||
{
|
||||
'id': item['id'],
|
||||
'tenant_id': item['tenant_id'],
|
||||
'item_type': item['item_type'], # 'alert' or 'recommendation'
|
||||
'alert_type': item['type'],
|
||||
'severity': item['severity'],
|
||||
'status': 'active',
|
||||
'service': item['service'],
|
||||
'title': item['title'],
|
||||
'message': item['message'],
|
||||
'actions': json.dumps(item.get('actions', [])),
|
||||
'metadata': json.dumps(item.get('metadata', {})),
|
||||
'created_at': item['timestamp']
|
||||
}
|
||||
# Create alert instance
|
||||
alert = Alert(
|
||||
id=item['id'],
|
||||
tenant_id=item['tenant_id'],
|
||||
item_type=item['item_type'], # 'alert' or 'recommendation'
|
||||
alert_type=item['type'],
|
||||
severity=AlertSeverity(item['severity']),
|
||||
status=AlertStatus.ACTIVE,
|
||||
service=item['service'],
|
||||
title=item['title'],
|
||||
message=item['message'],
|
||||
actions=item.get('actions', []),
|
||||
alert_metadata=item.get('metadata', {}),
|
||||
created_at=datetime.fromisoformat(item['timestamp']) if isinstance(item['timestamp'], str) else item['timestamp']
|
||||
)
|
||||
|
||||
row = result.fetchone()
|
||||
|
||||
session.add(alert)
|
||||
await session.commit()
|
||||
|
||||
await session.refresh(alert)
|
||||
|
||||
logger.debug("Item stored in database", item_id=item['id'])
|
||||
return dict(row._mapping)
|
||||
|
||||
# Convert to dict for return
|
||||
return {
|
||||
'id': str(alert.id),
|
||||
'tenant_id': str(alert.tenant_id),
|
||||
'item_type': alert.item_type,
|
||||
'alert_type': alert.alert_type,
|
||||
'severity': alert.severity.value,
|
||||
'status': alert.status.value,
|
||||
'service': alert.service,
|
||||
'title': alert.title,
|
||||
'message': alert.message,
|
||||
'actions': alert.actions,
|
||||
'metadata': alert.alert_metadata,
|
||||
'created_at': alert.created_at
|
||||
}
|
||||
|
||||
async def stream_to_sse(self, tenant_id: str, item: dict):
|
||||
"""Publish item to Redis for SSE streaming"""
|
||||
|
||||
1
services/alert_processor/app/models/__init__.py
Normal file
1
services/alert_processor/app/models/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# services/alert_processor/app/models/__init__.py
|
||||
56
services/alert_processor/app/models/alerts.py
Normal file
56
services/alert_processor/app/models/alerts.py
Normal file
@@ -0,0 +1,56 @@
|
||||
# services/alert_processor/app/models/alerts.py
|
||||
"""
|
||||
Alert models for the alert processor service
|
||||
"""
|
||||
|
||||
from sqlalchemy import Column, String, Text, DateTime, JSON, Enum
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
import enum
|
||||
|
||||
from shared.database.base import Base
|
||||
|
||||
|
||||
class AlertStatus(enum.Enum):
|
||||
"""Alert status values"""
|
||||
ACTIVE = "active"
|
||||
RESOLVED = "resolved"
|
||||
ACKNOWLEDGED = "acknowledged"
|
||||
IGNORED = "ignored"
|
||||
|
||||
|
||||
class AlertSeverity(enum.Enum):
|
||||
"""Alert severity levels"""
|
||||
LOW = "low"
|
||||
MEDIUM = "medium"
|
||||
HIGH = "high"
|
||||
URGENT = "urgent"
|
||||
|
||||
|
||||
class Alert(Base):
|
||||
"""Alert records for the alert processor service"""
|
||||
__tablename__ = "alerts"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
tenant_id = Column(UUID(as_uuid=True), nullable=False, index=True)
|
||||
|
||||
# Alert classification
|
||||
item_type = Column(String(50), nullable=False) # 'alert' or 'recommendation'
|
||||
alert_type = Column(String(100), nullable=False) # e.g., 'overstock_warning'
|
||||
severity = Column(Enum(AlertSeverity), nullable=False, index=True)
|
||||
status = Column(Enum(AlertStatus), default=AlertStatus.ACTIVE, index=True)
|
||||
|
||||
# Source and content
|
||||
service = Column(String(100), nullable=False) # originating service
|
||||
title = Column(String(255), nullable=False)
|
||||
message = Column(Text, nullable=False)
|
||||
|
||||
# Actions and metadata
|
||||
actions = Column(JSON, nullable=True) # List of available actions
|
||||
alert_metadata = Column(JSON, nullable=True) # Additional alert-specific data
|
||||
|
||||
# Timestamps
|
||||
created_at = Column(DateTime, default=datetime.utcnow, index=True)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
resolved_at = Column(DateTime, nullable=True)
|
||||
93
services/alert_processor/migrations/alembic.ini
Normal file
93
services/alert_processor/migrations/alembic.ini
Normal file
@@ -0,0 +1,93 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = .
|
||||
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python-dateutil library that can be
|
||||
# installed by adding `alembic[tz]` to the pip requirements
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version number format
|
||||
# Uses Alembic datetime format
|
||||
version_num_format = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d
|
||||
|
||||
# version name format
|
||||
version_path_separator = /
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = postgresql+asyncpg://alert_processor_user:alert_processor_pass123@alert-processor-db:5432/alert_processor_db
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
109
services/alert_processor/migrations/env.py
Normal file
109
services/alert_processor/migrations/env.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
Alembic environment configuration for Alert Processor Service
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||
|
||||
from alembic import context
|
||||
|
||||
# Add the app directory to the path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
# Import models to ensure they're registered
|
||||
from app.models.alerts import * # noqa
|
||||
from shared.database.base import Base
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Set the SQLAlchemy URL from environment variable if available
|
||||
database_url = os.getenv('ALERT_PROCESSOR_DATABASE_URL')
|
||||
if database_url:
|
||||
config.set_main_option('sqlalchemy.url', database_url)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
compare_type=True,
|
||||
compare_server_default=True,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection: Connection) -> None:
|
||||
"""Run migrations with database connection"""
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
compare_type=True,
|
||||
compare_server_default=True,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
"""Run migrations in async mode"""
|
||||
connectable = async_engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode."""
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
24
services/alert_processor/migrations/script.py.mako
Normal file
24
services/alert_processor/migrations/script.py.mako
Normal file
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Initial alerts table
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2025-09-18 23:17:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '001'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Create enum types
|
||||
alert_status_enum = postgresql.ENUM('active', 'resolved', 'acknowledged', 'ignored', name='alertstatus')
|
||||
alert_severity_enum = postgresql.ENUM('low', 'medium', 'high', 'urgent', name='alertseverity')
|
||||
|
||||
alert_status_enum.create(op.get_bind())
|
||||
alert_severity_enum.create(op.get_bind())
|
||||
|
||||
# Create alerts table
|
||||
op.create_table('alerts',
|
||||
sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column('item_type', sa.String(length=50), nullable=False),
|
||||
sa.Column('alert_type', sa.String(length=100), nullable=False),
|
||||
sa.Column('severity', alert_severity_enum, nullable=False),
|
||||
sa.Column('status', alert_status_enum, nullable=False),
|
||||
sa.Column('service', sa.String(length=100), nullable=False),
|
||||
sa.Column('title', sa.String(length=255), nullable=False),
|
||||
sa.Column('message', sa.Text(), nullable=False),
|
||||
sa.Column('actions', sa.JSON(), nullable=True),
|
||||
sa.Column('metadata', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('resolved_at', sa.DateTime(), nullable=True),
|
||||
)
|
||||
|
||||
# Create indexes
|
||||
op.create_index('ix_alerts_tenant_id', 'alerts', ['tenant_id'])
|
||||
op.create_index('ix_alerts_severity', 'alerts', ['severity'])
|
||||
op.create_index('ix_alerts_status', 'alerts', ['status'])
|
||||
op.create_index('ix_alerts_created_at', 'alerts', ['created_at'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Drop indexes
|
||||
op.drop_index('ix_alerts_created_at', 'alerts')
|
||||
op.drop_index('ix_alerts_status', 'alerts')
|
||||
op.drop_index('ix_alerts_severity', 'alerts')
|
||||
op.drop_index('ix_alerts_tenant_id', 'alerts')
|
||||
|
||||
# Drop table
|
||||
op.drop_table('alerts')
|
||||
|
||||
# Drop enum types
|
||||
op.execute('DROP TYPE alertseverity')
|
||||
op.execute('DROP TYPE alertstatus')
|
||||
@@ -106,7 +106,6 @@ class Ingredient(Base):
|
||||
# Product details
|
||||
description = Column(Text, nullable=True)
|
||||
brand = Column(String(100), nullable=True) # Brand or central baker name
|
||||
supplier_name = Column(String(200), nullable=True) # Central baker or distributor
|
||||
unit_of_measure = Column(SQLEnum(UnitOfMeasure), nullable=False)
|
||||
package_size = Column(Float, nullable=True) # Size per package/unit
|
||||
|
||||
@@ -158,7 +157,6 @@ class Ingredient(Base):
|
||||
Index('idx_ingredients_ingredient_category', 'tenant_id', 'ingredient_category', 'is_active'),
|
||||
Index('idx_ingredients_product_category', 'tenant_id', 'product_category', 'is_active'),
|
||||
Index('idx_ingredients_stock_levels', 'tenant_id', 'low_stock_threshold', 'reorder_point'),
|
||||
Index('idx_ingredients_central_baker', 'tenant_id', 'supplier_name', 'product_type'),
|
||||
)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
@@ -194,7 +192,6 @@ class Ingredient(Base):
|
||||
'subcategory': self.subcategory,
|
||||
'description': self.description,
|
||||
'brand': self.brand,
|
||||
'supplier_name': self.supplier_name,
|
||||
'unit_of_measure': self.unit_of_measure.value if self.unit_of_measure else None,
|
||||
'package_size': self.package_size,
|
||||
'average_cost': float(self.average_cost) if self.average_cost else None,
|
||||
@@ -230,6 +227,9 @@ class Stock(Base):
|
||||
tenant_id = Column(UUID(as_uuid=True), nullable=False, index=True)
|
||||
ingredient_id = Column(UUID(as_uuid=True), ForeignKey('ingredients.id'), nullable=False, index=True)
|
||||
|
||||
# Supplier association
|
||||
supplier_id = Column(UUID(as_uuid=True), nullable=True, index=True)
|
||||
|
||||
# Stock identification
|
||||
batch_number = Column(String(100), nullable=True, index=True)
|
||||
lot_number = Column(String(100), nullable=True, index=True)
|
||||
|
||||
@@ -61,13 +61,6 @@ class IngredientCreate(InventoryBaseSchema):
|
||||
is_perishable: bool = Field(False, description="Is perishable")
|
||||
allergen_info: Optional[Dict[str, Any]] = Field(None, description="Allergen information")
|
||||
|
||||
@validator('storage_temperature_max')
|
||||
def validate_temperature_range(cls, v, values):
|
||||
if v is not None and 'storage_temperature_min' in values and values['storage_temperature_min'] is not None:
|
||||
if v <= values['storage_temperature_min']:
|
||||
raise ValueError('Max temperature must be greater than min temperature')
|
||||
return v
|
||||
|
||||
@validator('reorder_point')
|
||||
def validate_reorder_point(cls, v, values):
|
||||
if 'low_stock_threshold' in values and v <= values['low_stock_threshold']:
|
||||
@@ -147,6 +140,7 @@ class IngredientResponse(InventoryBaseSchema):
|
||||
class StockCreate(InventoryBaseSchema):
|
||||
"""Schema for creating stock entries"""
|
||||
ingredient_id: str = Field(..., description="Ingredient ID")
|
||||
supplier_id: Optional[str] = Field(None, description="Supplier ID")
|
||||
batch_number: Optional[str] = Field(None, max_length=100, description="Batch number")
|
||||
lot_number: Optional[str] = Field(None, max_length=100, description="Lot number")
|
||||
supplier_batch_ref: Optional[str] = Field(None, max_length=100, description="Supplier batch reference")
|
||||
@@ -181,9 +175,16 @@ class StockCreate(InventoryBaseSchema):
|
||||
shelf_life_days: Optional[int] = Field(None, gt=0, description="Batch-specific shelf life in days")
|
||||
storage_instructions: Optional[str] = Field(None, description="Batch-specific storage instructions")
|
||||
|
||||
|
||||
@validator('storage_temperature_max')
|
||||
def validate_temperature_range(cls, v, values):
|
||||
min_temp = values.get('storage_temperature_min')
|
||||
if v is not None and min_temp is not None and v <= min_temp:
|
||||
raise ValueError('Max temperature must be greater than min temperature')
|
||||
return v
|
||||
|
||||
class StockUpdate(InventoryBaseSchema):
|
||||
"""Schema for updating stock entries"""
|
||||
supplier_id: Optional[str] = Field(None, description="Supplier ID")
|
||||
batch_number: Optional[str] = Field(None, max_length=100, description="Batch number")
|
||||
lot_number: Optional[str] = Field(None, max_length=100, description="Lot number")
|
||||
supplier_batch_ref: Optional[str] = Field(None, max_length=100, description="Supplier batch reference")
|
||||
@@ -226,6 +227,7 @@ class StockResponse(InventoryBaseSchema):
|
||||
id: str
|
||||
tenant_id: str
|
||||
ingredient_id: str
|
||||
supplier_id: Optional[str]
|
||||
batch_number: Optional[str]
|
||||
lot_number: Optional[str]
|
||||
supplier_batch_ref: Optional[str]
|
||||
|
||||
@@ -451,17 +451,17 @@ class DashboardService:
|
||||
SELECT
|
||||
'stock_movement' as activity_type,
|
||||
CASE
|
||||
WHEN movement_type = 'purchase' THEN 'Stock added: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
WHEN movement_type = 'production_use' THEN 'Stock consumed: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
WHEN movement_type = 'waste' THEN 'Stock wasted: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
WHEN movement_type = 'adjustment' THEN 'Stock adjusted: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
WHEN movement_type = 'PURCHASE' THEN 'Stock added: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
WHEN movement_type = 'PRODUCTION_USE' THEN 'Stock consumed: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
WHEN movement_type = 'WASTE' THEN 'Stock wasted: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
WHEN movement_type = 'ADJUSTMENT' THEN 'Stock adjusted: ' || i.name || ' (' || sm.quantity || ' ' || i.unit_of_measure::text || ')'
|
||||
ELSE 'Stock movement: ' || i.name
|
||||
END as description,
|
||||
sm.movement_date as timestamp,
|
||||
sm.created_by as user_id,
|
||||
CASE
|
||||
WHEN movement_type = 'waste' THEN 'high'
|
||||
WHEN movement_type = 'adjustment' THEN 'medium'
|
||||
WHEN movement_type = 'WASTE' THEN 'high'
|
||||
WHEN movement_type = 'ADJUSTMENT' THEN 'medium'
|
||||
ELSE 'low'
|
||||
END as impact_level,
|
||||
sm.id as entity_id,
|
||||
@@ -613,17 +613,22 @@ class DashboardService:
|
||||
|
||||
# Get ingredient metrics
|
||||
query = """
|
||||
SELECT
|
||||
SELECT
|
||||
COUNT(*) as total_ingredients,
|
||||
COUNT(CASE WHEN product_type = 'finished_product' THEN 1 END) as finished_products,
|
||||
COUNT(CASE WHEN product_type = 'ingredient' THEN 1 END) as raw_ingredients,
|
||||
COUNT(DISTINCT supplier_name) as supplier_count,
|
||||
COUNT(DISTINCT st.supplier_id) as supplier_count,
|
||||
AVG(CASE WHEN s.available_quantity IS NOT NULL THEN s.available_quantity ELSE 0 END) as avg_stock_level
|
||||
FROM ingredients i
|
||||
LEFT JOIN (
|
||||
SELECT ingredient_id, SUM(available_quantity) as available_quantity
|
||||
FROM stock WHERE tenant_id = :tenant_id GROUP BY ingredient_id
|
||||
) s ON i.id = s.ingredient_id
|
||||
LEFT JOIN (
|
||||
SELECT ingredient_id, supplier_id
|
||||
FROM stock WHERE tenant_id = :tenant_id AND supplier_id IS NOT NULL
|
||||
GROUP BY ingredient_id, supplier_id
|
||||
) st ON i.id = st.ingredient_id
|
||||
WHERE i.tenant_id = :tenant_id AND i.is_active = true
|
||||
"""
|
||||
|
||||
|
||||
@@ -428,17 +428,17 @@ class InventoryAlertService(BaseAlertService, AlertServiceMixin):
|
||||
i.low_stock_threshold as minimum_stock,
|
||||
i.max_stock_level as maximum_stock,
|
||||
COALESCE(SUM(s.current_quantity), 0) as current_stock,
|
||||
AVG(sm.quantity) FILTER (WHERE sm.movement_type = 'production_use'
|
||||
AVG(sm.quantity) FILTER (WHERE sm.movement_type = 'PRODUCTION_USE'
|
||||
AND sm.created_at > CURRENT_DATE - INTERVAL '30 days') as avg_daily_usage,
|
||||
COUNT(sm.id) FILTER (WHERE sm.movement_type = 'production_use'
|
||||
COUNT(sm.id) FILTER (WHERE sm.movement_type = 'PRODUCTION_USE'
|
||||
AND sm.created_at > CURRENT_DATE - INTERVAL '30 days') as usage_days,
|
||||
MAX(sm.created_at) FILTER (WHERE sm.movement_type = 'production_use') as last_used
|
||||
MAX(sm.created_at) FILTER (WHERE sm.movement_type = 'PRODUCTION_USE') as last_used
|
||||
FROM ingredients i
|
||||
LEFT JOIN stock s ON s.ingredient_id = i.id AND s.is_available = true
|
||||
LEFT JOIN stock_movements sm ON sm.ingredient_id = i.id
|
||||
WHERE i.is_active = true AND i.tenant_id = :tenant_id
|
||||
GROUP BY i.id, i.name, i.tenant_id, i.low_stock_threshold, i.max_stock_level
|
||||
HAVING COUNT(sm.id) FILTER (WHERE sm.movement_type = 'production_use'
|
||||
HAVING COUNT(sm.id) FILTER (WHERE sm.movement_type = 'PRODUCTION_USE'
|
||||
AND sm.created_at > CURRENT_DATE - INTERVAL '30 days') >= 3
|
||||
),
|
||||
recommendations AS (
|
||||
|
||||
@@ -162,23 +162,23 @@ class NotificationLog(Base):
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
notification_id = Column(UUID(as_uuid=True), nullable=False, index=True)
|
||||
|
||||
|
||||
# Attempt details
|
||||
attempt_number = Column(Integer, nullable=False)
|
||||
status = Column(Enum(NotificationStatus), nullable=False)
|
||||
|
||||
|
||||
# Provider details
|
||||
provider = Column(String(50), nullable=True) # e.g., "gmail", "twilio"
|
||||
provider_message_id = Column(String(255), nullable=True)
|
||||
provider_response = Column(JSON, nullable=True)
|
||||
|
||||
|
||||
# Timing
|
||||
attempted_at = Column(DateTime, default=datetime.utcnow)
|
||||
response_time_ms = Column(Integer, nullable=True)
|
||||
|
||||
|
||||
# Error details
|
||||
error_code = Column(String(50), nullable=True)
|
||||
error_message = Column(Text, nullable=True)
|
||||
|
||||
|
||||
# Additional metadata
|
||||
log_metadata = Column(JSON, nullable=True)
|
||||
@@ -8,7 +8,7 @@ from typing import List, Optional
|
||||
from uuid import UUID
|
||||
import structlog
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.core.database import get_db
|
||||
from app.services.supplier_service import SupplierService
|
||||
from app.schemas.suppliers import (
|
||||
@@ -27,7 +27,7 @@ async def create_supplier(
|
||||
supplier_data: SupplierCreate,
|
||||
tenant_id: str = Path(..., description="Tenant ID"),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user_dep),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
|
||||
try:
|
||||
@@ -54,7 +54,7 @@ async def list_suppliers(
|
||||
status: Optional[str] = Query(None, description="Status filter"),
|
||||
limit: int = Query(50, ge=1, le=1000, description="Number of results to return"),
|
||||
offset: int = Query(0, ge=0, description="Number of results to skip"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""List suppliers with optional filters"""
|
||||
# require_permissions(current_user, ["suppliers:read"])
|
||||
@@ -81,7 +81,7 @@ async def list_suppliers(
|
||||
@router.get("/statistics", response_model=SupplierStatistics)
|
||||
async def get_supplier_statistics(
|
||||
tenant_id: str = Path(..., description="Tenant ID"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Get supplier statistics for dashboard"""
|
||||
# require_permissions(current_user, ["suppliers:read"])
|
||||
@@ -98,7 +98,7 @@ async def get_supplier_statistics(
|
||||
@router.get("/active", response_model=List[SupplierSummary])
|
||||
async def get_active_suppliers(
|
||||
tenant_id: str = Path(..., description="Tenant ID"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Get all active suppliers"""
|
||||
# require_permissions(current_user, ["suppliers:read"])
|
||||
@@ -116,7 +116,7 @@ async def get_active_suppliers(
|
||||
async def get_top_suppliers(
|
||||
tenant_id: str = Path(..., description="Tenant ID"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Number of top suppliers to return"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Get top performing suppliers"""
|
||||
# require_permissions(current_user, ["suppliers:read"])
|
||||
@@ -134,7 +134,7 @@ async def get_top_suppliers(
|
||||
async def get_suppliers_needing_review(
|
||||
tenant_id: str = Path(..., description="Tenant ID"),
|
||||
days_since_last_order: int = Query(30, ge=1, le=365, description="Days since last order"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Get suppliers that may need performance review"""
|
||||
# require_permissions(current_user, ["suppliers:read"])
|
||||
@@ -154,7 +154,7 @@ async def get_suppliers_needing_review(
|
||||
async def get_supplier(
|
||||
supplier_id: UUID = Path(..., description="Supplier ID"),
|
||||
tenant_id: str = Path(..., description="Tenant ID"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Get supplier by ID"""
|
||||
# require_permissions(current_user, ["suppliers:read"])
|
||||
@@ -179,7 +179,7 @@ async def update_supplier(
|
||||
supplier_data: SupplierUpdate,
|
||||
supplier_id: UUID = Path(..., description="Supplier ID"),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user_dep),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Update supplier information"""
|
||||
# require_permissions(current_user, ["suppliers:update"])
|
||||
@@ -214,7 +214,7 @@ async def update_supplier(
|
||||
@router.delete("/{supplier_id}")
|
||||
async def delete_supplier(
|
||||
supplier_id: UUID = Path(..., description="Supplier ID"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Delete supplier (soft delete)"""
|
||||
# require_permissions(current_user, ["suppliers:delete"])
|
||||
@@ -244,7 +244,7 @@ async def approve_supplier(
|
||||
approval_data: SupplierApproval,
|
||||
supplier_id: UUID = Path(..., description="Supplier ID"),
|
||||
current_user: Dict[str, Any] = Depends(get_current_user_dep),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Approve or reject a pending supplier"""
|
||||
# require_permissions(current_user, ["suppliers:approve"])
|
||||
@@ -289,7 +289,7 @@ async def approve_supplier(
|
||||
async def get_suppliers_by_type(
|
||||
supplier_type: str = Path(..., description="Supplier type"),
|
||||
tenant_id: str = Path(..., description="Tenant ID"),
|
||||
db: Session = Depends(get_db)
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Get suppliers by type"""
|
||||
# require_permissions(current_user, ["suppliers:read"])
|
||||
|
||||
@@ -18,84 +18,84 @@ from shared.database.base import Base
|
||||
|
||||
class SupplierType(enum.Enum):
|
||||
"""Types of suppliers"""
|
||||
INGREDIENTS = "ingredients" # Raw materials supplier
|
||||
PACKAGING = "packaging" # Packaging materials
|
||||
EQUIPMENT = "equipment" # Bakery equipment
|
||||
SERVICES = "services" # Service providers
|
||||
UTILITIES = "utilities" # Utilities (gas, electricity)
|
||||
MULTI = "multi" # Multi-category supplier
|
||||
ingredients = "ingredients" # Raw materials supplier
|
||||
packaging = "packaging" # Packaging materials
|
||||
equipment = "equipment" # Bakery equipment
|
||||
services = "services" # Service providers
|
||||
utilities = "utilities" # Utilities (gas, electricity)
|
||||
multi = "multi" # Multi-category supplier
|
||||
|
||||
|
||||
class SupplierStatus(enum.Enum):
|
||||
"""Supplier lifecycle status"""
|
||||
ACTIVE = "active"
|
||||
INACTIVE = "inactive"
|
||||
PENDING_APPROVAL = "pending_approval"
|
||||
SUSPENDED = "suspended"
|
||||
BLACKLISTED = "blacklisted"
|
||||
active = "active"
|
||||
inactive = "inactive"
|
||||
pending_approval = "pending_approval"
|
||||
suspended = "suspended"
|
||||
blacklisted = "blacklisted"
|
||||
|
||||
|
||||
class PaymentTerms(enum.Enum):
|
||||
"""Payment terms with suppliers"""
|
||||
CASH_ON_DELIVERY = "cod"
|
||||
NET_15 = "net_15"
|
||||
NET_30 = "net_30"
|
||||
NET_45 = "net_45"
|
||||
NET_60 = "net_60"
|
||||
PREPAID = "prepaid"
|
||||
CREDIT_TERMS = "credit_terms"
|
||||
cod = "cod"
|
||||
net_15 = "net_15"
|
||||
net_30 = "net_30"
|
||||
net_45 = "net_45"
|
||||
net_60 = "net_60"
|
||||
prepaid = "prepaid"
|
||||
credit_terms = "credit_terms"
|
||||
|
||||
|
||||
class PurchaseOrderStatus(enum.Enum):
|
||||
"""Purchase order lifecycle status"""
|
||||
DRAFT = "draft"
|
||||
PENDING_APPROVAL = "pending_approval"
|
||||
APPROVED = "approved"
|
||||
SENT_TO_SUPPLIER = "sent_to_supplier"
|
||||
CONFIRMED = "confirmed"
|
||||
PARTIALLY_RECEIVED = "partially_received"
|
||||
COMPLETED = "completed"
|
||||
CANCELLED = "cancelled"
|
||||
DISPUTED = "disputed"
|
||||
draft = "draft"
|
||||
pending_approval = "pending_approval"
|
||||
approved = "approved"
|
||||
sent_to_supplier = "sent_to_supplier"
|
||||
confirmed = "confirmed"
|
||||
partially_received = "partially_received"
|
||||
completed = "completed"
|
||||
cancelled = "cancelled"
|
||||
disputed = "disputed"
|
||||
|
||||
|
||||
class DeliveryStatus(enum.Enum):
|
||||
"""Delivery status tracking"""
|
||||
SCHEDULED = "scheduled"
|
||||
IN_TRANSIT = "in_transit"
|
||||
OUT_FOR_DELIVERY = "out_for_delivery"
|
||||
DELIVERED = "delivered"
|
||||
PARTIALLY_DELIVERED = "partially_delivered"
|
||||
FAILED_DELIVERY = "failed_delivery"
|
||||
RETURNED = "returned"
|
||||
scheduled = "scheduled"
|
||||
in_transit = "in_transit"
|
||||
out_for_delivery = "out_for_delivery"
|
||||
delivered = "delivered"
|
||||
partially_delivered = "partially_delivered"
|
||||
failed_delivery = "failed_delivery"
|
||||
returned = "returned"
|
||||
|
||||
|
||||
class QualityRating(enum.Enum):
|
||||
"""Quality rating scale"""
|
||||
EXCELLENT = 5
|
||||
GOOD = 4
|
||||
AVERAGE = 3
|
||||
POOR = 2
|
||||
VERY_POOR = 1
|
||||
excellent = 5
|
||||
good = 4
|
||||
average = 3
|
||||
poor = 2
|
||||
very_poor = 1
|
||||
|
||||
|
||||
class DeliveryRating(enum.Enum):
|
||||
"""Delivery performance rating scale"""
|
||||
EXCELLENT = 5
|
||||
GOOD = 4
|
||||
AVERAGE = 3
|
||||
POOR = 2
|
||||
VERY_POOR = 1
|
||||
excellent = 5
|
||||
good = 4
|
||||
average = 3
|
||||
poor = 2
|
||||
very_poor = 1
|
||||
|
||||
|
||||
class InvoiceStatus(enum.Enum):
|
||||
"""Invoice processing status"""
|
||||
PENDING = "pending"
|
||||
APPROVED = "approved"
|
||||
PAID = "paid"
|
||||
OVERDUE = "overdue"
|
||||
DISPUTED = "disputed"
|
||||
CANCELLED = "cancelled"
|
||||
pending = "pending"
|
||||
approved = "approved"
|
||||
paid = "paid"
|
||||
overdue = "overdue"
|
||||
disputed = "disputed"
|
||||
cancelled = "cancelled"
|
||||
|
||||
|
||||
class Supplier(Base):
|
||||
@@ -113,7 +113,7 @@ class Supplier(Base):
|
||||
|
||||
# Supplier classification
|
||||
supplier_type = Column(SQLEnum(SupplierType), nullable=False, index=True)
|
||||
status = Column(SQLEnum(SupplierStatus), nullable=False, default=SupplierStatus.PENDING_APPROVAL, index=True)
|
||||
status = Column(SQLEnum(SupplierStatus), nullable=False, default=SupplierStatus.pending_approval, index=True)
|
||||
|
||||
# Contact information
|
||||
contact_person = Column(String(200), nullable=True)
|
||||
@@ -131,7 +131,7 @@ class Supplier(Base):
|
||||
country = Column(String(100), nullable=True)
|
||||
|
||||
# Business terms
|
||||
payment_terms = Column(SQLEnum(PaymentTerms), nullable=False, default=PaymentTerms.NET_30)
|
||||
payment_terms = Column(SQLEnum(PaymentTerms), nullable=False, default=PaymentTerms.net_30)
|
||||
credit_limit = Column(Numeric(12, 2), nullable=True)
|
||||
currency = Column(String(3), nullable=False, default="EUR") # ISO currency code
|
||||
|
||||
@@ -246,7 +246,7 @@ class PurchaseOrder(Base):
|
||||
reference_number = Column(String(100), nullable=True) # Internal reference
|
||||
|
||||
# Order status and workflow
|
||||
status = Column(SQLEnum(PurchaseOrderStatus), nullable=False, default=PurchaseOrderStatus.DRAFT, index=True)
|
||||
status = Column(SQLEnum(PurchaseOrderStatus), nullable=False, default=PurchaseOrderStatus.draft, index=True)
|
||||
priority = Column(String(20), nullable=False, default="normal") # urgent, high, normal, low
|
||||
|
||||
# Order details
|
||||
@@ -363,7 +363,7 @@ class Delivery(Base):
|
||||
supplier_delivery_note = Column(String(100), nullable=True) # Supplier's delivery reference
|
||||
|
||||
# Delivery status and tracking
|
||||
status = Column(SQLEnum(DeliveryStatus), nullable=False, default=DeliveryStatus.SCHEDULED, index=True)
|
||||
status = Column(SQLEnum(DeliveryStatus), nullable=False, default=DeliveryStatus.scheduled, index=True)
|
||||
|
||||
# Scheduling and timing
|
||||
scheduled_date = Column(DateTime(timezone=True), nullable=True)
|
||||
@@ -517,7 +517,7 @@ class SupplierInvoice(Base):
|
||||
supplier_invoice_number = Column(String(100), nullable=False)
|
||||
|
||||
# Invoice status and dates
|
||||
status = Column(SQLEnum(InvoiceStatus), nullable=False, default=InvoiceStatus.PENDING, index=True)
|
||||
status = Column(SQLEnum(InvoiceStatus), nullable=False, default=InvoiceStatus.pending, index=True)
|
||||
invoice_date = Column(DateTime(timezone=True), nullable=False)
|
||||
due_date = Column(DateTime(timezone=True), nullable=False)
|
||||
received_date = Column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -4,8 +4,8 @@ Base repository class for common database operations
|
||||
"""
|
||||
|
||||
from typing import TypeVar, Generic, List, Optional, Dict, Any
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import desc, asc
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import desc, asc, select, func
|
||||
from uuid import UUID
|
||||
|
||||
T = TypeVar('T')
|
||||
@@ -14,55 +14,59 @@ T = TypeVar('T')
|
||||
class BaseRepository(Generic[T]):
|
||||
"""Base repository with common CRUD operations"""
|
||||
|
||||
def __init__(self, model: type, db: Session):
|
||||
def __init__(self, model: type, db: AsyncSession):
|
||||
self.model = model
|
||||
self.db = db
|
||||
|
||||
def create(self, obj_data: Dict[str, Any]) -> T:
|
||||
async def create(self, obj_data: Dict[str, Any]) -> T:
|
||||
"""Create a new record"""
|
||||
db_obj = self.model(**obj_data)
|
||||
self.db.add(db_obj)
|
||||
self.db.commit()
|
||||
self.db.refresh(db_obj)
|
||||
await self.db.commit()
|
||||
await self.db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
def get_by_id(self, record_id: UUID) -> Optional[T]:
|
||||
async def get_by_id(self, record_id: UUID) -> Optional[T]:
|
||||
"""Get record by ID"""
|
||||
return self.db.query(self.model).filter(self.model.id == record_id).first()
|
||||
stmt = select(self.model).filter(self.model.id == record_id)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
def get_by_tenant_id(self, tenant_id: UUID, limit: int = 100, offset: int = 0) -> List[T]:
|
||||
async def get_by_tenant_id(self, tenant_id: UUID, limit: int = 100, offset: int = 0) -> List[T]:
|
||||
"""Get records by tenant ID with pagination"""
|
||||
return (
|
||||
self.db.query(self.model)
|
||||
.filter(self.model.tenant_id == tenant_id)
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
.all()
|
||||
)
|
||||
stmt = select(self.model).filter(
|
||||
self.model.tenant_id == tenant_id
|
||||
).limit(limit).offset(offset)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
def update(self, record_id: UUID, update_data: Dict[str, Any]) -> Optional[T]:
|
||||
async def update(self, record_id: UUID, update_data: Dict[str, Any]) -> Optional[T]:
|
||||
"""Update record by ID"""
|
||||
db_obj = self.get_by_id(record_id)
|
||||
db_obj = await self.get_by_id(record_id)
|
||||
if db_obj:
|
||||
for key, value in update_data.items():
|
||||
if hasattr(db_obj, key):
|
||||
setattr(db_obj, key, value)
|
||||
self.db.commit()
|
||||
self.db.refresh(db_obj)
|
||||
await self.db.commit()
|
||||
await self.db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
def delete(self, record_id: UUID) -> bool:
|
||||
async def delete(self, record_id: UUID) -> bool:
|
||||
"""Delete record by ID"""
|
||||
db_obj = self.get_by_id(record_id)
|
||||
db_obj = await self.get_by_id(record_id)
|
||||
if db_obj:
|
||||
self.db.delete(db_obj)
|
||||
self.db.commit()
|
||||
await self.db.delete(db_obj)
|
||||
await self.db.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
def count_by_tenant(self, tenant_id: UUID) -> int:
|
||||
async def count_by_tenant(self, tenant_id: UUID) -> int:
|
||||
"""Count records by tenant"""
|
||||
return self.db.query(self.model).filter(self.model.tenant_id == tenant_id).count()
|
||||
stmt = select(func.count()).select_from(self.model).filter(
|
||||
self.model.tenant_id == tenant_id
|
||||
)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalar() or 0
|
||||
|
||||
def list_with_filters(
|
||||
self,
|
||||
|
||||
@@ -4,8 +4,8 @@ Supplier repository for database operations
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Dict, Any
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import and_, or_, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import and_, or_, func, select
|
||||
from uuid import UUID
|
||||
from datetime import datetime
|
||||
|
||||
@@ -16,36 +16,32 @@ from app.repositories.base import BaseRepository
|
||||
class SupplierRepository(BaseRepository[Supplier]):
|
||||
"""Repository for supplier management operations"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
def __init__(self, db: AsyncSession):
|
||||
super().__init__(Supplier, db)
|
||||
|
||||
def get_by_name(self, tenant_id: UUID, name: str) -> Optional[Supplier]:
|
||||
async def get_by_name(self, tenant_id: UUID, name: str) -> Optional[Supplier]:
|
||||
"""Get supplier by name within tenant"""
|
||||
return (
|
||||
self.db.query(self.model)
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.name == name
|
||||
)
|
||||
stmt = select(self.model).filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.name == name
|
||||
)
|
||||
.first()
|
||||
)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
def get_by_supplier_code(self, tenant_id: UUID, supplier_code: str) -> Optional[Supplier]:
|
||||
async def get_by_supplier_code(self, tenant_id: UUID, supplier_code: str) -> Optional[Supplier]:
|
||||
"""Get supplier by supplier code within tenant"""
|
||||
return (
|
||||
self.db.query(self.model)
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.supplier_code == supplier_code
|
||||
)
|
||||
stmt = select(self.model).filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.supplier_code == supplier_code
|
||||
)
|
||||
.first()
|
||||
)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
def search_suppliers(
|
||||
async def search_suppliers(
|
||||
self,
|
||||
tenant_id: UUID,
|
||||
search_term: Optional[str] = None,
|
||||
@@ -55,8 +51,8 @@ class SupplierRepository(BaseRepository[Supplier]):
|
||||
offset: int = 0
|
||||
) -> List[Supplier]:
|
||||
"""Search suppliers with filters"""
|
||||
query = self.db.query(self.model).filter(self.model.tenant_id == tenant_id)
|
||||
|
||||
stmt = select(self.model).filter(self.model.tenant_id == tenant_id)
|
||||
|
||||
# Search term filter (name, contact person, email)
|
||||
if search_term:
|
||||
search_filter = or_(
|
||||
@@ -64,31 +60,30 @@ class SupplierRepository(BaseRepository[Supplier]):
|
||||
self.model.contact_person.ilike(f"%{search_term}%"),
|
||||
self.model.email.ilike(f"%{search_term}%")
|
||||
)
|
||||
query = query.filter(search_filter)
|
||||
|
||||
stmt = stmt.filter(search_filter)
|
||||
|
||||
# Type filter
|
||||
if supplier_type:
|
||||
query = query.filter(self.model.supplier_type == supplier_type)
|
||||
|
||||
stmt = stmt.filter(self.model.supplier_type == supplier_type)
|
||||
|
||||
# Status filter
|
||||
if status:
|
||||
query = query.filter(self.model.status == status)
|
||||
|
||||
return query.order_by(self.model.name).limit(limit).offset(offset).all()
|
||||
stmt = stmt.filter(self.model.status == status)
|
||||
|
||||
stmt = stmt.order_by(self.model.name).limit(limit).offset(offset)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
def get_active_suppliers(self, tenant_id: UUID) -> List[Supplier]:
|
||||
async def get_active_suppliers(self, tenant_id: UUID) -> List[Supplier]:
|
||||
"""Get all active suppliers for a tenant"""
|
||||
return (
|
||||
self.db.query(self.model)
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.ACTIVE
|
||||
)
|
||||
stmt = select(self.model).filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.active
|
||||
)
|
||||
.order_by(self.model.name)
|
||||
.all()
|
||||
)
|
||||
).order_by(self.model.name)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
def get_suppliers_by_type(
|
||||
self,
|
||||
@@ -102,7 +97,7 @@ class SupplierRepository(BaseRepository[Supplier]):
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.supplier_type == supplier_type,
|
||||
self.model.status == SupplierStatus.ACTIVE
|
||||
self.model.status == SupplierStatus.active
|
||||
)
|
||||
)
|
||||
.order_by(self.model.quality_rating.desc(), self.model.name)
|
||||
@@ -120,7 +115,7 @@ class SupplierRepository(BaseRepository[Supplier]):
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.ACTIVE
|
||||
self.model.status == SupplierStatus.active
|
||||
)
|
||||
)
|
||||
.order_by(
|
||||
@@ -178,7 +173,7 @@ class SupplierRepository(BaseRepository[Supplier]):
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.ACTIVE,
|
||||
self.model.status == SupplierStatus.active,
|
||||
or_(
|
||||
self.model.quality_rating < 3.0, # Poor rating
|
||||
self.model.delivery_rating < 3.0, # Poor delivery
|
||||
@@ -190,66 +185,33 @@ class SupplierRepository(BaseRepository[Supplier]):
|
||||
.all()
|
||||
)
|
||||
|
||||
def get_supplier_statistics(self, tenant_id: UUID) -> Dict[str, Any]:
|
||||
async def get_supplier_statistics(self, tenant_id: UUID) -> Dict[str, Any]:
|
||||
"""Get supplier statistics for dashboard"""
|
||||
total_suppliers = self.count_by_tenant(tenant_id)
|
||||
|
||||
active_suppliers = (
|
||||
self.db.query(self.model)
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.ACTIVE
|
||||
)
|
||||
)
|
||||
.count()
|
||||
)
|
||||
|
||||
pending_suppliers = (
|
||||
self.db.query(self.model)
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.PENDING_APPROVAL
|
||||
)
|
||||
)
|
||||
.count()
|
||||
)
|
||||
|
||||
avg_quality_rating = (
|
||||
self.db.query(func.avg(self.model.quality_rating))
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.ACTIVE,
|
||||
self.model.quality_rating > 0
|
||||
)
|
||||
)
|
||||
.scalar()
|
||||
) or 0.0
|
||||
|
||||
avg_delivery_rating = (
|
||||
self.db.query(func.avg(self.model.delivery_rating))
|
||||
.filter(
|
||||
and_(
|
||||
self.model.tenant_id == tenant_id,
|
||||
self.model.status == SupplierStatus.ACTIVE,
|
||||
self.model.delivery_rating > 0
|
||||
)
|
||||
)
|
||||
.scalar()
|
||||
) or 0.0
|
||||
|
||||
total_spend = (
|
||||
self.db.query(func.sum(self.model.total_amount))
|
||||
.filter(self.model.tenant_id == tenant_id)
|
||||
.scalar()
|
||||
) or 0.0
|
||||
|
||||
total_suppliers = await self.count_by_tenant(tenant_id)
|
||||
|
||||
# Get all suppliers for this tenant to avoid multiple queries and enum casting issues
|
||||
all_stmt = select(self.model).filter(self.model.tenant_id == tenant_id)
|
||||
all_result = await self.db.execute(all_stmt)
|
||||
all_suppliers = all_result.scalars().all()
|
||||
|
||||
# Calculate statistics in Python to avoid database enum casting issues
|
||||
active_suppliers = [s for s in all_suppliers if s.status == SupplierStatus.active]
|
||||
pending_suppliers = [s for s in all_suppliers if s.status == SupplierStatus.pending_approval]
|
||||
|
||||
# Calculate averages from active suppliers
|
||||
quality_ratings = [s.quality_rating for s in active_suppliers if s.quality_rating and s.quality_rating > 0]
|
||||
avg_quality_rating = sum(quality_ratings) / len(quality_ratings) if quality_ratings else 0.0
|
||||
|
||||
delivery_ratings = [s.delivery_rating for s in active_suppliers if s.delivery_rating and s.delivery_rating > 0]
|
||||
avg_delivery_rating = sum(delivery_ratings) / len(delivery_ratings) if delivery_ratings else 0.0
|
||||
|
||||
# Total spend for all suppliers
|
||||
total_spend = sum(float(s.total_amount or 0) for s in all_suppliers)
|
||||
|
||||
return {
|
||||
"total_suppliers": total_suppliers,
|
||||
"active_suppliers": active_suppliers,
|
||||
"pending_suppliers": pending_suppliers,
|
||||
"active_suppliers": len(active_suppliers),
|
||||
"pending_suppliers": len(pending_suppliers),
|
||||
"avg_quality_rating": round(float(avg_quality_rating), 2),
|
||||
"avg_delivery_rating": round(float(avg_delivery_rating), 2),
|
||||
"total_spend": float(total_spend)
|
||||
|
||||
@@ -42,7 +42,7 @@ class SupplierCreate(BaseModel):
|
||||
country: Optional[str] = Field(None, max_length=100)
|
||||
|
||||
# Business terms
|
||||
payment_terms: PaymentTerms = PaymentTerms.NET_30
|
||||
payment_terms: PaymentTerms = PaymentTerms.net_30
|
||||
credit_limit: Optional[Decimal] = Field(None, ge=0)
|
||||
currency: str = Field(default="EUR", max_length=3)
|
||||
standard_lead_time: int = Field(default=3, ge=0, le=365)
|
||||
|
||||
@@ -138,7 +138,6 @@ class DashboardService:
|
||||
|
||||
return SupplierPerformanceInsights(
|
||||
supplier_id=supplier_id,
|
||||
supplier_name=supplier['name'],
|
||||
current_overall_score=current_metrics.get('overall_score', 0),
|
||||
previous_score=previous_metrics.get('overall_score'),
|
||||
score_change_percentage=self._calculate_change_percentage(
|
||||
|
||||
@@ -7,7 +7,7 @@ import structlog
|
||||
from typing import List, Optional, Dict, Any
|
||||
from uuid import UUID
|
||||
from datetime import datetime
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.repositories.supplier_repository import SupplierRepository
|
||||
from app.models.suppliers import Supplier, SupplierStatus, SupplierType
|
||||
@@ -23,7 +23,7 @@ logger = structlog.get_logger()
|
||||
class SupplierService:
|
||||
"""Service for supplier management operations"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
def __init__(self, db: AsyncSession):
|
||||
self.db = db
|
||||
self.repository = SupplierRepository(db)
|
||||
|
||||
@@ -37,13 +37,13 @@ class SupplierService:
|
||||
logger.info("Creating supplier", tenant_id=str(tenant_id), name=supplier_data.name)
|
||||
|
||||
# Check for duplicate name
|
||||
existing = self.repository.get_by_name(tenant_id, supplier_data.name)
|
||||
existing = await self.repository.get_by_name(tenant_id, supplier_data.name)
|
||||
if existing:
|
||||
raise ValueError(f"Supplier with name '{supplier_data.name}' already exists")
|
||||
|
||||
|
||||
# Check for duplicate supplier code if provided
|
||||
if supplier_data.supplier_code:
|
||||
existing_code = self.repository.get_by_supplier_code(
|
||||
existing_code = await self.repository.get_by_supplier_code(
|
||||
tenant_id, supplier_data.supplier_code
|
||||
)
|
||||
if existing_code:
|
||||
@@ -61,7 +61,7 @@ class SupplierService:
|
||||
create_data.update({
|
||||
'tenant_id': tenant_id,
|
||||
'supplier_code': supplier_code,
|
||||
'status': SupplierStatus.PENDING_APPROVAL,
|
||||
'status': SupplierStatus.pending_approval,
|
||||
'created_by': created_by,
|
||||
'updated_by': created_by,
|
||||
'quality_rating': 0.0,
|
||||
@@ -70,7 +70,7 @@ class SupplierService:
|
||||
'total_amount': 0.0
|
||||
})
|
||||
|
||||
supplier = self.repository.create(create_data)
|
||||
supplier = await self.repository.create(create_data)
|
||||
|
||||
logger.info(
|
||||
"Supplier created successfully",
|
||||
@@ -83,7 +83,7 @@ class SupplierService:
|
||||
|
||||
async def get_supplier(self, supplier_id: UUID) -> Optional[Supplier]:
|
||||
"""Get supplier by ID"""
|
||||
return self.repository.get_by_id(supplier_id)
|
||||
return await self.repository.get_by_id(supplier_id)
|
||||
|
||||
async def update_supplier(
|
||||
self,
|
||||
@@ -138,7 +138,7 @@ class SupplierService:
|
||||
|
||||
# Soft delete by changing status
|
||||
self.repository.update(supplier_id, {
|
||||
'status': SupplierStatus.INACTIVE,
|
||||
'status': SupplierStatus.inactive,
|
||||
'updated_at': datetime.utcnow()
|
||||
})
|
||||
|
||||
@@ -151,7 +151,7 @@ class SupplierService:
|
||||
search_params: SupplierSearchParams
|
||||
) -> List[Supplier]:
|
||||
"""Search suppliers with filters"""
|
||||
return self.repository.search_suppliers(
|
||||
return await self.repository.search_suppliers(
|
||||
tenant_id=tenant_id,
|
||||
search_term=search_params.search_term,
|
||||
supplier_type=search_params.supplier_type,
|
||||
@@ -239,7 +239,7 @@ class SupplierService:
|
||||
|
||||
async def get_supplier_statistics(self, tenant_id: UUID) -> Dict[str, Any]:
|
||||
"""Get supplier statistics for dashboard"""
|
||||
return self.repository.get_supplier_statistics(tenant_id)
|
||||
return await self.repository.get_supplier_statistics(tenant_id)
|
||||
|
||||
async def get_suppliers_needing_review(
|
||||
self,
|
||||
|
||||
Reference in New Issue
Block a user