feat: Add accounting period selector for all views
- Add PeriodSelectorMini component for global period selection - Add accountingPeriod store for shared period state - Add calendar service/router/model for available periods API - Update Dashboard, Invoices, Trial Balance, Bank/Cash Register views to respect selected period - Fix Trial Balance navigation sync bug (period now syncs on mount) - Update backend services to accept luna/an parameters 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
3
reports-app/backend/app/cache/config.py
vendored
3
reports-app/backend/app/cache/config.py
vendored
@@ -26,6 +26,7 @@ class CacheConfig:
|
|||||||
ttl_invoices_summary: int
|
ttl_invoices_summary: int
|
||||||
ttl_treasury: int
|
ttl_treasury: int
|
||||||
ttl_trial_balance: int
|
ttl_trial_balance: int
|
||||||
|
ttl_calendar_periods: int
|
||||||
|
|
||||||
# Maintenance
|
# Maintenance
|
||||||
cleanup_interval: int
|
cleanup_interval: int
|
||||||
@@ -58,6 +59,7 @@ class CacheConfig:
|
|||||||
ttl_invoices_summary=int(os.getenv('CACHE_TTL_INVOICES_SUMMARY', '900')),
|
ttl_invoices_summary=int(os.getenv('CACHE_TTL_INVOICES_SUMMARY', '900')),
|
||||||
ttl_treasury=int(os.getenv('CACHE_TTL_TREASURY', '600')),
|
ttl_treasury=int(os.getenv('CACHE_TTL_TREASURY', '600')),
|
||||||
ttl_trial_balance=int(os.getenv('CACHE_TTL_TRIAL_BALANCE', '600')),
|
ttl_trial_balance=int(os.getenv('CACHE_TTL_TRIAL_BALANCE', '600')),
|
||||||
|
ttl_calendar_periods=int(os.getenv('CACHE_TTL_CALENDAR_PERIODS', '3600')),
|
||||||
|
|
||||||
# Maintenance
|
# Maintenance
|
||||||
cleanup_interval=int(os.getenv('CACHE_CLEANUP_INTERVAL', '3600')),
|
cleanup_interval=int(os.getenv('CACHE_CLEANUP_INTERVAL', '3600')),
|
||||||
@@ -82,5 +84,6 @@ class CacheConfig:
|
|||||||
'invoices_summary': self.ttl_invoices_summary,
|
'invoices_summary': self.ttl_invoices_summary,
|
||||||
'treasury': self.ttl_treasury,
|
'treasury': self.ttl_treasury,
|
||||||
'trial_balance': self.ttl_trial_balance,
|
'trial_balance': self.ttl_trial_balance,
|
||||||
|
'calendar_periods': self.ttl_calendar_periods,
|
||||||
}
|
}
|
||||||
return ttl_map.get(cache_type, self.default_ttl)
|
return ttl_map.get(cache_type, self.default_ttl)
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ from auth.middleware import AuthenticationMiddleware
|
|||||||
# from auth.routes import create_auth_router # Fixed inline
|
# from auth.routes import create_auth_router # Fixed inline
|
||||||
|
|
||||||
# Import routere locale
|
# Import routere locale
|
||||||
from app.routers import invoices, dashboard, treasury, companies, telegram, cache, trial_balance
|
from app.routers import invoices, dashboard, treasury, companies, telegram, cache, trial_balance, calendar
|
||||||
|
|
||||||
# Auth endpoints pentru test
|
# Auth endpoints pentru test
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException
|
||||||
@@ -318,6 +318,7 @@ app.include_router(treasury.router, prefix="/api/treasury", tags=["treasury"])
|
|||||||
app.include_router(telegram.router, prefix="/api/telegram", tags=["telegram"])
|
app.include_router(telegram.router, prefix="/api/telegram", tags=["telegram"])
|
||||||
app.include_router(cache.router, prefix="/api", tags=["cache"])
|
app.include_router(cache.router, prefix="/api", tags=["cache"])
|
||||||
app.include_router(trial_balance.router, prefix="/api/trial-balance", tags=["trial-balance"])
|
app.include_router(trial_balance.router, prefix="/api/trial-balance", tags=["trial-balance"])
|
||||||
|
app.include_router(calendar.router, prefix="/api/calendar", tags=["calendar"])
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
async def root():
|
async def root():
|
||||||
|
|||||||
19
reports-app/backend/app/models/calendar.py
Normal file
19
reports-app/backend/app/models/calendar.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
"""
|
||||||
|
Calendar period models for accounting period selector
|
||||||
|
"""
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarPeriod(BaseModel):
|
||||||
|
"""Model for an accounting period"""
|
||||||
|
an: int # Year
|
||||||
|
luna: int # Month (1-12)
|
||||||
|
display_name: str # Format: "Decembrie 2025"
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarPeriodsResponse(BaseModel):
|
||||||
|
"""Response model for calendar periods list"""
|
||||||
|
periods: List[CalendarPeriod]
|
||||||
|
current_period: Optional[CalendarPeriod] = None # Most recent period
|
||||||
|
total_count: int
|
||||||
@@ -44,8 +44,8 @@ class InvoiceFilter(BaseModel):
|
|||||||
"""Filtru pentru căutarea facturilor"""
|
"""Filtru pentru căutarea facturilor"""
|
||||||
company: str = Field(description="Codul firmei (schema Oracle)")
|
company: str = Field(description="Codul firmei (schema Oracle)")
|
||||||
partner_type: Literal["CLIENTI", "FURNIZORI"] = Field(description="Tipul partenerului")
|
partner_type: Literal["CLIENTI", "FURNIZORI"] = Field(description="Tipul partenerului")
|
||||||
date_from: Optional[date] = Field(description="Data de început")
|
luna: Optional[int] = Field(default=None, ge=1, le=12, description="Luna contabilă (1-12)")
|
||||||
date_to: Optional[date] = Field(description="Data de sfârșit")
|
an: Optional[int] = Field(default=None, ge=2000, le=2100, description="Anul contabil")
|
||||||
partner_name: Optional[str] = Field(description="Filtru după nume")
|
partner_name: Optional[str] = Field(description="Filtru după nume")
|
||||||
cont: Optional[str] = Field(description="Filtru după cont contabil")
|
cont: Optional[str] = Field(description="Filtru după cont contabil")
|
||||||
only_unpaid: bool = Field(default=True, description="Doar neachitate")
|
only_unpaid: bool = Field(default=True, description="Doar neachitate")
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ class RegisterFilter(BaseModel):
|
|||||||
"""Filtre pentru registrul de casă și bancă"""
|
"""Filtre pentru registrul de casă și bancă"""
|
||||||
company: str
|
company: str
|
||||||
register_type: Optional[str] = None # BANCA_LEI, BANCA_VALUTA, CASA_LEI, CASA_VALUTA sau None pentru toate
|
register_type: Optional[str] = None # BANCA_LEI, BANCA_VALUTA, CASA_LEI, CASA_VALUTA sau None pentru toate
|
||||||
|
luna: Optional[int] = None # Luna contabilă (1-12) pentru PACK_SESIUNE
|
||||||
|
an: Optional[int] = None # Anul contabil pentru PACK_SESIUNE
|
||||||
date_from: Optional[datetime] = None
|
date_from: Optional[datetime] = None
|
||||||
date_to: Optional[datetime] = None
|
date_to: Optional[datetime] = None
|
||||||
partner_name: Optional[str] = None
|
partner_name: Optional[str] = None
|
||||||
|
|||||||
33
reports-app/backend/app/routers/calendar.py
Normal file
33
reports-app/backend/app/routers/calendar.py
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
"""
|
||||||
|
API Router for calendar/accounting periods
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../../shared'))
|
||||||
|
|
||||||
|
from auth.dependencies import get_current_user
|
||||||
|
from auth.models import CurrentUser
|
||||||
|
from ..models.calendar import CalendarPeriodsResponse
|
||||||
|
from ..services.calendar_service import CalendarService
|
||||||
|
|
||||||
|
router = APIRouter(redirect_slashes=False)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/periods", response_model=CalendarPeriodsResponse)
|
||||||
|
async def get_calendar_periods(
|
||||||
|
company: int = Query(..., description="Company ID"),
|
||||||
|
current_user: CurrentUser = Depends(get_current_user)
|
||||||
|
) -> CalendarPeriodsResponse:
|
||||||
|
"""
|
||||||
|
Get available accounting periods for a company.
|
||||||
|
Returns periods ordered by year DESC, month DESC with Romanian month names.
|
||||||
|
"""
|
||||||
|
# Validate company access
|
||||||
|
if str(company) not in current_user.companies:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail=f"Nu aveți acces la firma {company}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return await CalendarService.get_available_periods(company)
|
||||||
@@ -18,6 +18,8 @@ router = APIRouter()
|
|||||||
async def get_dashboard_summary(
|
async def get_dashboard_summary(
|
||||||
request: Request,
|
request: Request,
|
||||||
company: str = Query(description="Codul firmei"),
|
company: str = Query(description="Codul firmei"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
current_user: CurrentUser = Depends(get_current_user)
|
current_user: CurrentUser = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
@@ -26,13 +28,14 @@ async def get_dashboard_summary(
|
|||||||
- Necesită autentificare JWT
|
- Necesită autentificare JWT
|
||||||
- Returnează statistici clienți/furnizori și trezorerie
|
- Returnează statistici clienți/furnizori și trezorerie
|
||||||
- Include metadata cache pentru Telegram Bot (X-Include-Cache-Metadata header)
|
- Include metadata cache pentru Telegram Bot (X-Include-Cache-Metadata header)
|
||||||
|
- Suportă filtrare pe luna/an contabil (dacă nu sunt specificate, folosește ultima perioadă)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Verifică dacă utilizatorul are acces la firma specificată
|
# Verifică dacă utilizatorul are acces la firma specificată
|
||||||
if company not in current_user.companies:
|
if company not in current_user.companies:
|
||||||
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
||||||
|
|
||||||
result = await DashboardService.get_complete_summary(company, current_user.username, request=request)
|
result = await DashboardService.get_complete_summary(company, current_user.username, luna=luna, an=an, request=request)
|
||||||
|
|
||||||
# Convert Pydantic model to dict for JSON serialization
|
# Convert Pydantic model to dict for JSON serialization
|
||||||
result_dict = result.dict() if hasattr(result, 'dict') else result
|
result_dict = result.dict() if hasattr(result, 'dict') else result
|
||||||
@@ -60,6 +63,8 @@ async def get_dashboard_trends(
|
|||||||
request: Request,
|
request: Request,
|
||||||
company: str = Query(description="Codul firmei"),
|
company: str = Query(description="Codul firmei"),
|
||||||
period: str = Query(default="30d", description="Perioada pentru trends: 7d, 30d, ytd, 12m"),
|
period: str = Query(default="30d", description="Perioada pentru trends: 7d, 30d, ytd, 12m"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
compare_previous: bool = Query(default=True, description="Compară cu perioada anterioară"),
|
compare_previous: bool = Query(default=True, description="Compară cu perioada anterioară"),
|
||||||
current_user: CurrentUser = Depends(get_current_user)
|
current_user: CurrentUser = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
@@ -67,6 +72,7 @@ async def get_dashboard_trends(
|
|||||||
Obține trenduri pentru indicatorii principali (clienți/furnizori)
|
Obține trenduri pentru indicatorii principali (clienți/furnizori)
|
||||||
|
|
||||||
- period: "7d" (7 zile), "30d" (30 zile), "ytd" (year to date), "12m" (12 luni)
|
- period: "7d" (7 zile), "30d" (30 zile), "ytd" (year to date), "12m" (12 luni)
|
||||||
|
- luna/an: perioada contabilă de referință (dacă nu sunt specificate, folosește ultima perioadă)
|
||||||
- compare_previous: dacă să compare cu perioada anterioară
|
- compare_previous: dacă să compare cu perioada anterioară
|
||||||
- Necesită autentificare JWT
|
- Necesită autentificare JWT
|
||||||
- Returnează date pentru grafice de trenduri
|
- Returnează date pentru grafice de trenduri
|
||||||
@@ -85,7 +91,7 @@ async def get_dashboard_trends(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Obține datele de trenduri
|
# Obține datele de trenduri
|
||||||
result = await DashboardService.get_trends(int(company), period, request=request)
|
result = await DashboardService.get_trends(int(company), period, luna=luna, an=an, request=request)
|
||||||
|
|
||||||
# Convert to dict if needed
|
# Convert to dict if needed
|
||||||
result_dict = result.dict() if hasattr(result, 'dict') else result
|
result_dict = result.dict() if hasattr(result, 'dict') else result
|
||||||
@@ -115,6 +121,8 @@ async def get_dashboard_trends(
|
|||||||
async def get_detailed_data(
|
async def get_detailed_data(
|
||||||
company: str = Query(description="Codul firmei"),
|
company: str = Query(description="Codul firmei"),
|
||||||
data_type: str = Query(description="Tipul de date: clients, suppliers, treasury"),
|
data_type: str = Query(description="Tipul de date: clients, suppliers, treasury"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
page: int = Query(default=1, ge=1),
|
page: int = Query(default=1, ge=1),
|
||||||
page_size: int = Query(default=25, ge=1, le=100),
|
page_size: int = Query(default=25, ge=1, le=100),
|
||||||
search: str = Query(default="", description="Termen de căutare"),
|
search: str = Query(default="", description="Termen de căutare"),
|
||||||
@@ -132,6 +140,8 @@ async def get_detailed_data(
|
|||||||
result = await DashboardService.get_detailed_data(
|
result = await DashboardService.get_detailed_data(
|
||||||
company=company,
|
company=company,
|
||||||
data_type=data_type,
|
data_type=data_type,
|
||||||
|
luna=luna,
|
||||||
|
an=an,
|
||||||
page=page,
|
page=page,
|
||||||
page_size=page_size,
|
page_size=page_size,
|
||||||
search=search
|
search=search
|
||||||
@@ -225,6 +235,8 @@ async def get_maturity_analysis(
|
|||||||
request: Request,
|
request: Request,
|
||||||
company: int = Query(..., description="ID-ul firmei"),
|
company: int = Query(..., description="ID-ul firmei"),
|
||||||
period: str = Query("7d", regex="^(7d|1m|3m|6m|12m|all)$", description="Orizont de planificare pentru analiza scadențelor"),
|
period: str = Query("7d", regex="^(7d|1m|3m|6m|12m|all)$", description="Orizont de planificare pentru analiza scadențelor"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
current_user: CurrentUser = Depends(get_current_user)
|
current_user: CurrentUser = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
@@ -232,6 +244,7 @@ async def get_maturity_analysis(
|
|||||||
|
|
||||||
- Necesită autentificare JWT
|
- Necesită autentificare JWT
|
||||||
- Logică: Include TOATE restanțele + scadențele viitoare din perioada selectată
|
- Logică: Include TOATE restanțele + scadențele viitoare din perioada selectată
|
||||||
|
- luna/an: perioada contabilă de referință (dacă nu sunt specificate, folosește ultima perioadă)
|
||||||
- Perioade disponibile:
|
- Perioade disponibile:
|
||||||
* 7d: Toate restanțele + scadențe următoarelor 7 zile
|
* 7d: Toate restanțele + scadențe următoarelor 7 zile
|
||||||
* 1m: Toate restanțele + scadențe următoarelor 30 zile
|
* 1m: Toate restanțele + scadențe următoarelor 30 zile
|
||||||
@@ -249,7 +262,7 @@ async def get_maturity_analysis(
|
|||||||
if str(company) not in current_user.companies:
|
if str(company) not in current_user.companies:
|
||||||
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
||||||
|
|
||||||
result = await DashboardService.get_maturity_analysis(company, period, request=request)
|
result = await DashboardService.get_maturity_analysis(company, period, luna=luna, an=an, request=request)
|
||||||
|
|
||||||
# Convert to dict if needed
|
# Convert to dict if needed
|
||||||
result_dict = result.dict() if hasattr(result, 'dict') else result
|
result_dict = result.dict() if hasattr(result, 'dict') else result
|
||||||
@@ -276,6 +289,8 @@ async def get_maturity_analysis(
|
|||||||
@router.get("/monthly-flows")
|
@router.get("/monthly-flows")
|
||||||
async def get_monthly_flows(
|
async def get_monthly_flows(
|
||||||
company: int = Query(..., description="ID-ul firmei"),
|
company: int = Query(..., description="ID-ul firmei"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
current_user: CurrentUser = Depends(get_current_user)
|
current_user: CurrentUser = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
@@ -283,13 +298,14 @@ async def get_monthly_flows(
|
|||||||
|
|
||||||
- Necesită autentificare JWT
|
- Necesită autentificare JWT
|
||||||
- Returnează date pentru analiza fluxurilor lunare
|
- Returnează date pentru analiza fluxurilor lunare
|
||||||
|
- luna/an: perioada contabilă de referință (dacă nu sunt specificate, folosește ultima perioadă)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Verifică dacă utilizatorul are acces la firma specificată
|
# Verifică dacă utilizatorul are acces la firma specificată
|
||||||
if str(company) not in current_user.companies:
|
if str(company) not in current_user.companies:
|
||||||
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
||||||
|
|
||||||
result = await DashboardService.get_monthly_flows(company)
|
result = await DashboardService.get_monthly_flows(company, luna=luna, an=an)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
@@ -302,6 +318,8 @@ async def get_monthly_flows(
|
|||||||
async def get_treasury_breakdown(
|
async def get_treasury_breakdown(
|
||||||
request: Request,
|
request: Request,
|
||||||
company: int = Query(..., description="ID-ul firmei"),
|
company: int = Query(..., description="ID-ul firmei"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
current_user: CurrentUser = Depends(get_current_user)
|
current_user: CurrentUser = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
@@ -309,6 +327,7 @@ async def get_treasury_breakdown(
|
|||||||
|
|
||||||
- Necesită autentificare JWT
|
- Necesită autentificare JWT
|
||||||
- Returnează distribuția soldurilor pe conturi și tipuri
|
- Returnează distribuția soldurilor pe conturi și tipuri
|
||||||
|
- luna/an: perioada contabilă de referință (dacă nu sunt specificate, folosește ultima perioadă)
|
||||||
- Include metadata cache pentru Telegram Bot (X-Include-Cache-Metadata header)
|
- Include metadata cache pentru Telegram Bot (X-Include-Cache-Metadata header)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
@@ -316,7 +335,7 @@ async def get_treasury_breakdown(
|
|||||||
if str(company) not in current_user.companies:
|
if str(company) not in current_user.companies:
|
||||||
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
||||||
|
|
||||||
result = await DashboardService.get_treasury_breakdown(company, request=request)
|
result = await DashboardService.get_treasury_breakdown(company, luna=luna, an=an, request=request)
|
||||||
|
|
||||||
# Convert to dict if needed
|
# Convert to dict if needed
|
||||||
result_dict = result.dict() if hasattr(result, 'dict') else result
|
result_dict = result.dict() if hasattr(result, 'dict') else result
|
||||||
@@ -344,6 +363,8 @@ async def get_treasury_breakdown(
|
|||||||
async def get_net_balance_breakdown(
|
async def get_net_balance_breakdown(
|
||||||
request: Request,
|
request: Request,
|
||||||
company: int = Query(..., description="ID-ul firmei"),
|
company: int = Query(..., description="ID-ul firmei"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
current_user: CurrentUser = Depends(get_current_user)
|
current_user: CurrentUser = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
@@ -351,6 +372,7 @@ async def get_net_balance_breakdown(
|
|||||||
|
|
||||||
- Necesită autentificare JWT
|
- Necesită autentificare JWT
|
||||||
- Returnează analiza detaliată a balanței nete
|
- Returnează analiza detaliată a balanței nete
|
||||||
|
- luna/an: perioada contabilă de referință (dacă nu sunt specificate, folosește ultima perioadă)
|
||||||
- Include metadata cache pentru Telegram Bot (X-Include-Cache-Metadata header)
|
- Include metadata cache pentru Telegram Bot (X-Include-Cache-Metadata header)
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
@@ -358,7 +380,7 @@ async def get_net_balance_breakdown(
|
|||||||
if str(company) not in current_user.companies:
|
if str(company) not in current_user.companies:
|
||||||
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
||||||
|
|
||||||
result = await DashboardService.get_net_balance_breakdown(company, request=request)
|
result = await DashboardService.get_net_balance_breakdown(company, luna=luna, an=an, request=request)
|
||||||
|
|
||||||
# Convert to dict if needed
|
# Convert to dict if needed
|
||||||
result_dict = result.dict() if hasattr(result, 'dict') else result
|
result_dict = result.dict() if hasattr(result, 'dict') else result
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ router = APIRouter()
|
|||||||
async def get_invoices(
|
async def get_invoices(
|
||||||
company: str = Query(description="Codul firmei"),
|
company: str = Query(description="Codul firmei"),
|
||||||
partner_type: str = Query("CLIENTI", description="CLIENTI sau FURNIZORI"),
|
partner_type: str = Query("CLIENTI", description="CLIENTI sau FURNIZORI"),
|
||||||
date_from: Optional[str] = Query(None, description="Data început (YYYY-MM-DD)"),
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
date_to: Optional[str] = Query(None, description="Data sfârșit (YYYY-MM-DD)"),
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
partner_name: Optional[str] = Query(None, description="Filtru nume partener"),
|
partner_name: Optional[str] = Query(None, description="Filtru nume partener"),
|
||||||
cont: Optional[str] = Query(None, description="Filtru după cont contabil"),
|
cont: Optional[str] = Query(None, description="Filtru după cont contabil"),
|
||||||
only_unpaid: bool = Query(True, description="Doar facturile neachitate"),
|
only_unpaid: bool = Query(True, description="Doar facturile neachitate"),
|
||||||
@@ -35,34 +35,18 @@ async def get_invoices(
|
|||||||
|
|
||||||
- Necesită autentificare JWT
|
- Necesită autentificare JWT
|
||||||
- Utilizatorul trebuie să aibă acces la firma specificată
|
- Utilizatorul trebuie să aibă acces la firma specificată
|
||||||
- Suportă filtrare și paginare
|
- Suportă filtrare după luna/an contabil și paginare
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Verifică dacă utilizatorul are acces la firma specificată
|
# Verifică dacă utilizatorul are acces la firma specificată
|
||||||
if company not in current_user.companies:
|
if company not in current_user.companies:
|
||||||
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
raise HTTPException(status_code=403, detail=f"Nu aveți acces la firma {company}")
|
||||||
|
|
||||||
# Convertește string-urile de date în obiecte date
|
|
||||||
date_from_obj = None
|
|
||||||
date_to_obj = None
|
|
||||||
|
|
||||||
if date_from:
|
|
||||||
try:
|
|
||||||
date_from_obj = date.fromisoformat(date_from)
|
|
||||||
except ValueError:
|
|
||||||
raise HTTPException(status_code=400, detail="Formatul datei de început este invalid. Folosiți YYYY-MM-DD")
|
|
||||||
|
|
||||||
if date_to:
|
|
||||||
try:
|
|
||||||
date_to_obj = date.fromisoformat(date_to)
|
|
||||||
except ValueError:
|
|
||||||
raise HTTPException(status_code=400, detail="Formatul datei de sfârșit este invalid. Folosiți YYYY-MM-DD")
|
|
||||||
|
|
||||||
filter_params = InvoiceFilter(
|
filter_params = InvoiceFilter(
|
||||||
company=company,
|
company=company,
|
||||||
partner_type=partner_type,
|
partner_type=partner_type,
|
||||||
date_from=date_from_obj,
|
luna=luna,
|
||||||
date_to=date_to_obj,
|
an=an,
|
||||||
partner_name=partner_name,
|
partner_name=partner_name,
|
||||||
cont=cont,
|
cont=cont,
|
||||||
only_unpaid=only_unpaid,
|
only_unpaid=only_unpaid,
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ router = APIRouter()
|
|||||||
async def get_bank_cash_register(
|
async def get_bank_cash_register(
|
||||||
company: str = Query(description="Codul firmei"),
|
company: str = Query(description="Codul firmei"),
|
||||||
register_type: Optional[str] = Query(None, description="Tipul registrului: BANCA_LEI, BANCA_VALUTA, CASA_LEI, CASA_VALUTA sau None pentru toate"),
|
register_type: Optional[str] = Query(None, description="Tipul registrului: BANCA_LEI, BANCA_VALUTA, CASA_LEI, CASA_VALUTA sau None pentru toate"),
|
||||||
|
luna: Optional[int] = Query(None, ge=1, le=12, description="Luna contabilă (1-12)"),
|
||||||
|
an: Optional[int] = Query(None, ge=2000, le=2100, description="Anul contabil"),
|
||||||
date_from: Optional[str] = Query(None, description="Data început (YYYY-MM-DD)"),
|
date_from: Optional[str] = Query(None, description="Data început (YYYY-MM-DD)"),
|
||||||
date_to: Optional[str] = Query(None, description="Data sfârșit (YYYY-MM-DD)"),
|
date_to: Optional[str] = Query(None, description="Data sfârșit (YYYY-MM-DD)"),
|
||||||
partner_name: Optional[str] = Query(None, description="Filtru nume partener"),
|
partner_name: Optional[str] = Query(None, description="Filtru nume partener"),
|
||||||
@@ -63,6 +65,8 @@ async def get_bank_cash_register(
|
|||||||
filter_params = RegisterFilter(
|
filter_params = RegisterFilter(
|
||||||
company=company,
|
company=company,
|
||||||
register_type=register_type,
|
register_type=register_type,
|
||||||
|
luna=luna,
|
||||||
|
an=an,
|
||||||
date_from=date_from_obj,
|
date_from=date_from_obj,
|
||||||
date_to=date_to_obj,
|
date_to=date_to_obj,
|
||||||
partner_name=partner_name,
|
partner_name=partner_name,
|
||||||
|
|||||||
78
reports-app/backend/app/services/calendar_service.py
Normal file
78
reports-app/backend/app/services/calendar_service.py
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
"""
|
||||||
|
Calendar service for fetching available accounting periods
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../../shared'))
|
||||||
|
|
||||||
|
from database.oracle_pool import oracle_pool
|
||||||
|
from ..models.calendar import CalendarPeriod, CalendarPeriodsResponse
|
||||||
|
from ..cache.decorators import cached
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarService:
|
||||||
|
"""Service for calendar/accounting period operations"""
|
||||||
|
|
||||||
|
# Romanian month names for display
|
||||||
|
MONTH_NAMES_RO = [
|
||||||
|
"Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie",
|
||||||
|
"Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
|
||||||
|
]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
@cached(cache_type='schema', key_params=['company_id'])
|
||||||
|
async def _get_schema(company_id: int) -> str:
|
||||||
|
"""Get schema for company (CACHED 24h)"""
|
||||||
|
async with oracle_pool.get_connection() as connection:
|
||||||
|
with connection.cursor() as cursor:
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT schema FROM CONTAFIN_ORACLE.v_nom_firme
|
||||||
|
WHERE id_firma = :company_id
|
||||||
|
""", {'company_id': company_id})
|
||||||
|
result = cursor.fetchone()
|
||||||
|
return result[0] if result else None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
@cached(cache_type='calendar_periods', key_params=['company_id'])
|
||||||
|
async def get_available_periods(company_id: int) -> CalendarPeriodsResponse:
|
||||||
|
"""
|
||||||
|
Get all available accounting periods for a company (CACHED 1h)
|
||||||
|
|
||||||
|
Returns periods ordered by year DESC, month DESC with Romanian month names.
|
||||||
|
"""
|
||||||
|
schema = await CalendarService._get_schema(company_id)
|
||||||
|
if not schema:
|
||||||
|
logger.warning(f"Schema not found for company {company_id}")
|
||||||
|
return CalendarPeriodsResponse(periods=[], current_period=None, total_count=0)
|
||||||
|
|
||||||
|
async with oracle_pool.get_connection() as connection:
|
||||||
|
with connection.cursor() as cursor:
|
||||||
|
cursor.execute(f"""
|
||||||
|
SELECT anul, luna
|
||||||
|
FROM {schema}.calendar
|
||||||
|
ORDER BY anul DESC, luna DESC
|
||||||
|
""")
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
|
||||||
|
periods = []
|
||||||
|
for row in rows:
|
||||||
|
an, luna = row[0], row[1]
|
||||||
|
month_name = CalendarService.MONTH_NAMES_RO[luna - 1]
|
||||||
|
periods.append(CalendarPeriod(
|
||||||
|
an=an,
|
||||||
|
luna=luna,
|
||||||
|
display_name=f"{month_name} {an}"
|
||||||
|
))
|
||||||
|
|
||||||
|
current_period = periods[0] if periods else None
|
||||||
|
|
||||||
|
logger.info(f"Loaded {len(periods)} accounting periods for company {company_id}")
|
||||||
|
|
||||||
|
return CalendarPeriodsResponse(
|
||||||
|
periods=periods,
|
||||||
|
current_period=current_period,
|
||||||
|
total_count=len(periods)
|
||||||
|
)
|
||||||
@@ -16,6 +16,34 @@ logger = logging.getLogger(__name__)
|
|||||||
class DashboardService:
|
class DashboardService:
|
||||||
"""Service pentru dashboard - date agregate"""
|
"""Service pentru dashboard - date agregate"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _build_period_cte(schema: str, luna: Optional[int] = None, an: Optional[int] = None) -> tuple[str, dict]:
|
||||||
|
"""
|
||||||
|
Construiește CTE pentru luna curentă.
|
||||||
|
|
||||||
|
Dacă luna și an sunt specificate, le folosește.
|
||||||
|
Altfel, folosește MAX(anul*12+luna) din calendar.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple: (cte_sql, params_dict)
|
||||||
|
"""
|
||||||
|
if luna is not None and an is not None:
|
||||||
|
# Folosește parametrii specificați
|
||||||
|
cte_sql = f"""
|
||||||
|
WITH luna_curenta AS (
|
||||||
|
SELECT :param_an as anul, :param_luna as luna FROM DUAL
|
||||||
|
)"""
|
||||||
|
params = {'param_an': an, 'param_luna': luna}
|
||||||
|
else:
|
||||||
|
# Folosește MAX din calendar
|
||||||
|
cte_sql = f"""
|
||||||
|
WITH luna_curenta AS (
|
||||||
|
SELECT anul, luna FROM {schema}.calendar
|
||||||
|
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
||||||
|
)"""
|
||||||
|
params = {}
|
||||||
|
return cte_sql, params
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@cached(cache_type='schema', key_params=['company_id'])
|
@cached(cache_type='schema', key_params=['company_id'])
|
||||||
async def _get_schema(company_id: int) -> str:
|
async def _get_schema(company_id: int) -> str:
|
||||||
@@ -41,24 +69,31 @@ class DashboardService:
|
|||||||
return schema_result[0]
|
return schema_result[0]
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@cached(cache_type='dashboard_summary', key_params=['company', 'username'])
|
@cached(cache_type='dashboard_summary', key_params=['company', 'username', 'luna', 'an'])
|
||||||
async def get_complete_summary(company: str, username: str, request: Optional[Request] = None) -> DashboardSummary:
|
async def get_complete_summary(company: str, username: str, luna: Optional[int] = None, an: Optional[int] = None, request: Optional[Request] = None) -> DashboardSummary:
|
||||||
"""
|
"""
|
||||||
Obține toate datele pentru dashboard într-un singur apel (CACHED 30 min)
|
Obține toate datele pentru dashboard într-un singur apel (CACHED 30 min)
|
||||||
Execută 2 query-uri separate: facturi și trezorerie
|
Execută 2 query-uri separate: facturi și trezorerie
|
||||||
|
|
||||||
|
Args:
|
||||||
|
company: ID-ul firmei
|
||||||
|
username: Numele utilizatorului
|
||||||
|
luna: Luna contabilă (1-12), opțional
|
||||||
|
an: Anul contabil, opțional
|
||||||
|
request: Request object pentru cache metadata
|
||||||
"""
|
"""
|
||||||
company_id = int(company)
|
company_id = int(company)
|
||||||
schema = await DashboardService._get_schema(company_id)
|
schema = await DashboardService._get_schema(company_id)
|
||||||
|
|
||||||
|
# Construiește CTE pentru perioada curentă
|
||||||
|
period_cte, period_params = DashboardService._build_period_cte(schema, luna, an)
|
||||||
|
|
||||||
async with oracle_pool.get_connection() as connection:
|
async with oracle_pool.get_connection() as connection:
|
||||||
with connection.cursor() as cursor:
|
with connection.cursor() as cursor:
|
||||||
|
|
||||||
# Query 1: Statistici facturi cu breakdown pe perioade - FIXED ORA-00937
|
# Query 1: Statistici facturi cu breakdown pe perioade - FIXED ORA-00937
|
||||||
facturi_query = f"""
|
facturi_query = f"""
|
||||||
WITH luna_curenta AS (
|
{period_cte},
|
||||||
SELECT anul, luna FROM {schema}.calendar
|
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
|
||||||
),
|
|
||||||
perioada_stats AS (
|
perioada_stats AS (
|
||||||
SELECT
|
SELECT
|
||||||
an, luna,
|
an, luna,
|
||||||
@@ -347,15 +382,12 @@ class DashboardService:
|
|||||||
FROM facturi_stats fs
|
FROM facturi_stats fs
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(facturi_query)
|
cursor.execute(facturi_query, period_params)
|
||||||
facturi_row = cursor.fetchone()
|
facturi_row = cursor.fetchone()
|
||||||
|
|
||||||
# Query 2: Trezorerie
|
# Query 2: Trezorerie (folosește același period_cte)
|
||||||
treasury_query = f"""
|
treasury_query = f"""
|
||||||
WITH luna_curenta AS (
|
{period_cte}
|
||||||
SELECT anul, luna FROM {schema}.calendar
|
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
|
||||||
)
|
|
||||||
SELECT
|
SELECT
|
||||||
cont,
|
cont,
|
||||||
nume as nume_banca,
|
nume as nume_banca,
|
||||||
@@ -383,15 +415,12 @@ class DashboardService:
|
|||||||
ORDER BY cont, nume
|
ORDER BY cont, nume
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(treasury_query)
|
cursor.execute(treasury_query, period_params)
|
||||||
treasury_rows = cursor.fetchall()
|
treasury_rows = cursor.fetchall()
|
||||||
|
|
||||||
# Query 3: Solduri TVA din tabelul vbal
|
# Query 3: Solduri TVA din tabelul vbal (folosește același period_cte)
|
||||||
tva_query = f"""
|
tva_query = f"""
|
||||||
WITH luna_curenta AS (
|
{period_cte}
|
||||||
SELECT anul, luna FROM {schema}.calendar
|
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
|
||||||
)
|
|
||||||
SELECT
|
SELECT
|
||||||
cont,
|
cont,
|
||||||
precdeb,
|
precdeb,
|
||||||
@@ -405,7 +434,7 @@ class DashboardService:
|
|||||||
ORDER BY cont
|
ORDER BY cont
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(tva_query)
|
cursor.execute(tva_query, period_params)
|
||||||
tva_rows = cursor.fetchall()
|
tva_rows = cursor.fetchall()
|
||||||
|
|
||||||
# Procesare solduri TVA
|
# Procesare solduri TVA
|
||||||
@@ -537,34 +566,47 @@ class DashboardService:
|
|||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@cached(cache_type='dashboard_trends', key_params=['company_id', 'period'])
|
@cached(cache_type='dashboard_trends', key_params=['company_id', 'period', 'luna', 'an'])
|
||||||
async def get_trends(company_id: int, period: str = "12m", request: Optional[Request] = None) -> Dict[str, Any]:
|
async def get_trends(company_id: int, period: str = "12m", luna: Optional[int] = None, an: Optional[int] = None, request: Optional[Request] = None) -> Dict[str, Any]:
|
||||||
"""Get comprehensive trend analysis data for all dashboard indicators (CACHED 30 min)"""
|
"""Get comprehensive trend analysis data for all dashboard indicators (CACHED 30 min)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
company_id: ID-ul firmei
|
||||||
|
period: Perioada pentru trends (7d, 30d, ytd, 12m)
|
||||||
|
luna: Luna contabilă (1-12), opțional - dacă nu e specificată, folosește MAX
|
||||||
|
an: Anul contabil, opțional - dacă nu e specificat, folosește MAX
|
||||||
|
request: Request object pentru cache metadata
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
schema = await DashboardService._get_schema(company_id)
|
schema = await DashboardService._get_schema(company_id)
|
||||||
|
|
||||||
async with oracle_pool.get_connection() as connection:
|
async with oracle_pool.get_connection() as connection:
|
||||||
with connection.cursor() as cursor:
|
with connection.cursor() as cursor:
|
||||||
|
|
||||||
# Get current period
|
# Determine current period from params or database
|
||||||
current_period_query = f"""
|
if luna is not None and an is not None:
|
||||||
WITH luna_curenta AS (
|
current_year = an
|
||||||
SELECT anul, luna FROM {schema}.calendar
|
current_month = luna
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
|
||||||
)
|
|
||||||
SELECT anul, luna FROM luna_curenta
|
|
||||||
"""
|
|
||||||
|
|
||||||
cursor.execute(current_period_query)
|
|
||||||
current_period = cursor.fetchone()
|
|
||||||
|
|
||||||
if not current_period:
|
|
||||||
# Fallback to current system date
|
|
||||||
current_year = 2024
|
|
||||||
current_month = 12
|
|
||||||
else:
|
else:
|
||||||
current_year = current_period[0]
|
# Get current period from database
|
||||||
current_month = current_period[1]
|
current_period_query = f"""
|
||||||
|
WITH luna_curenta AS (
|
||||||
|
SELECT anul, luna FROM {schema}.calendar
|
||||||
|
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
||||||
|
)
|
||||||
|
SELECT anul, luna FROM luna_curenta
|
||||||
|
"""
|
||||||
|
|
||||||
|
cursor.execute(current_period_query)
|
||||||
|
current_period = cursor.fetchone()
|
||||||
|
|
||||||
|
if not current_period:
|
||||||
|
# Fallback to current system date
|
||||||
|
current_year = 2024
|
||||||
|
current_month = 12
|
||||||
|
else:
|
||||||
|
current_year = current_period[0]
|
||||||
|
current_month = current_period[1]
|
||||||
|
|
||||||
# Determine period parameters
|
# Determine period parameters
|
||||||
if period == 'ytd':
|
if period == 'ytd':
|
||||||
@@ -921,12 +963,21 @@ class DashboardService:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_detailed_data(company: str, data_type: str, page: int = 1, page_size: int = 25, search: str = ""):
|
async def get_detailed_data(company: str, data_type: str, luna: Optional[int] = None, an: Optional[int] = None, page: int = 1, page_size: int = 25, search: str = ""):
|
||||||
"""
|
"""
|
||||||
Obține date detaliate pentru tabelele din dashboard
|
Obține date detaliate pentru tabelele din dashboard
|
||||||
Fixed to use existing vireg_parteneri view instead of missing tables
|
Fixed to use existing vireg_parteneri view instead of missing tables
|
||||||
|
|
||||||
|
Args:
|
||||||
|
company: ID-ul firmei
|
||||||
|
data_type: Tipul datelor (clients, suppliers, treasury)
|
||||||
|
luna: Luna contabilă (1-12), opțional
|
||||||
|
an: Anul contabil, opțional
|
||||||
|
page: Pagina curentă
|
||||||
|
page_size: Mărimea paginii
|
||||||
|
search: Termen de căutare
|
||||||
"""
|
"""
|
||||||
logger.info(f"get_detailed_data called: company={company}, data_type={data_type}, page={page}")
|
logger.info(f"get_detailed_data called: company={company}, data_type={data_type}, luna={luna}, an={an}, page={page}")
|
||||||
async with oracle_pool.get_connection() as connection:
|
async with oracle_pool.get_connection() as connection:
|
||||||
with connection.cursor() as cursor:
|
with connection.cursor() as cursor:
|
||||||
try:
|
try:
|
||||||
@@ -946,6 +997,9 @@ class DashboardService:
|
|||||||
schema = schema_result[0]
|
schema = schema_result[0]
|
||||||
logger.info(f"Found schema: {schema}")
|
logger.info(f"Found schema: {schema}")
|
||||||
|
|
||||||
|
# Construiește CTE pentru perioada curentă
|
||||||
|
period_cte, period_params = DashboardService._build_period_cte(schema, luna, an)
|
||||||
|
|
||||||
# Calculate offset for pagination
|
# Calculate offset for pagination
|
||||||
offset = (page - 1) * page_size
|
offset = (page - 1) * page_size
|
||||||
logger.info(f"Pagination params: page={page}, page_size={page_size}, offset={offset}")
|
logger.info(f"Pagination params: page={page}, page_size={page_size}, offset={offset}")
|
||||||
@@ -965,10 +1019,7 @@ class DashboardService:
|
|||||||
if data_type == "clients":
|
if data_type == "clients":
|
||||||
# Query cu paginare pe CLIENȚI (nu pe facturi individuale)
|
# Query cu paginare pe CLIENȚI (nu pe facturi individuale)
|
||||||
base_query = f"""
|
base_query = f"""
|
||||||
WITH luna_curenta AS (
|
{period_cte},
|
||||||
SELECT anul, luna FROM {schema}.calendar
|
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
|
||||||
),
|
|
||||||
clienti_cu_sold AS (
|
clienti_cu_sold AS (
|
||||||
-- Pasul 1: Identifică TOȚI clienții cu sold != 0
|
-- Pasul 1: Identifică TOȚI clienții cu sold != 0
|
||||||
SELECT DISTINCT vp.nume as client_name
|
SELECT DISTINCT vp.nume as client_name
|
||||||
@@ -1012,10 +1063,7 @@ class DashboardService:
|
|||||||
elif data_type == "suppliers":
|
elif data_type == "suppliers":
|
||||||
# Query cu paginare pe FURNIZORI (nu pe facturi individuale)
|
# Query cu paginare pe FURNIZORI (nu pe facturi individuale)
|
||||||
base_query = f"""
|
base_query = f"""
|
||||||
WITH luna_curenta AS (
|
{period_cte},
|
||||||
SELECT anul, luna FROM {schema}.calendar
|
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
|
||||||
),
|
|
||||||
furnizori_cu_sold AS (
|
furnizori_cu_sold AS (
|
||||||
-- Pasul 1: Identifică TOȚI furnizorii cu sold != 0
|
-- Pasul 1: Identifică TOȚI furnizorii cu sold != 0
|
||||||
SELECT DISTINCT vp.nume as furnizor_name
|
SELECT DISTINCT vp.nume as furnizor_name
|
||||||
@@ -1061,9 +1109,9 @@ class DashboardService:
|
|||||||
# Get total count of CLIENȚI/FURNIZORI (not individual invoices)
|
# Get total count of CLIENȚI/FURNIZORI (not individual invoices)
|
||||||
if data_type == "clients":
|
if data_type == "clients":
|
||||||
count_query = f"""
|
count_query = f"""
|
||||||
|
{period_cte}
|
||||||
SELECT COUNT(DISTINCT vp.nume)
|
SELECT COUNT(DISTINCT vp.nume)
|
||||||
FROM {schema}.vireg_parteneri vp,
|
FROM {schema}.vireg_parteneri vp, luna_curenta lc
|
||||||
(SELECT anul, luna FROM {schema}.calendar WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)) lc
|
|
||||||
WHERE vp.an = lc.anul
|
WHERE vp.an = lc.anul
|
||||||
AND vp.luna = lc.luna
|
AND vp.luna = lc.luna
|
||||||
AND vp.cont IN ('4111','461')
|
AND vp.cont IN ('4111','461')
|
||||||
@@ -1073,9 +1121,9 @@ class DashboardService:
|
|||||||
"""
|
"""
|
||||||
elif data_type == "suppliers":
|
elif data_type == "suppliers":
|
||||||
count_query = f"""
|
count_query = f"""
|
||||||
|
{period_cte}
|
||||||
SELECT COUNT(DISTINCT vp.nume)
|
SELECT COUNT(DISTINCT vp.nume)
|
||||||
FROM {schema}.vireg_parteneri vp,
|
FROM {schema}.vireg_parteneri vp, luna_curenta lc
|
||||||
(SELECT anul, luna FROM {schema}.calendar WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)) lc
|
|
||||||
WHERE vp.an = lc.anul
|
WHERE vp.an = lc.anul
|
||||||
AND vp.luna = lc.luna
|
AND vp.luna = lc.luna
|
||||||
AND vp.cont IN ('401','404','462')
|
AND vp.cont IN ('401','404','462')
|
||||||
@@ -1084,13 +1132,13 @@ class DashboardService:
|
|||||||
AND (UPPER(vp.nume) LIKE UPPER('%{search}%') OR '{search}' = '')
|
AND (UPPER(vp.nume) LIKE UPPER('%{search}%') OR '{search}' = '')
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(count_query)
|
cursor.execute(count_query, period_params)
|
||||||
total = cursor.fetchone()[0]
|
total = cursor.fetchone()[0]
|
||||||
logger.info(f"Total {data_type}: {total}")
|
logger.info(f"Total {data_type}: {total}")
|
||||||
|
|
||||||
# Execute base query directly (pagination already included in CTE)
|
# Execute base query directly (pagination already included in CTE)
|
||||||
logger.info(f"Executing query with offset={offset}, page_size={page_size}")
|
logger.info(f"Executing query with offset={offset}, page_size={page_size}")
|
||||||
cursor.execute(base_query)
|
cursor.execute(base_query, period_params)
|
||||||
columns = [desc[0].lower() for desc in cursor.description]
|
columns = [desc[0].lower() for desc in cursor.description]
|
||||||
|
|
||||||
data = []
|
data = []
|
||||||
@@ -1300,14 +1348,16 @@ class DashboardService:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@cached(cache_type='maturity_analysis', key_params=['company_id', 'period'])
|
@cached(cache_type='maturity_analysis', key_params=['company_id', 'period', 'luna', 'an'])
|
||||||
async def get_maturity_analysis(company_id: int, period: str = "7d", request: Optional[Request] = None) -> Dict[str, Any]:
|
async def get_maturity_analysis(company_id: int, period: str = "7d", luna: Optional[int] = None, an: Optional[int] = None, request: Optional[Request] = None) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Analizează scadențele clienți vs furnizori cu date reale din Oracle (CACHED 30 min)
|
Analizează scadențele clienți vs furnizori cu date reale din Oracle (CACHED 30 min)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
company_id: ID-ul companiei
|
company_id: ID-ul companiei
|
||||||
period: Perioada ("7d", "1m", "3m", "6m", "12m", "over12m")
|
period: Perioada ("7d", "1m", "3m", "6m", "12m", "over12m")
|
||||||
|
luna: Luna contabilă (1-12), opțional
|
||||||
|
an: Anul contabil, opțional
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
{
|
{
|
||||||
@@ -1330,6 +1380,9 @@ class DashboardService:
|
|||||||
|
|
||||||
schema = schema_result[0]
|
schema = schema_result[0]
|
||||||
|
|
||||||
|
# Construiește CTE pentru perioada curentă
|
||||||
|
period_cte, period_params = DashboardService._build_period_cte(schema, luna, an)
|
||||||
|
|
||||||
# Determină filtrele pentru perioada selectată (orizont de planificare)
|
# Determină filtrele pentru perioada selectată (orizont de planificare)
|
||||||
# Logică: Include TOATE restanțele + scadențele viitoare din perioada selectată
|
# Logică: Include TOATE restanțele + scadențele viitoare din perioada selectată
|
||||||
if period == "7d":
|
if period == "7d":
|
||||||
@@ -1347,11 +1400,7 @@ class DashboardService:
|
|||||||
|
|
||||||
# Query pentru clienți (facturi de încasat)
|
# Query pentru clienți (facturi de încasat)
|
||||||
clients_query = f"""
|
clients_query = f"""
|
||||||
WITH luna_curenta AS
|
{period_cte}
|
||||||
(SELECT anul, luna
|
|
||||||
FROM {schema}.calendar
|
|
||||||
WHERE anul * 12 + luna =
|
|
||||||
(SELECT MAX(anul * 12 + luna) FROM {schema}.calendar))
|
|
||||||
SELECT client_name,
|
SELECT client_name,
|
||||||
SUM(amount) as amount,
|
SUM(amount) as amount,
|
||||||
MAX(due_date) as due_date,
|
MAX(due_date) as due_date,
|
||||||
@@ -1372,7 +1421,7 @@ class DashboardService:
|
|||||||
ORDER BY days_overdue desc
|
ORDER BY days_overdue desc
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(clients_query)
|
cursor.execute(clients_query, period_params)
|
||||||
clients_rows = cursor.fetchall()
|
clients_rows = cursor.fetchall()
|
||||||
|
|
||||||
clients = []
|
clients = []
|
||||||
@@ -1394,11 +1443,7 @@ class DashboardService:
|
|||||||
|
|
||||||
# Query pentru furnizori (facturi de plătit)
|
# Query pentru furnizori (facturi de plătit)
|
||||||
suppliers_query = f"""
|
suppliers_query = f"""
|
||||||
WITH luna_curenta AS
|
{period_cte}
|
||||||
(SELECT anul, luna
|
|
||||||
FROM {schema}.calendar
|
|
||||||
WHERE anul * 12 + luna =
|
|
||||||
(SELECT MAX(anul * 12 + luna) FROM {schema}.calendar))
|
|
||||||
SELECT client_name,
|
SELECT client_name,
|
||||||
SUM(amount) as amount,
|
SUM(amount) as amount,
|
||||||
MIN(due_date) as due_date,
|
MIN(due_date) as due_date,
|
||||||
@@ -1419,7 +1464,7 @@ class DashboardService:
|
|||||||
ORDER BY days_overdue desc
|
ORDER BY days_overdue desc
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(suppliers_query)
|
cursor.execute(suppliers_query, period_params)
|
||||||
suppliers_rows = cursor.fetchall()
|
suppliers_rows = cursor.fetchall()
|
||||||
|
|
||||||
suppliers = []
|
suppliers = []
|
||||||
@@ -1502,9 +1547,14 @@ class DashboardService:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_monthly_flows(company: int) -> Dict[str, Any]:
|
async def get_monthly_flows(company: int, luna: Optional[int] = None, an: Optional[int] = None) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Obține fluxurile lunare de intrare și ieșire pentru luna curentă
|
Obține fluxurile lunare de intrare și ieșire pentru luna curentă
|
||||||
|
|
||||||
|
Args:
|
||||||
|
company: ID-ul firmei
|
||||||
|
luna: Luna contabilă (1-12), opțional
|
||||||
|
an: Anul contabil, opțional
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
async with oracle_pool.get_connection() as connection:
|
async with oracle_pool.get_connection() as connection:
|
||||||
@@ -1520,14 +1570,27 @@ class DashboardService:
|
|||||||
|
|
||||||
schema = schema_result[0]
|
schema = schema_result[0]
|
||||||
|
|
||||||
|
# Construiește CTE pentru perioada curentă (cu period column)
|
||||||
|
if luna is not None and an is not None:
|
||||||
|
period_cte = f"""
|
||||||
|
WITH luna_curenta AS (
|
||||||
|
SELECT :param_an as anul, :param_luna as luna,
|
||||||
|
:param_an || '-' || LPAD(:param_luna, 2, '0') as period
|
||||||
|
FROM DUAL
|
||||||
|
)"""
|
||||||
|
period_params = {'param_an': an, 'param_luna': luna}
|
||||||
|
else:
|
||||||
|
period_cte = f"""
|
||||||
|
WITH luna_curenta AS (
|
||||||
|
SELECT anul, luna, anul || '-' || LPAD(luna, 2, '0') as period
|
||||||
|
FROM {schema}.calendar
|
||||||
|
WHERE anul * 12 + luna = (SELECT MAX(c2.anul * 12 + c2.luna) FROM {schema}.calendar c2)
|
||||||
|
)"""
|
||||||
|
period_params = {}
|
||||||
|
|
||||||
# Query pentru fluxuri lunare
|
# Query pentru fluxuri lunare
|
||||||
flows_query = f"""
|
flows_query = f"""
|
||||||
WITH luna_curenta AS
|
{period_cte}
|
||||||
(SELECT anul, luna, anul || '-' || LPAD(luna, 2, '0') as period
|
|
||||||
FROM {schema}.calendar
|
|
||||||
WHERE anul * 12 + luna =
|
|
||||||
(SELECT MAX(c2.anul * 12 + c2.luna)
|
|
||||||
FROM {schema}.calendar c2))
|
|
||||||
SELECT
|
SELECT
|
||||||
SUM(CASE
|
SUM(CASE
|
||||||
WHEN vp.cont IN ('4111', '461') THEN
|
WHEN vp.cont IN ('4111', '461') THEN
|
||||||
@@ -1552,14 +1615,16 @@ class DashboardService:
|
|||||||
AND vp.cont IN ('4111', '461', '419', '401', '404', '462', '409')
|
AND vp.cont IN ('4111', '461', '419', '401', '404', '462', '409')
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(flows_query)
|
cursor.execute(flows_query, period_params)
|
||||||
flow_row = cursor.fetchone()
|
flow_row = cursor.fetchone()
|
||||||
|
|
||||||
if not flow_row:
|
if not flow_row:
|
||||||
|
# Default period from params or current date
|
||||||
|
default_period = f"{an}-{str(luna).zfill(2)}" if luna and an else "2025-12"
|
||||||
return {
|
return {
|
||||||
"inflows": 0,
|
"inflows": 0,
|
||||||
"outflows": 0,
|
"outflows": 0,
|
||||||
"period": "2025-08",
|
"period": default_period,
|
||||||
"currency": "RON"
|
"currency": "RON"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1574,10 +1639,15 @@ class DashboardService:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@cached(cache_type='treasury_breakdown', key_params=['company'])
|
@cached(cache_type='treasury_breakdown', key_params=['company', 'luna', 'an'])
|
||||||
async def get_treasury_breakdown(company: int, request: Optional[Request] = None) -> Dict[str, Any]:
|
async def get_treasury_breakdown(company: int, luna: Optional[int] = None, an: Optional[int] = None, request: Optional[Request] = None) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Obține breakdown-ul trezoreriei pe casă și bancă (CACHED 30 min)
|
Obține breakdown-ul trezoreriei pe casă și bancă (CACHED 30 min)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
company: ID-ul firmei
|
||||||
|
luna: Luna contabilă (1-12), opțional
|
||||||
|
an: Anul contabil, opțional
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
async with oracle_pool.get_connection() as connection:
|
async with oracle_pool.get_connection() as connection:
|
||||||
@@ -1593,13 +1663,12 @@ class DashboardService:
|
|||||||
|
|
||||||
schema = schema_result[0]
|
schema = schema_result[0]
|
||||||
|
|
||||||
|
# Construiește CTE pentru perioada curentă
|
||||||
|
period_cte, period_params = DashboardService._build_period_cte(schema, luna, an)
|
||||||
|
|
||||||
# Query pentru breakdown trezorerie - cu nume reale și sub-breakdown
|
# Query pentru breakdown trezorerie - cu nume reale și sub-breakdown
|
||||||
treasury_query = f"""
|
treasury_query = f"""
|
||||||
WITH luna_curenta AS
|
{period_cte}
|
||||||
(SELECT anul, luna
|
|
||||||
FROM {schema}.calendar
|
|
||||||
WHERE anul * 12 + luna =
|
|
||||||
(SELECT MAX(c2.anul * 12 + c2.luna) FROM {schema}.calendar c2))
|
|
||||||
SELECT
|
SELECT
|
||||||
vb.cont,
|
vb.cont,
|
||||||
vb.nume as nume_real,
|
vb.nume as nume_real,
|
||||||
@@ -1616,7 +1685,7 @@ class DashboardService:
|
|||||||
ORDER BY tip, vb.cont
|
ORDER BY tip, vb.cont
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(treasury_query)
|
cursor.execute(treasury_query, period_params)
|
||||||
treasury_rows = cursor.fetchall()
|
treasury_rows = cursor.fetchall()
|
||||||
|
|
||||||
if not treasury_rows:
|
if not treasury_rows:
|
||||||
@@ -1675,10 +1744,15 @@ class DashboardService:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@cached(cache_type='net_balance_breakdown', key_params=['company'])
|
@cached(cache_type='net_balance_breakdown', key_params=['company', 'luna', 'an'])
|
||||||
async def get_net_balance_breakdown(company: int, request: Optional[Request] = None) -> Dict[str, Any]:
|
async def get_net_balance_breakdown(company: int, luna: Optional[int] = None, an: Optional[int] = None, request: Optional[Request] = None) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Obține breakdown-ul balanței nete pe clienți și furnizori cu detaliere pe perioade (CACHED 30 min)
|
Obține breakdown-ul balanței nete pe clienți și furnizori cu detaliere pe perioade (CACHED 30 min)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
company: ID-ul firmei
|
||||||
|
luna: Luna contabilă (1-12), opțional
|
||||||
|
an: Anul contabil, opțional
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
async with oracle_pool.get_connection() as connection:
|
async with oracle_pool.get_connection() as connection:
|
||||||
@@ -1694,13 +1768,12 @@ class DashboardService:
|
|||||||
|
|
||||||
schema = schema_result[0]
|
schema = schema_result[0]
|
||||||
|
|
||||||
|
# Construiește CTE pentru perioada curentă
|
||||||
|
period_cte, period_params = DashboardService._build_period_cte(schema, luna, an)
|
||||||
|
|
||||||
# Query extins pentru breakdown detaliat pe perioade
|
# Query extins pentru breakdown detaliat pe perioade
|
||||||
balance_query = f"""
|
balance_query = f"""
|
||||||
WITH luna_curenta AS (
|
{period_cte}
|
||||||
SELECT anul, luna
|
|
||||||
FROM {schema}.calendar
|
|
||||||
WHERE anul*12+luna = (SELECT MAX(c2.anul*12+c2.luna) FROM {schema}.calendar c2)
|
|
||||||
)
|
|
||||||
SELECT
|
SELECT
|
||||||
-- CLIENȚI - Sold total
|
-- CLIENȚI - Sold total
|
||||||
SUM(CASE
|
SUM(CASE
|
||||||
@@ -1794,7 +1867,7 @@ class DashboardService:
|
|||||||
AND vp.cont IN ('4111', '461', '419', '401', '404', '462','409')
|
AND vp.cont IN ('4111', '461', '419', '401', '404', '462','409')
|
||||||
"""
|
"""
|
||||||
|
|
||||||
cursor.execute(balance_query)
|
cursor.execute(balance_query, period_params)
|
||||||
row = cursor.fetchone()
|
row = cursor.fetchone()
|
||||||
|
|
||||||
if not row:
|
if not row:
|
||||||
|
|||||||
@@ -56,6 +56,15 @@ class InvoiceService:
|
|||||||
else:
|
else:
|
||||||
conturi = "'4111'" # default
|
conturi = "'4111'" # default
|
||||||
|
|
||||||
|
# Determine period to use: from params or MAX from calendar
|
||||||
|
if filter_params.luna and filter_params.an:
|
||||||
|
period_condition = "vp.an = :an AND vp.luna = :luna"
|
||||||
|
use_param_period = True
|
||||||
|
else:
|
||||||
|
period_condition = f"""vp.an = (SELECT anul FROM {schema}.calendar WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar))
|
||||||
|
AND vp.luna = (SELECT luna FROM {schema}.calendar WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar))"""
|
||||||
|
use_param_period = False
|
||||||
|
|
||||||
# Query cu calculele corecte pentru solduri
|
# Query cu calculele corecte pentru solduri
|
||||||
base_query = f"""
|
base_query = f"""
|
||||||
SELECT
|
SELECT
|
||||||
@@ -87,8 +96,7 @@ class InvoiceService:
|
|||||||
ELSE 'in_termen'
|
ELSE 'in_termen'
|
||||||
END as status
|
END as status
|
||||||
FROM {schema}.vireg_parteneri vp
|
FROM {schema}.vireg_parteneri vp
|
||||||
WHERE vp.an = (SELECT anul FROM {schema}.calendar WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar))
|
WHERE {period_condition}
|
||||||
AND vp.luna = (SELECT luna FROM {schema}.calendar WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar))
|
|
||||||
AND (
|
AND (
|
||||||
(:partner_type = 'CLIENTI' AND vp.cont IN ('4111', '461'))
|
(:partner_type = 'CLIENTI' AND vp.cont IN ('4111', '461'))
|
||||||
OR
|
OR
|
||||||
@@ -98,14 +106,10 @@ class InvoiceService:
|
|||||||
|
|
||||||
params = {'partner_type': filter_params.partner_type}
|
params = {'partner_type': filter_params.partner_type}
|
||||||
|
|
||||||
# Adaugă filtre dinamice
|
# Add period params if using explicit period
|
||||||
if filter_params.date_from:
|
if use_param_period:
|
||||||
base_query += " AND vp.dataact >= :date_from"
|
params['an'] = filter_params.an
|
||||||
params['date_from'] = filter_params.date_from
|
params['luna'] = filter_params.luna
|
||||||
|
|
||||||
if filter_params.date_to:
|
|
||||||
base_query += " AND vp.dataact <= :date_to"
|
|
||||||
params['date_to'] = filter_params.date_to
|
|
||||||
|
|
||||||
if filter_params.partner_name:
|
if filter_params.partner_name:
|
||||||
base_query += " AND UPPER(vp.nume) LIKE UPPER(:partner_name)"
|
base_query += " AND UPPER(vp.nume) LIKE UPPER(:partner_name)"
|
||||||
@@ -139,18 +143,24 @@ class InvoiceService:
|
|||||||
cursor.execute(count_query, params)
|
cursor.execute(count_query, params)
|
||||||
total_count = cursor.fetchone()[0]
|
total_count = cursor.fetchone()[0]
|
||||||
|
|
||||||
# Get accounting period (luna, an) from calendar
|
# Get accounting period - use params if provided, else from calendar
|
||||||
period_query = f"""
|
if use_param_period:
|
||||||
SELECT anul, luna
|
accounting_period = {
|
||||||
FROM {schema}.calendar
|
'an': filter_params.an,
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
'luna': filter_params.luna
|
||||||
"""
|
}
|
||||||
cursor.execute(period_query)
|
else:
|
||||||
period_result = cursor.fetchone()
|
period_query = f"""
|
||||||
accounting_period = {
|
SELECT anul, luna
|
||||||
'an': period_result[0] if period_result else None,
|
FROM {schema}.calendar
|
||||||
'luna': period_result[1] if period_result else None
|
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar)
|
||||||
}
|
"""
|
||||||
|
cursor.execute(period_query)
|
||||||
|
period_result = cursor.fetchone()
|
||||||
|
accounting_period = {
|
||||||
|
'an': period_result[0] if period_result else None,
|
||||||
|
'luna': period_result[1] if period_result else None
|
||||||
|
}
|
||||||
|
|
||||||
# Adaugă ORDER BY și paginare - Ordonare cronologică (DATAACT, NRACT, NUME)
|
# Adaugă ORDER BY și paginare - Ordonare cronologică (DATAACT, NRACT, NUME)
|
||||||
base_query += " ORDER BY vp.DATAACT ASC, vp.NRACT ASC, vp.NUME"
|
base_query += " ORDER BY vp.DATAACT ASC, vp.NRACT ASC, vp.NUME"
|
||||||
|
|||||||
@@ -153,8 +153,23 @@ class TreasuryService:
|
|||||||
offset = (filter_params.page - 1) * filter_params.page_size
|
offset = (filter_params.page - 1) * filter_params.page_size
|
||||||
limit_val = filter_params.page_size
|
limit_val = filter_params.page_size
|
||||||
|
|
||||||
|
# Determine period to use: from params or MAX from calendar
|
||||||
|
if filter_params.luna and filter_params.an:
|
||||||
|
use_param_period = True
|
||||||
|
period_select = f"""
|
||||||
|
v_an := :param_an;
|
||||||
|
v_luna := :param_luna;
|
||||||
|
"""
|
||||||
|
else:
|
||||||
|
use_param_period = False
|
||||||
|
period_select = f"""
|
||||||
|
SELECT anul, luna INTO v_an, v_luna
|
||||||
|
FROM {schema}.calendar
|
||||||
|
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar);
|
||||||
|
"""
|
||||||
|
|
||||||
# Bloc PL/SQL anonim care face totul într-o singură tranzacție:
|
# Bloc PL/SQL anonim care face totul într-o singură tranzacție:
|
||||||
# 1. Obține anul și luna din calendar
|
# 1. Obține anul și luna din params sau calendar
|
||||||
# 2. Setează PACK_SESIUNE.SETAN și SETLUNA
|
# 2. Setează PACK_SESIUNE.SETAN și SETLUNA
|
||||||
# 3. Returnează datele prin REF CURSOR
|
# 3. Returnează datele prin REF CURSOR
|
||||||
# IMPORTANT: Folosim ROW_NUMBER() pentru paginare corectă cu ORDER BY NULLS FIRST
|
# IMPORTANT: Folosim ROW_NUMBER() pentru paginare corectă cu ORDER BY NULLS FIRST
|
||||||
@@ -164,10 +179,8 @@ class TreasuryService:
|
|||||||
v_luna NUMBER;
|
v_luna NUMBER;
|
||||||
v_cursor SYS_REFCURSOR;
|
v_cursor SYS_REFCURSOR;
|
||||||
BEGIN
|
BEGIN
|
||||||
-- Obține anul și luna curentă din calendar
|
-- Obține anul și luna din parametri sau calendar
|
||||||
SELECT anul, luna INTO v_an, v_luna
|
{period_select}
|
||||||
FROM {schema}.calendar
|
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar);
|
|
||||||
|
|
||||||
-- Setează contextul de sesiune (OBLIGATORIU înainte de SELECT din vbancasa*)
|
-- Setează contextul de sesiune (OBLIGATORIU înainte de SELECT din vbancasa*)
|
||||||
{schema}.PACK_SESIUNE.SETAN(v_an);
|
{schema}.PACK_SESIUNE.SETAN(v_an);
|
||||||
@@ -198,8 +211,14 @@ class TreasuryService:
|
|||||||
out_an = cursor.var(int)
|
out_an = cursor.var(int)
|
||||||
out_luna = cursor.var(int)
|
out_luna = cursor.var(int)
|
||||||
|
|
||||||
|
# Build params dict
|
||||||
|
exec_params = {'result_cursor': result_cursor, 'out_an': out_an, 'out_luna': out_luna}
|
||||||
|
if use_param_period:
|
||||||
|
exec_params['param_an'] = filter_params.an
|
||||||
|
exec_params['param_luna'] = filter_params.luna
|
||||||
|
|
||||||
# Execută blocul PL/SQL cu REF CURSOR
|
# Execută blocul PL/SQL cu REF CURSOR
|
||||||
cursor.execute(plsql_block, {'result_cursor': result_cursor, 'out_an': out_an, 'out_luna': out_luna})
|
cursor.execute(plsql_block, exec_params)
|
||||||
|
|
||||||
# Get accounting period values
|
# Get accounting period values
|
||||||
accounting_year = out_an.getvalue()
|
accounting_year = out_an.getvalue()
|
||||||
@@ -216,9 +235,8 @@ class TreasuryService:
|
|||||||
v_an NUMBER;
|
v_an NUMBER;
|
||||||
v_luna NUMBER;
|
v_luna NUMBER;
|
||||||
BEGIN
|
BEGIN
|
||||||
SELECT anul, luna INTO v_an, v_luna
|
-- Obține anul și luna din parametri sau calendar
|
||||||
FROM {schema}.calendar
|
{period_select}
|
||||||
WHERE anul*12+luna = (SELECT MAX(anul*12+luna) FROM {schema}.calendar);
|
|
||||||
|
|
||||||
{schema}.PACK_SESIUNE.SETAN(v_an);
|
{schema}.PACK_SESIUNE.SETAN(v_an);
|
||||||
{schema}.PACK_SESIUNE.SETLUNA(v_luna);
|
{schema}.PACK_SESIUNE.SETLUNA(v_luna);
|
||||||
@@ -228,7 +246,11 @@ class TreasuryService:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
total_count_var = cursor.var(int)
|
total_count_var = cursor.var(int)
|
||||||
cursor.execute(count_plsql, {'total_count': total_count_var})
|
count_params = {'total_count': total_count_var}
|
||||||
|
if use_param_period:
|
||||||
|
count_params['param_an'] = filter_params.an
|
||||||
|
count_params['param_luna'] = filter_params.luna
|
||||||
|
cursor.execute(count_plsql, count_params)
|
||||||
total_count = total_count_var.getvalue()
|
total_count = total_count_var.getvalue()
|
||||||
|
|
||||||
# Procesare rezultate
|
# Procesare rezultate
|
||||||
|
|||||||
@@ -0,0 +1,366 @@
|
|||||||
|
<template>
|
||||||
|
<div class="period-selector-mini" ref="dropdownContainer">
|
||||||
|
<div class="period-dropdown" ref="dropdown">
|
||||||
|
<button
|
||||||
|
class="period-trigger"
|
||||||
|
@click="toggleDropdown"
|
||||||
|
:disabled="!companyStore.selectedCompany"
|
||||||
|
:aria-expanded="dropdownOpen"
|
||||||
|
aria-label="Select accounting period"
|
||||||
|
>
|
||||||
|
<div class="period-info">
|
||||||
|
<span class="period-label">Perioada:</span>
|
||||||
|
<span class="period-name">{{ selectedPeriodDisplay }}</span>
|
||||||
|
</div>
|
||||||
|
<i
|
||||||
|
class="pi pi-chevron-down"
|
||||||
|
:class="{ 'rotate-180': dropdownOpen }"
|
||||||
|
></i>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-show="dropdownOpen"
|
||||||
|
class="period-dropdown-panel"
|
||||||
|
:class="{ 'panel-open': dropdownOpen }"
|
||||||
|
>
|
||||||
|
<div class="period-list">
|
||||||
|
<div
|
||||||
|
v-for="(period, index) in periodStore.periods"
|
||||||
|
:key="`${period.an}-${period.luna}`"
|
||||||
|
class="period-item"
|
||||||
|
:class="{
|
||||||
|
active: isSelected(period),
|
||||||
|
'keyboard-highlighted': isHighlighted(index),
|
||||||
|
}"
|
||||||
|
@click="selectPeriod(period)"
|
||||||
|
@mouseenter="highlightedIndex = index"
|
||||||
|
>
|
||||||
|
<div class="period-details">
|
||||||
|
{{ period.display_name }}
|
||||||
|
</div>
|
||||||
|
<i v-if="isSelected(period)" class="pi pi-check period-selected-icon"></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="periodStore.periods.length === 0" class="no-results">
|
||||||
|
<i class="pi pi-info-circle"></i>
|
||||||
|
<span>Nu sunt perioade disponibile</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from "vue";
|
||||||
|
import { useAccountingPeriodStore } from "../../stores/accountingPeriod";
|
||||||
|
import { useCompanyStore } from "../../stores/companies";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: "PeriodSelectorMini",
|
||||||
|
emits: ["period-changed"],
|
||||||
|
setup(props, { emit }) {
|
||||||
|
const periodStore = useAccountingPeriodStore();
|
||||||
|
const companyStore = useCompanyStore();
|
||||||
|
const dropdown = ref(null);
|
||||||
|
const dropdownContainer = ref(null);
|
||||||
|
const dropdownOpen = ref(false);
|
||||||
|
const highlightedIndex = ref(-1);
|
||||||
|
|
||||||
|
const selectedPeriodDisplay = computed(() => {
|
||||||
|
return periodStore.selectedPeriod?.display_name || "Selectare perioada";
|
||||||
|
});
|
||||||
|
|
||||||
|
const isSelected = (period) => {
|
||||||
|
if (!periodStore.selectedPeriod) return false;
|
||||||
|
return (
|
||||||
|
period.an === periodStore.selectedPeriod.an &&
|
||||||
|
period.luna === periodStore.selectedPeriod.luna
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isHighlighted = (index) => {
|
||||||
|
return index === highlightedIndex.value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleDropdown = async () => {
|
||||||
|
if (!companyStore.selectedCompany) return;
|
||||||
|
dropdownOpen.value = !dropdownOpen.value;
|
||||||
|
if (dropdownOpen.value) {
|
||||||
|
highlightedIndex.value = -1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeDropdown = () => {
|
||||||
|
dropdownOpen.value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectPeriod = (period) => {
|
||||||
|
periodStore.setSelectedPeriod(period);
|
||||||
|
emit("period-changed", period);
|
||||||
|
closeDropdown();
|
||||||
|
};
|
||||||
|
|
||||||
|
const scrollToHighlighted = () => {
|
||||||
|
nextTick(() => {
|
||||||
|
const highlightedElement = document.querySelector(
|
||||||
|
".period-item.keyboard-highlighted"
|
||||||
|
);
|
||||||
|
if (highlightedElement) {
|
||||||
|
highlightedElement.scrollIntoView({
|
||||||
|
block: "nearest",
|
||||||
|
behavior: "smooth",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyDown = (event) => {
|
||||||
|
if (!dropdownOpen.value || periodStore.periods.length === 0) return;
|
||||||
|
|
||||||
|
switch (event.key) {
|
||||||
|
case "ArrowDown":
|
||||||
|
event.preventDefault();
|
||||||
|
highlightedIndex.value =
|
||||||
|
(highlightedIndex.value + 1) % periodStore.periods.length;
|
||||||
|
scrollToHighlighted();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "ArrowUp":
|
||||||
|
event.preventDefault();
|
||||||
|
if (highlightedIndex.value <= 0) {
|
||||||
|
highlightedIndex.value = periodStore.periods.length - 1;
|
||||||
|
} else {
|
||||||
|
highlightedIndex.value--;
|
||||||
|
}
|
||||||
|
scrollToHighlighted();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "Enter":
|
||||||
|
event.preventDefault();
|
||||||
|
if (
|
||||||
|
highlightedIndex.value >= 0 &&
|
||||||
|
highlightedIndex.value < periodStore.periods.length
|
||||||
|
) {
|
||||||
|
selectPeriod(periodStore.periods[highlightedIndex.value]);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "Escape":
|
||||||
|
closeDropdown();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClickOutside = (event) => {
|
||||||
|
if (dropdown.value && !dropdown.value.contains(event.target)) {
|
||||||
|
closeDropdown();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Watch for company changes - load periods and reset to latest
|
||||||
|
watch(
|
||||||
|
() => companyStore.selectedCompany,
|
||||||
|
async (newCompany) => {
|
||||||
|
if (newCompany) {
|
||||||
|
await periodStore.loadPeriods(newCompany.id_firma);
|
||||||
|
} else {
|
||||||
|
periodStore.reset();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
document.addEventListener("click", handleClickOutside);
|
||||||
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
});
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
document.removeEventListener("click", handleClickOutside);
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
periodStore,
|
||||||
|
companyStore,
|
||||||
|
dropdown,
|
||||||
|
dropdownContainer,
|
||||||
|
dropdownOpen,
|
||||||
|
highlightedIndex,
|
||||||
|
selectedPeriodDisplay,
|
||||||
|
isSelected,
|
||||||
|
isHighlighted,
|
||||||
|
toggleDropdown,
|
||||||
|
closeDropdown,
|
||||||
|
selectPeriod,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.period-selector-mini {
|
||||||
|
position: relative;
|
||||||
|
max-width: 220px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-dropdown {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-trigger {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-sm);
|
||||||
|
padding: var(--space-sm) var(--space-md);
|
||||||
|
background: var(--color-bg);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all var(--transition-fast);
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
min-width: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-trigger:hover:not(:disabled) {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
background: var(--color-bg-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-trigger:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-info {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-label {
|
||||||
|
font-size: var(--text-xs);
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-name {
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
font-weight: var(--font-medium);
|
||||||
|
color: var(--color-text);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pi-chevron-down {
|
||||||
|
transition: transform var(--transition-fast);
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: var(--text-xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rotate-180 {
|
||||||
|
transform: rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-dropdown-panel {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 4px);
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background: var(--color-bg);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
z-index: var(--z-dropdown);
|
||||||
|
max-height: 300px;
|
||||||
|
overflow: hidden;
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-10px);
|
||||||
|
transition: all var(--transition-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-open {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-list {
|
||||||
|
max-height: 280px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: var(--space-sm) var(--space-md);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color var(--transition-fast);
|
||||||
|
border-bottom: 1px solid var(--color-border-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-item:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-item:hover {
|
||||||
|
background: var(--color-bg-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-item.active {
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: var(--color-text-inverse);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-item.keyboard-highlighted {
|
||||||
|
background: var(--color-bg-secondary);
|
||||||
|
outline: 2px solid var(--color-primary);
|
||||||
|
outline-offset: -2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-item.active.keyboard-highlighted {
|
||||||
|
outline: 2px solid rgba(255, 255, 255, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-details {
|
||||||
|
flex: 1;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-selected-icon {
|
||||||
|
color: inherit;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-results {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: var(--space-sm);
|
||||||
|
padding: var(--space-xl);
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Mobile adjustments */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.period-selector-mini {
|
||||||
|
max-width: none;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-trigger {
|
||||||
|
min-width: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.period-dropdown-panel {
|
||||||
|
left: -16px;
|
||||||
|
right: -16px;
|
||||||
|
width: calc(100% + 32px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -499,6 +499,7 @@
|
|||||||
import { ref, computed, watch, onMounted } from "vue";
|
import { ref, computed, watch, onMounted } from "vue";
|
||||||
import { useDashboardStore } from "../../../stores/dashboard";
|
import { useDashboardStore } from "../../../stores/dashboard";
|
||||||
import { useCompanyStore } from "../../../stores/companies";
|
import { useCompanyStore } from "../../../stores/companies";
|
||||||
|
import { useAccountingPeriodStore } from "../../../stores/accountingPeriod";
|
||||||
import { useToast } from "primevue/usetoast";
|
import { useToast } from "primevue/usetoast";
|
||||||
import Paginator from "primevue/paginator";
|
import Paginator from "primevue/paginator";
|
||||||
import * as XLSX from "xlsx";
|
import * as XLSX from "xlsx";
|
||||||
@@ -519,6 +520,7 @@ const emit = defineEmits(["periodChanged"]);
|
|||||||
// Stores
|
// Stores
|
||||||
const dashboardStore = useDashboardStore();
|
const dashboardStore = useDashboardStore();
|
||||||
const companyStore = useCompanyStore();
|
const companyStore = useCompanyStore();
|
||||||
|
const periodStore = useAccountingPeriodStore();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
|
||||||
// State - Maturity Analysis
|
// State - Maturity Analysis
|
||||||
@@ -819,10 +821,15 @@ const loadMaturityData = async () => {
|
|||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
error.value = null;
|
error.value = null;
|
||||||
|
|
||||||
|
const luna = periodStore.selectedPeriod?.luna || null;
|
||||||
|
const an = periodStore.selectedPeriod?.an || null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await dashboardStore.loadMaturityData(
|
const response = await dashboardStore.loadMaturityData(
|
||||||
props.companyId,
|
props.companyId,
|
||||||
selectedPeriod.value,
|
selectedPeriod.value,
|
||||||
|
luna,
|
||||||
|
an,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
@@ -854,12 +861,17 @@ const loadDetailedData = async () => {
|
|||||||
// Calculate page number from firstRow
|
// Calculate page number from firstRow
|
||||||
const page = Math.floor(firstRow.value / rowsPerPage.value) + 1;
|
const page = Math.floor(firstRow.value / rowsPerPage.value) + 1;
|
||||||
|
|
||||||
|
const luna = periodStore.selectedPeriod?.luna || null;
|
||||||
|
const an = periodStore.selectedPeriod?.an || null;
|
||||||
|
|
||||||
const response = await dashboardStore.loadDetailedData(
|
const response = await dashboardStore.loadDetailedData(
|
||||||
selectedType.value,
|
selectedType.value,
|
||||||
companyStore.selectedCompany.id_firma,
|
companyStore.selectedCompany.id_firma,
|
||||||
page,
|
page,
|
||||||
rowsPerPage.value,
|
rowsPerPage.value,
|
||||||
searchTerm.value,
|
searchTerm.value,
|
||||||
|
luna,
|
||||||
|
an,
|
||||||
);
|
);
|
||||||
detailedData.value = response.data;
|
detailedData.value = response.data;
|
||||||
expandedGroups.value.clear();
|
expandedGroups.value.clear();
|
||||||
@@ -925,6 +937,21 @@ watch(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Watch for accounting period changes - reload data when period changes
|
||||||
|
watch(
|
||||||
|
() => periodStore.selectedPeriod,
|
||||||
|
(newPeriod, oldPeriod) => {
|
||||||
|
if (newPeriod && (newPeriod.luna !== oldPeriod?.luna || newPeriod.an !== oldPeriod?.an)) {
|
||||||
|
console.log("Period changed in MaturityAndDetailsCard:", newPeriod);
|
||||||
|
loadMaturityData();
|
||||||
|
if (isDetailsExpanded.value) {
|
||||||
|
loadDetailedData();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ deep: true }
|
||||||
|
);
|
||||||
|
|
||||||
// Watch for pagination changes
|
// Watch for pagination changes
|
||||||
watch([firstRow, rowsPerPage], () => {
|
watch([firstRow, rowsPerPage], () => {
|
||||||
if (isDetailsExpanded.value && detailedData.value.length > 0) {
|
if (isDetailsExpanded.value && detailedData.value.length > 0) {
|
||||||
|
|||||||
@@ -19,8 +19,12 @@
|
|||||||
</router-link>
|
</router-link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Right side: Company + User -->
|
<!-- Right side: Period + Company + User -->
|
||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
|
<PeriodSelectorMini
|
||||||
|
v-if="selectedCompany"
|
||||||
|
@period-changed="onPeriodChanged"
|
||||||
|
/>
|
||||||
<CompanySelectorMini
|
<CompanySelectorMini
|
||||||
v-model="selectedCompany"
|
v-model="selectedCompany"
|
||||||
@company-changed="onCompanyChanged"
|
@company-changed="onCompanyChanged"
|
||||||
@@ -75,6 +79,7 @@
|
|||||||
import { ref, computed } from "vue";
|
import { ref, computed } from "vue";
|
||||||
import { useRouter } from "vue-router";
|
import { useRouter } from "vue-router";
|
||||||
import CompanySelectorMini from "../dashboard/CompanySelectorMini.vue";
|
import CompanySelectorMini from "../dashboard/CompanySelectorMini.vue";
|
||||||
|
import PeriodSelectorMini from "../dashboard/PeriodSelectorMini.vue";
|
||||||
import { useCompanyStore } from "../../stores/companies";
|
import { useCompanyStore } from "../../stores/companies";
|
||||||
import { useAuthStore } from "../../stores/auth";
|
import { useAuthStore } from "../../stores/auth";
|
||||||
|
|
||||||
@@ -82,6 +87,7 @@ export default {
|
|||||||
name: "DashboardHeader",
|
name: "DashboardHeader",
|
||||||
components: {
|
components: {
|
||||||
CompanySelectorMini,
|
CompanySelectorMini,
|
||||||
|
PeriodSelectorMini,
|
||||||
},
|
},
|
||||||
props: {
|
props: {
|
||||||
menuOpen: {
|
menuOpen: {
|
||||||
@@ -89,7 +95,7 @@ export default {
|
|||||||
default: false,
|
default: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
emits: ["menu-toggle", "company-changed"],
|
emits: ["menu-toggle", "company-changed", "period-changed"],
|
||||||
setup(props, { emit }) {
|
setup(props, { emit }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const companiesStore = useCompanyStore();
|
const companiesStore = useCompanyStore();
|
||||||
@@ -120,6 +126,10 @@ export default {
|
|||||||
emit("company-changed", company);
|
emit("company-changed", company);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const onPeriodChanged = (period) => {
|
||||||
|
emit("period-changed", period);
|
||||||
|
};
|
||||||
|
|
||||||
const navigateToTelegram = async () => {
|
const navigateToTelegram = async () => {
|
||||||
try {
|
try {
|
||||||
closeUserMenu();
|
closeUserMenu();
|
||||||
@@ -147,6 +157,7 @@ export default {
|
|||||||
toggleUserMenu,
|
toggleUserMenu,
|
||||||
closeUserMenu,
|
closeUserMenu,
|
||||||
onCompanyChanged,
|
onCompanyChanged,
|
||||||
|
onPeriodChanged,
|
||||||
navigateToTelegram,
|
navigateToTelegram,
|
||||||
handleLogout,
|
handleLogout,
|
||||||
};
|
};
|
||||||
|
|||||||
138
reports-app/frontend/src/stores/accountingPeriod.js
Normal file
138
reports-app/frontend/src/stores/accountingPeriod.js
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
import { defineStore } from "pinia";
|
||||||
|
import { ref, computed } from "vue";
|
||||||
|
import { apiService } from "../services/api";
|
||||||
|
import { useAuthStore } from "./auth";
|
||||||
|
import { useCompanyStore } from "./companies";
|
||||||
|
|
||||||
|
export const useAccountingPeriodStore = defineStore("accountingPeriod", () => {
|
||||||
|
// State
|
||||||
|
const periods = ref([]);
|
||||||
|
const selectedPeriod = ref(null);
|
||||||
|
const isLoading = ref(false);
|
||||||
|
const error = ref(null);
|
||||||
|
|
||||||
|
// Getters
|
||||||
|
const hasPeriods = computed(() => periods.value.length > 0);
|
||||||
|
const currentPeriod = computed(() => selectedPeriod.value);
|
||||||
|
|
||||||
|
// Computed date range for current period (first/last day of month)
|
||||||
|
const dateRange = computed(() => {
|
||||||
|
if (!selectedPeriod.value) return { dateFrom: null, dateTo: null };
|
||||||
|
|
||||||
|
const { an, luna } = selectedPeriod.value;
|
||||||
|
const firstDay = new Date(an, luna - 1, 1);
|
||||||
|
const lastDay = new Date(an, luna, 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
dateFrom: firstDay,
|
||||||
|
dateTo: lastDay,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
const loadPeriods = async (companyId) => {
|
||||||
|
if (!companyId) return { success: false };
|
||||||
|
|
||||||
|
isLoading.value = true;
|
||||||
|
error.value = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await apiService.get("/calendar/periods", {
|
||||||
|
params: { company: companyId },
|
||||||
|
});
|
||||||
|
|
||||||
|
periods.value = response.data.periods || [];
|
||||||
|
|
||||||
|
// Try to restore saved period or use most recent
|
||||||
|
const saved = initializeSelectedPeriod();
|
||||||
|
if (saved) {
|
||||||
|
const exists = periods.value.find(
|
||||||
|
(p) => p.an === saved.an && p.luna === saved.luna
|
||||||
|
);
|
||||||
|
if (exists) {
|
||||||
|
selectedPeriod.value = exists;
|
||||||
|
} else if (response.data.current_period) {
|
||||||
|
setSelectedPeriod(response.data.current_period);
|
||||||
|
}
|
||||||
|
} else if (response.data.current_period) {
|
||||||
|
setSelectedPeriod(response.data.current_period);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err.response?.data?.detail || "Failed to load periods";
|
||||||
|
return { success: false, error: error.value };
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setSelectedPeriod = (period) => {
|
||||||
|
selectedPeriod.value = period;
|
||||||
|
persistSelectedPeriod(period);
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetToLatest = () => {
|
||||||
|
if (periods.value.length > 0) {
|
||||||
|
setSelectedPeriod(periods.value[0]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
periods.value = [];
|
||||||
|
selectedPeriod.value = null;
|
||||||
|
isLoading.value = false;
|
||||||
|
error.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// localStorage helpers
|
||||||
|
const getStorageKey = () => {
|
||||||
|
const authStore = useAuthStore();
|
||||||
|
const companyStore = useCompanyStore();
|
||||||
|
const username = authStore.user?.username;
|
||||||
|
const companyId = companyStore.selectedCompany?.id_firma;
|
||||||
|
if (!username || !companyId) return null;
|
||||||
|
return `selected_period_${username}_${companyId}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const initializeSelectedPeriod = () => {
|
||||||
|
const key = getStorageKey();
|
||||||
|
if (!key) return null;
|
||||||
|
|
||||||
|
const saved = localStorage.getItem(key);
|
||||||
|
if (saved) {
|
||||||
|
try {
|
||||||
|
return JSON.parse(saved);
|
||||||
|
} catch (e) {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const persistSelectedPeriod = (period) => {
|
||||||
|
const key = getStorageKey();
|
||||||
|
if (key && period) {
|
||||||
|
localStorage.setItem(key, JSON.stringify(period));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
// State
|
||||||
|
periods,
|
||||||
|
selectedPeriod,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
|
||||||
|
// Getters
|
||||||
|
hasPeriods,
|
||||||
|
currentPeriod,
|
||||||
|
dateRange,
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
loadPeriods,
|
||||||
|
setSelectedPeriod,
|
||||||
|
resetToLatest,
|
||||||
|
reset,
|
||||||
|
};
|
||||||
|
});
|
||||||
@@ -21,14 +21,16 @@ export const useDashboardStore = defineStore("dashboard", () => {
|
|||||||
// Cache pentru date
|
// Cache pentru date
|
||||||
const dataCache = new Map();
|
const dataCache = new Map();
|
||||||
|
|
||||||
const loadDashboardSummary = async (companyId) => {
|
const loadDashboardSummary = async (companyId, luna = null, an = null) => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
error.value = null;
|
error.value = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiService.get("/dashboard/summary", {
|
const params = { company: companyId };
|
||||||
params: { company: companyId },
|
if (luna !== null) params.luna = luna;
|
||||||
});
|
if (an !== null) params.an = an;
|
||||||
|
|
||||||
|
const response = await apiService.get("/dashboard/summary", { params });
|
||||||
summary.value = response.data;
|
summary.value = response.data;
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -44,21 +46,25 @@ export const useDashboardStore = defineStore("dashboard", () => {
|
|||||||
companyId,
|
companyId,
|
||||||
period = "12m",
|
period = "12m",
|
||||||
chartType = "line",
|
chartType = "line",
|
||||||
|
luna = null,
|
||||||
|
an = null,
|
||||||
) => {
|
) => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
error.value = null;
|
error.value = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log(
|
console.log(
|
||||||
`Loading trend data for company ${companyId}, period: ${period}`,
|
`Loading trend data for company ${companyId}, period: ${period}, luna: ${luna}, an: ${an}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const response = await apiService.get("/dashboard/trends", {
|
const params = {
|
||||||
params: {
|
company: companyId,
|
||||||
company: companyId,
|
period: period,
|
||||||
period: period,
|
};
|
||||||
},
|
if (luna !== null) params.luna = luna;
|
||||||
});
|
if (an !== null) params.an = an;
|
||||||
|
|
||||||
|
const response = await apiService.get("/dashboard/trends", { params });
|
||||||
|
|
||||||
// Validate response structure
|
// Validate response structure
|
||||||
if (!response.data) {
|
if (!response.data) {
|
||||||
@@ -188,20 +194,24 @@ export const useDashboardStore = defineStore("dashboard", () => {
|
|||||||
page = 1,
|
page = 1,
|
||||||
pageSize = 25,
|
pageSize = 25,
|
||||||
search = "",
|
search = "",
|
||||||
|
luna = null,
|
||||||
|
an = null,
|
||||||
) => {
|
) => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
error.value = null;
|
error.value = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiService.get("/dashboard/detailed-data", {
|
const params = {
|
||||||
params: {
|
company: companyId,
|
||||||
company: companyId,
|
data_type: dataType,
|
||||||
data_type: dataType,
|
page: page,
|
||||||
page: page,
|
page_size: pageSize,
|
||||||
page_size: pageSize,
|
search: search,
|
||||||
search: search,
|
};
|
||||||
},
|
if (luna !== null) params.luna = luna;
|
||||||
});
|
if (an !== null) params.an = an;
|
||||||
|
|
||||||
|
const response = await apiService.get("/dashboard/detailed-data", { params });
|
||||||
|
|
||||||
// Store total for pagination
|
// Store total for pagination
|
||||||
detailedDataTotal.value = response.data.total || 0;
|
detailedDataTotal.value = response.data.total || 0;
|
||||||
@@ -417,8 +427,8 @@ export const useDashboardStore = defineStore("dashboard", () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadMaturityData = async (companyId, period = "7d") => {
|
const loadMaturityData = async (companyId, period = "7d", luna = null, an = null) => {
|
||||||
const cacheKey = `maturity-${companyId}-${period}`;
|
const cacheKey = `maturity-${companyId}-${period}-${luna}-${an}`;
|
||||||
|
|
||||||
if (dataCache.has(cacheKey)) {
|
if (dataCache.has(cacheKey)) {
|
||||||
maturityData.value[period] = dataCache.get(cacheKey);
|
maturityData.value[period] = dataCache.get(cacheKey);
|
||||||
@@ -426,9 +436,11 @@ export const useDashboardStore = defineStore("dashboard", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiService.get("/dashboard/maturity", {
|
const params = { company: companyId, period };
|
||||||
params: { company: companyId, period },
|
if (luna !== null) params.luna = luna;
|
||||||
});
|
if (an !== null) params.an = an;
|
||||||
|
|
||||||
|
const response = await apiService.get("/dashboard/maturity", { params });
|
||||||
|
|
||||||
maturityData.value[period] = response.data;
|
maturityData.value[period] = response.data;
|
||||||
dataCache.set(cacheKey, response.data);
|
dataCache.set(cacheKey, response.data);
|
||||||
|
|||||||
@@ -68,30 +68,6 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-col">
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Data Început</label>
|
|
||||||
<Calendar
|
|
||||||
v-model="filters.dateFrom"
|
|
||||||
dateFormat="dd/mm/yy"
|
|
||||||
placeholder="Selectați data"
|
|
||||||
class="w-full"
|
|
||||||
@date-select="handleFilterChange"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="form-col">
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Data Sfârșit</label>
|
|
||||||
<Calendar
|
|
||||||
v-model="filters.dateTo"
|
|
||||||
dateFormat="dd/mm/yy"
|
|
||||||
placeholder="Selectați data"
|
|
||||||
class="w-full"
|
|
||||||
@date-select="handleFilterChange"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="form-col">
|
<div class="form-col">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label class="form-label">Căutare Partener</label>
|
<label class="form-label">Căutare Partener</label>
|
||||||
@@ -287,12 +263,14 @@ import { ref, computed, onMounted, watch } from "vue";
|
|||||||
import { useToast } from "primevue/usetoast";
|
import { useToast } from "primevue/usetoast";
|
||||||
import { useTreasuryStore } from "../stores/treasury";
|
import { useTreasuryStore } from "../stores/treasury";
|
||||||
import { useCompanyStore } from "../stores/companies";
|
import { useCompanyStore } from "../stores/companies";
|
||||||
|
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { exportToExcel, exportBankCashRegisterPDF } from "../utils/exportUtils";
|
import { exportToExcel, exportBankCashRegisterPDF } from "../utils/exportUtils";
|
||||||
|
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const treasuryStore = useTreasuryStore();
|
const treasuryStore = useTreasuryStore();
|
||||||
const companyStore = useCompanyStore();
|
const companyStore = useCompanyStore();
|
||||||
|
const periodStore = useAccountingPeriodStore();
|
||||||
|
|
||||||
// State for company selection
|
// State for company selection
|
||||||
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
|
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
|
||||||
@@ -307,8 +285,6 @@ const registerTypeOptions = [
|
|||||||
|
|
||||||
const filters = ref({
|
const filters = ref({
|
||||||
registerType: "BANCA_LEI", // Default: Registrul de Banca Lei
|
registerType: "BANCA_LEI", // Default: Registrul de Banca Lei
|
||||||
dateFrom: null,
|
|
||||||
dateTo: null,
|
|
||||||
partnerName: "",
|
partnerName: "",
|
||||||
bankAccount: null, // Filter for specific bank/cash account
|
bankAccount: null, // Filter for specific bank/cash account
|
||||||
});
|
});
|
||||||
@@ -400,25 +376,8 @@ const contColumnHeader = computed(() => {
|
|||||||
|
|
||||||
// Accounting period text for PDF export
|
// Accounting period text for PDF export
|
||||||
const accountingPeriodText = computed(() => {
|
const accountingPeriodText = computed(() => {
|
||||||
const months = [
|
// Use the global period store
|
||||||
"Ianuarie",
|
return periodStore.selectedPeriod?.display_name || "";
|
||||||
"Februarie",
|
|
||||||
"Martie",
|
|
||||||
"Aprilie",
|
|
||||||
"Mai",
|
|
||||||
"Iunie",
|
|
||||||
"Iulie",
|
|
||||||
"August",
|
|
||||||
"Septembrie",
|
|
||||||
"Octombrie",
|
|
||||||
"Noiembrie",
|
|
||||||
"Decembrie",
|
|
||||||
];
|
|
||||||
const luna = treasuryStore.accountingPeriod.luna;
|
|
||||||
const an = treasuryStore.accountingPeriod.an;
|
|
||||||
if (!luna || !an) return "";
|
|
||||||
const monthName = months[luna - 1] || "";
|
|
||||||
return `${monthName} ${an}`;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Helper to remove diacritics from text
|
// Helper to remove diacritics from text
|
||||||
@@ -504,8 +463,6 @@ const onPage = async (event) => {
|
|||||||
const resetFilters = async () => {
|
const resetFilters = async () => {
|
||||||
filters.value = {
|
filters.value = {
|
||||||
registerType: "BANCA_LEI", // Reset la default: Registrul de Banca Lei
|
registerType: "BANCA_LEI", // Reset la default: Registrul de Banca Lei
|
||||||
dateFrom: null,
|
|
||||||
dateTo: null,
|
|
||||||
partnerName: "",
|
partnerName: "",
|
||||||
bankAccount: null, // Reset bank account filter
|
bankAccount: null, // Reset bank account filter
|
||||||
};
|
};
|
||||||
@@ -559,12 +516,18 @@ const refreshData = async () => {
|
|||||||
// Fetch ALL data for export (not just current page)
|
// Fetch ALL data for export (not just current page)
|
||||||
const fetchAllData = async () => {
|
const fetchAllData = async () => {
|
||||||
if (!companyStore.selectedCompany) return [];
|
if (!companyStore.selectedCompany) return [];
|
||||||
|
if (!periodStore.selectedPeriod) return [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Get luna/an from period store
|
||||||
|
const { luna, an } = periodStore.selectedPeriod;
|
||||||
|
|
||||||
const params = {
|
const params = {
|
||||||
company: companyStore.selectedCompany.id_firma,
|
company: companyStore.selectedCompany.id_firma,
|
||||||
page: 1,
|
page: 1,
|
||||||
page_size: 999999, // Get all data
|
page_size: 999999, // Get all data
|
||||||
|
luna: luna,
|
||||||
|
an: an,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add register_type filter
|
// Add register_type filter
|
||||||
@@ -572,25 +535,6 @@ const fetchAllData = async () => {
|
|||||||
params.register_type = filters.value.registerType;
|
params.register_type = filters.value.registerType;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add optional filters (use LOCAL date, not UTC)
|
|
||||||
if (filters.value.dateFrom) {
|
|
||||||
const year = filters.value.dateFrom.getFullYear();
|
|
||||||
const month = String(filters.value.dateFrom.getMonth() + 1).padStart(
|
|
||||||
2,
|
|
||||||
"0",
|
|
||||||
);
|
|
||||||
const day = String(filters.value.dateFrom.getDate()).padStart(2, "0");
|
|
||||||
params.date_from = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
if (filters.value.dateTo) {
|
|
||||||
const year = filters.value.dateTo.getFullYear();
|
|
||||||
const month = String(filters.value.dateTo.getMonth() + 1).padStart(
|
|
||||||
2,
|
|
||||||
"0",
|
|
||||||
);
|
|
||||||
const day = String(filters.value.dateTo.getDate()).padStart(2, "0");
|
|
||||||
params.date_to = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
if (filters.value.partnerName) {
|
if (filters.value.partnerName) {
|
||||||
params.partner_name = filters.value.partnerName;
|
params.partner_name = filters.value.partnerName;
|
||||||
}
|
}
|
||||||
@@ -756,33 +700,22 @@ const exportPDF = async () => {
|
|||||||
|
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
if (!companyStore.selectedCompany) return;
|
if (!companyStore.selectedCompany) return;
|
||||||
|
if (!periodStore.selectedPeriod) return; // Wait for period to be loaded
|
||||||
|
|
||||||
treasuryStore.setPagination(pagination.value);
|
treasuryStore.setPagination(pagination.value);
|
||||||
|
|
||||||
// Build filter params - use LOCAL dates, not UTC
|
// Get luna/an from period store
|
||||||
|
const { luna, an } = periodStore.selectedPeriod;
|
||||||
|
|
||||||
|
// Build filter params with luna/an instead of date_from/date_to
|
||||||
const filterParams = {
|
const filterParams = {
|
||||||
partner_name: filters.value.partnerName || undefined,
|
partner_name: filters.value.partnerName || undefined,
|
||||||
register_type: filters.value.registerType || undefined,
|
register_type: filters.value.registerType || undefined,
|
||||||
bank_account: filters.value.bankAccount || undefined,
|
bank_account: filters.value.bankAccount || undefined,
|
||||||
|
luna: luna,
|
||||||
|
an: an,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Format dates properly using local time
|
|
||||||
if (filters.value.dateFrom) {
|
|
||||||
const year = filters.value.dateFrom.getFullYear();
|
|
||||||
const month = String(filters.value.dateFrom.getMonth() + 1).padStart(
|
|
||||||
2,
|
|
||||||
"0",
|
|
||||||
);
|
|
||||||
const day = String(filters.value.dateFrom.getDate()).padStart(2, "0");
|
|
||||||
filterParams.date_from = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
if (filters.value.dateTo) {
|
|
||||||
const year = filters.value.dateTo.getFullYear();
|
|
||||||
const month = String(filters.value.dateTo.getMonth() + 1).padStart(2, "0");
|
|
||||||
const day = String(filters.value.dateTo.getDate()).padStart(2, "0");
|
|
||||||
filterParams.date_to = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
await treasuryStore.loadBankCashRegister(
|
await treasuryStore.loadBankCashRegister(
|
||||||
companyStore.selectedCompany.id_firma,
|
companyStore.selectedCompany.id_firma,
|
||||||
filterParams,
|
filterParams,
|
||||||
@@ -795,23 +728,34 @@ onMounted(async () => {
|
|||||||
await companyStore.loadCompanies();
|
await companyStore.loadCompanies();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load data if company is selected
|
// Load bank accounts for initial register type if company is selected
|
||||||
if (companyStore.selectedCompany) {
|
if (companyStore.selectedCompany) {
|
||||||
// Load bank accounts for initial register type
|
|
||||||
await loadBankAccounts();
|
await loadBankAccounts();
|
||||||
await loadData();
|
|
||||||
}
|
}
|
||||||
|
// Don't load data here - let period watch handle it with immediate: true
|
||||||
});
|
});
|
||||||
|
|
||||||
// Watch for company changes - CRITICAL FIX
|
// Watch for company changes
|
||||||
watch(
|
watch(
|
||||||
() => companyStore.selectedCompany,
|
() => companyStore.selectedCompany,
|
||||||
async (newCompany) => {
|
async (newCompany) => {
|
||||||
if (newCompany) {
|
if (newCompany && periodStore.selectedPeriod) {
|
||||||
|
await loadBankAccounts();
|
||||||
await loadData();
|
await loadData();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Watch for period changes - reload data when period changes
|
||||||
|
watch(
|
||||||
|
() => periodStore.selectedPeriod,
|
||||||
|
async (newPeriod) => {
|
||||||
|
if (newPeriod && companyStore.selectedCompany) {
|
||||||
|
await loadData();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ import FurnizoriBalanceCard from "../components/dashboard/cards/FurnizoriBalance
|
|||||||
import TreasuryDualCard from "../components/dashboard/cards/TreasuryDualCard.vue";
|
import TreasuryDualCard from "../components/dashboard/cards/TreasuryDualCard.vue";
|
||||||
import { useCompanyStore } from "../stores/companies";
|
import { useCompanyStore } from "../stores/companies";
|
||||||
import { useDashboardStore } from "../stores/dashboard";
|
import { useDashboardStore } from "../stores/dashboard";
|
||||||
|
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
|
||||||
import { apiService } from "../services/api";
|
import { apiService } from "../services/api";
|
||||||
import {
|
import {
|
||||||
exportToExcel,
|
exportToExcel,
|
||||||
@@ -106,6 +107,7 @@ import {
|
|||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const companyStore = useCompanyStore();
|
const companyStore = useCompanyStore();
|
||||||
const dashboardStore = useDashboardStore();
|
const dashboardStore = useDashboardStore();
|
||||||
|
const periodStore = useAccountingPeriodStore();
|
||||||
|
|
||||||
// State
|
// State
|
||||||
const filteredCompanies = ref([]);
|
const filteredCompanies = ref([]);
|
||||||
@@ -423,19 +425,22 @@ const bancaPreviousSparkline = computed(() => {
|
|||||||
// Detectare mobile
|
// Detectare mobile
|
||||||
const isMobile = computed(() => window.innerWidth < 768);
|
const isMobile = computed(() => window.innerWidth < 768);
|
||||||
|
|
||||||
// Computed property pentru luna curentă Oracle formatată în română
|
// Computed property pentru luna curentă - folosește perioada din period selector
|
||||||
const currentMonthLabel = computed(() => {
|
const currentMonthLabel = computed(() => {
|
||||||
if (!dashboardStore.currentPeriod) {
|
// Prioritate: period selector > dashboard current period > loading
|
||||||
return "Se încarcă...";
|
if (periodStore.selectedPeriod) {
|
||||||
|
const { an, luna } = periodStore.selectedPeriod;
|
||||||
|
const date = new Date(an, luna - 1, 1);
|
||||||
|
return date.toLocaleDateString("ro-RO", { month: "long", year: "numeric" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { year, month } = dashboardStore.currentPeriod;
|
if (dashboardStore.currentPeriod) {
|
||||||
|
const { year, month } = dashboardStore.currentPeriod;
|
||||||
|
const date = new Date(year, month - 1, 1);
|
||||||
|
return date.toLocaleDateString("ro-RO", { month: "long", year: "numeric" });
|
||||||
|
}
|
||||||
|
|
||||||
// Crează un obiect Date pentru a formata luna în română
|
return "Se încarcă...";
|
||||||
const date = new Date(year, month - 1, 1);
|
|
||||||
|
|
||||||
// Formatează luna în română: "Octombrie 2025"
|
|
||||||
return date.toLocaleDateString("ro-RO", { month: "long", year: "numeric" });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
@@ -474,15 +479,21 @@ const loadTrendData = async () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const luna = periodStore.selectedPeriod?.luna || null;
|
||||||
|
const an = periodStore.selectedPeriod?.an || null;
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
"Loading trend data for company:",
|
"Loading trend data for company:",
|
||||||
companyStore.selectedCompany.id_firma,
|
companyStore.selectedCompany.id_firma,
|
||||||
|
"luna:", luna, "an:", an,
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = await dashboardStore.loadTrendData(
|
const result = await dashboardStore.loadTrendData(
|
||||||
companyStore.selectedCompany.id_firma,
|
companyStore.selectedCompany.id_firma,
|
||||||
selectedPeriod.value,
|
selectedPeriod.value,
|
||||||
selectedChartType.value,
|
selectedChartType.value,
|
||||||
|
luna,
|
||||||
|
an,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
@@ -688,13 +699,18 @@ const handleCompanySelect = async (event) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Fixed: Changed company_id to company parameter
|
// Fixed: Changed company_id to company parameter
|
||||||
|
// Updated: Added luna/an from period selector
|
||||||
const loadMonthlyFlows = async () => {
|
const loadMonthlyFlows = async () => {
|
||||||
if (!companyStore.selectedCompany) return;
|
if (!companyStore.selectedCompany) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiService.get("/dashboard/monthly-flows", {
|
const params = { company: companyStore.selectedCompany.id_firma };
|
||||||
params: { company: companyStore.selectedCompany.id_firma },
|
if (periodStore.selectedPeriod) {
|
||||||
});
|
params.luna = periodStore.selectedPeriod.luna;
|
||||||
|
params.an = periodStore.selectedPeriod.an;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await apiService.get("/dashboard/monthly-flows", { params });
|
||||||
monthlyInflows.value = response.data.inflows || 0;
|
monthlyInflows.value = response.data.inflows || 0;
|
||||||
monthlyOutflows.value = response.data.outflows || 0;
|
monthlyOutflows.value = response.data.outflows || 0;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -706,9 +722,13 @@ const loadTreasuryBreakdown = async () => {
|
|||||||
if (!companyStore.selectedCompany) return;
|
if (!companyStore.selectedCompany) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiService.get("/dashboard/treasury-breakdown", {
|
const params = { company: companyStore.selectedCompany.id_firma };
|
||||||
params: { company: companyStore.selectedCompany.id_firma },
|
if (periodStore.selectedPeriod) {
|
||||||
});
|
params.luna = periodStore.selectedPeriod.luna;
|
||||||
|
params.an = periodStore.selectedPeriod.an;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await apiService.get("/dashboard/treasury-breakdown", { params });
|
||||||
treasuryData.value = response.data;
|
treasuryData.value = response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to load treasury breakdown:", error);
|
console.error("Failed to load treasury breakdown:", error);
|
||||||
@@ -719,9 +739,13 @@ const loadNetBalanceBreakdown = async () => {
|
|||||||
if (!companyStore.selectedCompany) return;
|
if (!companyStore.selectedCompany) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiService.get("/dashboard/net-balance-breakdown", {
|
const params = { company: companyStore.selectedCompany.id_firma };
|
||||||
params: { company: companyStore.selectedCompany.id_firma },
|
if (periodStore.selectedPeriod) {
|
||||||
});
|
params.luna = periodStore.selectedPeriod.luna;
|
||||||
|
params.an = periodStore.selectedPeriod.an;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await apiService.get("/dashboard/net-balance-breakdown", { params });
|
||||||
|
|
||||||
// Folosește direct datele structurate de la backend
|
// Folosește direct datele structurate de la backend
|
||||||
netBalanceData.value = {
|
netBalanceData.value = {
|
||||||
@@ -755,10 +779,15 @@ const loadDashboardData = async () => {
|
|||||||
if (!companyStore.selectedCompany) return;
|
if (!companyStore.selectedCompany) return;
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
|
|
||||||
|
const luna = periodStore.selectedPeriod?.luna || null;
|
||||||
|
const an = periodStore.selectedPeriod?.an || null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
dashboardStore.loadDashboardSummary(
|
dashboardStore.loadDashboardSummary(
|
||||||
companyStore.selectedCompany.id_firma,
|
companyStore.selectedCompany.id_firma,
|
||||||
|
luna,
|
||||||
|
an,
|
||||||
),
|
),
|
||||||
dashboardStore.loadCurrentPeriod(companyStore.selectedCompany.id_firma),
|
dashboardStore.loadCurrentPeriod(companyStore.selectedCompany.id_firma),
|
||||||
loadTrendData(),
|
loadTrendData(),
|
||||||
@@ -807,6 +836,20 @@ watch(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Watch for period selector changes - reload dashboard when period changes
|
||||||
|
watch(
|
||||||
|
() => periodStore.selectedPeriod,
|
||||||
|
async (newPeriod, oldPeriod) => {
|
||||||
|
// Only reload if period actually changed and we have a company selected
|
||||||
|
if (companyStore.selectedCompany && newPeriod &&
|
||||||
|
(newPeriod.luna !== oldPeriod?.luna || newPeriod.an !== oldPeriod?.an)) {
|
||||||
|
console.log("Period changed, reloading dashboard:", newPeriod);
|
||||||
|
await loadDashboardData();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ deep: true }
|
||||||
|
);
|
||||||
|
|
||||||
// Lifecycle
|
// Lifecycle
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
// Load companies first
|
// Load companies first
|
||||||
|
|||||||
@@ -69,33 +69,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Date Range -->
|
|
||||||
<div class="form-col">
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Data De</label>
|
|
||||||
<Calendar
|
|
||||||
v-model="filters.dateFrom"
|
|
||||||
date-format="dd/mm/yy"
|
|
||||||
placeholder="Selectați data"
|
|
||||||
class="w-full"
|
|
||||||
@date-select="handleFilterChange"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-col">
|
|
||||||
<div class="form-group">
|
|
||||||
<label class="form-label">Data Până</label>
|
|
||||||
<Calendar
|
|
||||||
v-model="filters.dateTo"
|
|
||||||
date-format="dd/mm/yy"
|
|
||||||
placeholder="Selectați data"
|
|
||||||
class="w-full"
|
|
||||||
@date-select="handleFilterChange"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Search -->
|
<!-- Search -->
|
||||||
<div class="form-col">
|
<div class="form-col">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -273,6 +246,7 @@ import { ref, computed, onMounted, watch } from "vue";
|
|||||||
import { useToast } from "primevue/usetoast";
|
import { useToast } from "primevue/usetoast";
|
||||||
import { useCompanyStore } from "../stores/companies";
|
import { useCompanyStore } from "../stores/companies";
|
||||||
import { useInvoicesStore } from "../stores/invoices";
|
import { useInvoicesStore } from "../stores/invoices";
|
||||||
|
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { ro } from "date-fns/locale";
|
import { ro } from "date-fns/locale";
|
||||||
import { exportToExcel, exportToPDF } from "../utils/exportUtils";
|
import { exportToExcel, exportToPDF } from "../utils/exportUtils";
|
||||||
@@ -280,6 +254,7 @@ import { exportToExcel, exportToPDF } from "../utils/exportUtils";
|
|||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const companyStore = useCompanyStore();
|
const companyStore = useCompanyStore();
|
||||||
const invoicesStore = useInvoicesStore();
|
const invoicesStore = useInvoicesStore();
|
||||||
|
const periodStore = useAccountingPeriodStore();
|
||||||
|
|
||||||
// State
|
// State
|
||||||
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
|
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
|
||||||
@@ -287,8 +262,6 @@ const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
|
|||||||
const filters = ref({
|
const filters = ref({
|
||||||
type: "CLIENTI",
|
type: "CLIENTI",
|
||||||
paymentStatus: "neachitate", // Default to unpaid invoices
|
paymentStatus: "neachitate", // Default to unpaid invoices
|
||||||
dateFrom: null,
|
|
||||||
dateTo: null,
|
|
||||||
searchTerm: "",
|
searchTerm: "",
|
||||||
cont: "",
|
cont: "",
|
||||||
});
|
});
|
||||||
@@ -306,25 +279,8 @@ const totalSold = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const accountingPeriodText = computed(() => {
|
const accountingPeriodText = computed(() => {
|
||||||
const months = [
|
// Use the global period store
|
||||||
"Ianuarie",
|
return periodStore.selectedPeriod?.display_name || "";
|
||||||
"Februarie",
|
|
||||||
"Martie",
|
|
||||||
"Aprilie",
|
|
||||||
"Mai",
|
|
||||||
"Iunie",
|
|
||||||
"Iulie",
|
|
||||||
"August",
|
|
||||||
"Septembrie",
|
|
||||||
"Octombrie",
|
|
||||||
"Noiembrie",
|
|
||||||
"Decembrie",
|
|
||||||
];
|
|
||||||
const luna = invoicesStore.accountingPeriod.luna;
|
|
||||||
const an = invoicesStore.accountingPeriod.an;
|
|
||||||
if (!luna || !an) return "";
|
|
||||||
const monthName = months[luna - 1] || "";
|
|
||||||
return `${monthName} ${an}`;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Options
|
// Options
|
||||||
@@ -394,8 +350,6 @@ const clearFilters = async () => {
|
|||||||
filters.value = {
|
filters.value = {
|
||||||
type: "CLIENTI",
|
type: "CLIENTI",
|
||||||
paymentStatus: "neachitate",
|
paymentStatus: "neachitate",
|
||||||
dateFrom: null,
|
|
||||||
dateTo: null,
|
|
||||||
searchTerm: "",
|
searchTerm: "",
|
||||||
cont: "",
|
cont: "",
|
||||||
};
|
};
|
||||||
@@ -415,40 +369,27 @@ const refreshData = async () => {
|
|||||||
|
|
||||||
const loadInvoices = async () => {
|
const loadInvoices = async () => {
|
||||||
if (!companyStore.selectedCompany) return;
|
if (!companyStore.selectedCompany) return;
|
||||||
|
if (!periodStore.selectedPeriod) return; // Wait for period to be loaded
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Set filters in store FIRST
|
// Set filters in store FIRST
|
||||||
invoicesStore.setFilters(filters.value);
|
invoicesStore.setFilters(filters.value);
|
||||||
invoicesStore.setPagination(pagination.value);
|
invoicesStore.setPagination(pagination.value);
|
||||||
|
|
||||||
|
// Use luna/an from period store directly
|
||||||
|
const { luna, an } = periodStore.selectedPeriod;
|
||||||
|
|
||||||
const params = {
|
const params = {
|
||||||
partner_type: filters.value.type, // FIX: Add partner_type filter
|
partner_type: filters.value.type,
|
||||||
page: pagination.value.page,
|
page: pagination.value.page,
|
||||||
page_size: pagination.value.rows,
|
page_size: pagination.value.rows,
|
||||||
only_unpaid: filters.value.paymentStatus === "neachitate", // Use filter value
|
only_unpaid: filters.value.paymentStatus === "neachitate",
|
||||||
|
luna: luna,
|
||||||
|
an: an,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add optional filters (use LOCAL date, not UTC)
|
|
||||||
if (filters.value.dateFrom) {
|
|
||||||
const year = filters.value.dateFrom.getFullYear();
|
|
||||||
const month = String(filters.value.dateFrom.getMonth() + 1).padStart(
|
|
||||||
2,
|
|
||||||
"0",
|
|
||||||
);
|
|
||||||
const day = String(filters.value.dateFrom.getDate()).padStart(2, "0");
|
|
||||||
params.date_from = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
if (filters.value.dateTo) {
|
|
||||||
const year = filters.value.dateTo.getFullYear();
|
|
||||||
const month = String(filters.value.dateTo.getMonth() + 1).padStart(
|
|
||||||
2,
|
|
||||||
"0",
|
|
||||||
);
|
|
||||||
const day = String(filters.value.dateTo.getDate()).padStart(2, "0");
|
|
||||||
params.date_to = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
if (filters.value.searchTerm) {
|
if (filters.value.searchTerm) {
|
||||||
params.partner_name = filters.value.searchTerm; // FIX: Use partner_name not search
|
params.partner_name = filters.value.searchTerm;
|
||||||
}
|
}
|
||||||
if (filters.value.cont) {
|
if (filters.value.cont) {
|
||||||
params.cont = filters.value.cont;
|
params.cont = filters.value.cont;
|
||||||
@@ -484,37 +425,24 @@ const onSort = async (event) => {
|
|||||||
// Export methods - Fetch ALL data (not just current page)
|
// Export methods - Fetch ALL data (not just current page)
|
||||||
const fetchAllInvoicesData = async () => {
|
const fetchAllInvoicesData = async () => {
|
||||||
if (!companyStore.selectedCompany) return [];
|
if (!companyStore.selectedCompany) return [];
|
||||||
|
if (!periodStore.selectedPeriod) return [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Use luna/an from period store
|
||||||
|
const { luna, an } = periodStore.selectedPeriod;
|
||||||
|
|
||||||
const params = {
|
const params = {
|
||||||
company: companyStore.selectedCompany.id_firma,
|
company: companyStore.selectedCompany.id_firma,
|
||||||
partner_type: filters.value.type, // FIX: Correctly pass partner_type
|
partner_type: filters.value.type,
|
||||||
page: 1,
|
page: 1,
|
||||||
page_size: 999999, // Get all data
|
page_size: 999999, // Get all data
|
||||||
only_unpaid: filters.value.paymentStatus === "neachitate", // Use filter value for export
|
only_unpaid: filters.value.paymentStatus === "neachitate",
|
||||||
|
luna: luna,
|
||||||
|
an: an,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add optional filters (use LOCAL date, not UTC)
|
|
||||||
if (filters.value.dateFrom) {
|
|
||||||
const year = filters.value.dateFrom.getFullYear();
|
|
||||||
const month = String(filters.value.dateFrom.getMonth() + 1).padStart(
|
|
||||||
2,
|
|
||||||
"0",
|
|
||||||
);
|
|
||||||
const day = String(filters.value.dateFrom.getDate()).padStart(2, "0");
|
|
||||||
params.date_from = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
if (filters.value.dateTo) {
|
|
||||||
const year = filters.value.dateTo.getFullYear();
|
|
||||||
const month = String(filters.value.dateTo.getMonth() + 1).padStart(
|
|
||||||
2,
|
|
||||||
"0",
|
|
||||||
);
|
|
||||||
const day = String(filters.value.dateTo.getDate()).padStart(2, "0");
|
|
||||||
params.date_to = `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
if (filters.value.searchTerm) {
|
if (filters.value.searchTerm) {
|
||||||
params.partner_name = filters.value.searchTerm; // FIX: Use partner_name not search
|
params.partner_name = filters.value.searchTerm;
|
||||||
}
|
}
|
||||||
if (filters.value.cont) {
|
if (filters.value.cont) {
|
||||||
params.cont = filters.value.cont;
|
params.cont = filters.value.cont;
|
||||||
@@ -710,22 +638,29 @@ onMounted(async () => {
|
|||||||
if (!companyStore.hasCompanies) {
|
if (!companyStore.hasCompanies) {
|
||||||
await companyStore.loadCompanies();
|
await companyStore.loadCompanies();
|
||||||
}
|
}
|
||||||
|
// Don't load here - let period watch handle it with immediate: true
|
||||||
// Load invoices if company is selected
|
|
||||||
if (companyStore.selectedCompany) {
|
|
||||||
await loadInvoices();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Watch for company changes
|
// Watch for company changes
|
||||||
watch(
|
watch(
|
||||||
() => companyStore.selectedCompany,
|
() => companyStore.selectedCompany,
|
||||||
async (newCompany) => {
|
async (newCompany) => {
|
||||||
if (newCompany) {
|
if (newCompany && periodStore.selectedPeriod) {
|
||||||
await loadInvoices();
|
await loadInvoices();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Watch for period changes - reload data when period changes
|
||||||
|
watch(
|
||||||
|
() => periodStore.selectedPeriod,
|
||||||
|
async (newPeriod) => {
|
||||||
|
if (newPeriod && companyStore.selectedCompany) {
|
||||||
|
await loadInvoices();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -238,11 +238,13 @@ import { ref, computed, onMounted, watch } from "vue";
|
|||||||
import { useToast } from "primevue/usetoast";
|
import { useToast } from "primevue/usetoast";
|
||||||
import { useCompanyStore } from "../stores/companies";
|
import { useCompanyStore } from "../stores/companies";
|
||||||
import { useTrialBalanceStore } from "../stores/trialBalance";
|
import { useTrialBalanceStore } from "../stores/trialBalance";
|
||||||
|
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
|
||||||
import { exportToExcel, exportToPDF } from "../utils/exportUtils";
|
import { exportToExcel, exportToPDF } from "../utils/exportUtils";
|
||||||
|
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const companyStore = useCompanyStore();
|
const companyStore = useCompanyStore();
|
||||||
const trialBalanceStore = useTrialBalanceStore();
|
const trialBalanceStore = useTrialBalanceStore();
|
||||||
|
const periodStore = useAccountingPeriodStore();
|
||||||
|
|
||||||
// State
|
// State
|
||||||
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
|
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
|
||||||
@@ -254,22 +256,8 @@ const localFilters = ref({
|
|||||||
|
|
||||||
// Computed
|
// Computed
|
||||||
const currentPeriodText = computed(() => {
|
const currentPeriodText = computed(() => {
|
||||||
const months = [
|
// Use the global period store
|
||||||
"Ianuarie",
|
return periodStore.selectedPeriod?.display_name || "";
|
||||||
"Februarie",
|
|
||||||
"Martie",
|
|
||||||
"Aprilie",
|
|
||||||
"Mai",
|
|
||||||
"Iunie",
|
|
||||||
"Iulie",
|
|
||||||
"August",
|
|
||||||
"Septembrie",
|
|
||||||
"Octombrie",
|
|
||||||
"Noiembrie",
|
|
||||||
"Decembrie",
|
|
||||||
];
|
|
||||||
const monthName = months[trialBalanceStore.filters.luna - 1] || "";
|
|
||||||
return `${monthName} ${trialBalanceStore.filters.an}`;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
@@ -599,6 +587,14 @@ onMounted(async () => {
|
|||||||
await companyStore.loadCompanies();
|
await companyStore.loadCompanies();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FIX: Sync period from global periodStore BEFORE loading data
|
||||||
|
// This ensures Trial Balance shows the correct period when navigating
|
||||||
|
// from other views (e.g., Invoices with November selected)
|
||||||
|
if (periodStore.selectedPeriod) {
|
||||||
|
trialBalanceStore.filters.luna = periodStore.selectedPeriod.luna;
|
||||||
|
trialBalanceStore.filters.an = periodStore.selectedPeriod.an;
|
||||||
|
}
|
||||||
|
|
||||||
// Load trial balance if company is selected
|
// Load trial balance if company is selected
|
||||||
if (companyStore.selectedCompany) {
|
if (companyStore.selectedCompany) {
|
||||||
await loadTrialBalance();
|
await loadTrialBalance();
|
||||||
@@ -614,6 +610,20 @@ watch(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Watch for period changes - sync luna/an with trial balance store
|
||||||
|
watch(
|
||||||
|
() => periodStore.selectedPeriod,
|
||||||
|
async (newPeriod) => {
|
||||||
|
if (newPeriod && companyStore.selectedCompany) {
|
||||||
|
await trialBalanceStore.changePeriod(
|
||||||
|
newPeriod.luna,
|
||||||
|
newPeriod.an,
|
||||||
|
companyStore.selectedCompany.id_firma
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
Reference in New Issue
Block a user