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:
2025-12-09 12:14:35 +02:00
parent 3c0ab51f87
commit c75e896a84
22 changed files with 1162 additions and 425 deletions

View File

@@ -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>

View File

@@ -499,6 +499,7 @@
import { ref, computed, watch, onMounted } from "vue";
import { useDashboardStore } from "../../../stores/dashboard";
import { useCompanyStore } from "../../../stores/companies";
import { useAccountingPeriodStore } from "../../../stores/accountingPeriod";
import { useToast } from "primevue/usetoast";
import Paginator from "primevue/paginator";
import * as XLSX from "xlsx";
@@ -519,6 +520,7 @@ const emit = defineEmits(["periodChanged"]);
// Stores
const dashboardStore = useDashboardStore();
const companyStore = useCompanyStore();
const periodStore = useAccountingPeriodStore();
const toast = useToast();
// State - Maturity Analysis
@@ -819,10 +821,15 @@ const loadMaturityData = async () => {
isLoading.value = true;
error.value = null;
const luna = periodStore.selectedPeriod?.luna || null;
const an = periodStore.selectedPeriod?.an || null;
try {
const response = await dashboardStore.loadMaturityData(
props.companyId,
selectedPeriod.value,
luna,
an,
);
if (response && response.success) {
@@ -854,12 +861,17 @@ const loadDetailedData = async () => {
// Calculate page number from firstRow
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(
selectedType.value,
companyStore.selectedCompany.id_firma,
page,
rowsPerPage.value,
searchTerm.value,
luna,
an,
);
detailedData.value = response.data;
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([firstRow, rowsPerPage], () => {
if (isDetailsExpanded.value && detailedData.value.length > 0) {

View File

@@ -19,8 +19,12 @@
</router-link>
</div>
<!-- Right side: Company + User -->
<!-- Right side: Period + Company + User -->
<div class="header-actions">
<PeriodSelectorMini
v-if="selectedCompany"
@period-changed="onPeriodChanged"
/>
<CompanySelectorMini
v-model="selectedCompany"
@company-changed="onCompanyChanged"
@@ -75,6 +79,7 @@
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import CompanySelectorMini from "../dashboard/CompanySelectorMini.vue";
import PeriodSelectorMini from "../dashboard/PeriodSelectorMini.vue";
import { useCompanyStore } from "../../stores/companies";
import { useAuthStore } from "../../stores/auth";
@@ -82,6 +87,7 @@ export default {
name: "DashboardHeader",
components: {
CompanySelectorMini,
PeriodSelectorMini,
},
props: {
menuOpen: {
@@ -89,7 +95,7 @@ export default {
default: false,
},
},
emits: ["menu-toggle", "company-changed"],
emits: ["menu-toggle", "company-changed", "period-changed"],
setup(props, { emit }) {
const router = useRouter();
const companiesStore = useCompanyStore();
@@ -120,6 +126,10 @@ export default {
emit("company-changed", company);
};
const onPeriodChanged = (period) => {
emit("period-changed", period);
};
const navigateToTelegram = async () => {
try {
closeUserMenu();
@@ -147,6 +157,7 @@ export default {
toggleUserMenu,
closeUserMenu,
onCompanyChanged,
onPeriodChanged,
navigateToTelegram,
handleLogout,
};

View 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,
};
});

View File

@@ -21,14 +21,16 @@ export const useDashboardStore = defineStore("dashboard", () => {
// Cache pentru date
const dataCache = new Map();
const loadDashboardSummary = async (companyId) => {
const loadDashboardSummary = async (companyId, luna = null, an = null) => {
isLoading.value = true;
error.value = null;
try {
const response = await apiService.get("/dashboard/summary", {
params: { company: companyId },
});
const 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;
return { success: true };
} catch (err) {
@@ -44,21 +46,25 @@ export const useDashboardStore = defineStore("dashboard", () => {
companyId,
period = "12m",
chartType = "line",
luna = null,
an = null,
) => {
isLoading.value = true;
error.value = null;
try {
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", {
params: {
company: companyId,
period: period,
},
});
const params = {
company: companyId,
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
if (!response.data) {
@@ -188,20 +194,24 @@ export const useDashboardStore = defineStore("dashboard", () => {
page = 1,
pageSize = 25,
search = "",
luna = null,
an = null,
) => {
isLoading.value = true;
error.value = null;
try {
const response = await apiService.get("/dashboard/detailed-data", {
params: {
company: companyId,
data_type: dataType,
page: page,
page_size: pageSize,
search: search,
},
});
const params = {
company: companyId,
data_type: dataType,
page: page,
page_size: pageSize,
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
detailedDataTotal.value = response.data.total || 0;
@@ -417,8 +427,8 @@ export const useDashboardStore = defineStore("dashboard", () => {
}
};
const loadMaturityData = async (companyId, period = "7d") => {
const cacheKey = `maturity-${companyId}-${period}`;
const loadMaturityData = async (companyId, period = "7d", luna = null, an = null) => {
const cacheKey = `maturity-${companyId}-${period}-${luna}-${an}`;
if (dataCache.has(cacheKey)) {
maturityData.value[period] = dataCache.get(cacheKey);
@@ -426,9 +436,11 @@ export const useDashboardStore = defineStore("dashboard", () => {
}
try {
const response = await apiService.get("/dashboard/maturity", {
params: { company: companyId, period },
});
const 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;
dataCache.set(cacheKey, response.data);

View File

@@ -68,30 +68,6 @@
/>
</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-group">
<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 { useTreasuryStore } from "../stores/treasury";
import { useCompanyStore } from "../stores/companies";
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
import { format } from "date-fns";
import { exportToExcel, exportBankCashRegisterPDF } from "../utils/exportUtils";
const toast = useToast();
const treasuryStore = useTreasuryStore();
const companyStore = useCompanyStore();
const periodStore = useAccountingPeriodStore();
// State for company selection
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
@@ -307,8 +285,6 @@ const registerTypeOptions = [
const filters = ref({
registerType: "BANCA_LEI", // Default: Registrul de Banca Lei
dateFrom: null,
dateTo: null,
partnerName: "",
bankAccount: null, // Filter for specific bank/cash account
});
@@ -400,25 +376,8 @@ const contColumnHeader = computed(() => {
// Accounting period text for PDF export
const accountingPeriodText = computed(() => {
const months = [
"Ianuarie",
"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}`;
// Use the global period store
return periodStore.selectedPeriod?.display_name || "";
});
// Helper to remove diacritics from text
@@ -504,8 +463,6 @@ const onPage = async (event) => {
const resetFilters = async () => {
filters.value = {
registerType: "BANCA_LEI", // Reset la default: Registrul de Banca Lei
dateFrom: null,
dateTo: null,
partnerName: "",
bankAccount: null, // Reset bank account filter
};
@@ -559,12 +516,18 @@ const refreshData = async () => {
// Fetch ALL data for export (not just current page)
const fetchAllData = async () => {
if (!companyStore.selectedCompany) return [];
if (!periodStore.selectedPeriod) return [];
try {
// Get luna/an from period store
const { luna, an } = periodStore.selectedPeriod;
const params = {
company: companyStore.selectedCompany.id_firma,
page: 1,
page_size: 999999, // Get all data
luna: luna,
an: an,
};
// Add register_type filter
@@ -572,25 +535,6 @@ const fetchAllData = async () => {
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) {
params.partner_name = filters.value.partnerName;
}
@@ -756,33 +700,22 @@ const exportPDF = async () => {
const loadData = async () => {
if (!companyStore.selectedCompany) return;
if (!periodStore.selectedPeriod) return; // Wait for period to be loaded
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 = {
partner_name: filters.value.partnerName || undefined,
register_type: filters.value.registerType || 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(
companyStore.selectedCompany.id_firma,
filterParams,
@@ -795,23 +728,34 @@ onMounted(async () => {
await companyStore.loadCompanies();
}
// Load data if company is selected
// Load bank accounts for initial register type if company is selected
if (companyStore.selectedCompany) {
// Load bank accounts for initial register type
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(
() => companyStore.selectedCompany,
async (newCompany) => {
if (newCompany) {
if (newCompany && periodStore.selectedPeriod) {
await loadBankAccounts();
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>
<style scoped>

View File

@@ -96,6 +96,7 @@ import FurnizoriBalanceCard from "../components/dashboard/cards/FurnizoriBalance
import TreasuryDualCard from "../components/dashboard/cards/TreasuryDualCard.vue";
import { useCompanyStore } from "../stores/companies";
import { useDashboardStore } from "../stores/dashboard";
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
import { apiService } from "../services/api";
import {
exportToExcel,
@@ -106,6 +107,7 @@ import {
const toast = useToast();
const companyStore = useCompanyStore();
const dashboardStore = useDashboardStore();
const periodStore = useAccountingPeriodStore();
// State
const filteredCompanies = ref([]);
@@ -423,19 +425,22 @@ const bancaPreviousSparkline = computed(() => {
// Detectare mobile
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(() => {
if (!dashboardStore.currentPeriod) {
return "Se încarcă...";
// Prioritate: period selector > dashboard current period > loading
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ă
const date = new Date(year, month - 1, 1);
// Formatează luna în română: "Octombrie 2025"
return date.toLocaleDateString("ro-RO", { month: "long", year: "numeric" });
return "Se încarcă...";
});
// Methods
@@ -474,15 +479,21 @@ const loadTrendData = async () => {
return;
}
const luna = periodStore.selectedPeriod?.luna || null;
const an = periodStore.selectedPeriod?.an || null;
console.log(
"Loading trend data for company:",
companyStore.selectedCompany.id_firma,
"luna:", luna, "an:", an,
);
const result = await dashboardStore.loadTrendData(
companyStore.selectedCompany.id_firma,
selectedPeriod.value,
selectedChartType.value,
luna,
an,
);
if (result.success) {
@@ -688,13 +699,18 @@ const handleCompanySelect = async (event) => {
};
// Fixed: Changed company_id to company parameter
// Updated: Added luna/an from period selector
const loadMonthlyFlows = async () => {
if (!companyStore.selectedCompany) return;
try {
const response = await apiService.get("/dashboard/monthly-flows", {
params: { company: companyStore.selectedCompany.id_firma },
});
const 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;
monthlyOutflows.value = response.data.outflows || 0;
} catch (error) {
@@ -706,9 +722,13 @@ const loadTreasuryBreakdown = async () => {
if (!companyStore.selectedCompany) return;
try {
const response = await apiService.get("/dashboard/treasury-breakdown", {
params: { company: companyStore.selectedCompany.id_firma },
});
const 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;
} catch (error) {
console.error("Failed to load treasury breakdown:", error);
@@ -719,9 +739,13 @@ const loadNetBalanceBreakdown = async () => {
if (!companyStore.selectedCompany) return;
try {
const response = await apiService.get("/dashboard/net-balance-breakdown", {
params: { company: companyStore.selectedCompany.id_firma },
});
const 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
netBalanceData.value = {
@@ -755,10 +779,15 @@ const loadDashboardData = async () => {
if (!companyStore.selectedCompany) return;
isLoading.value = true;
const luna = periodStore.selectedPeriod?.luna || null;
const an = periodStore.selectedPeriod?.an || null;
try {
await Promise.all([
dashboardStore.loadDashboardSummary(
companyStore.selectedCompany.id_firma,
luna,
an,
),
dashboardStore.loadCurrentPeriod(companyStore.selectedCompany.id_firma),
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
onMounted(async () => {
// Load companies first

View File

@@ -69,33 +69,6 @@
</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 -->
<div class="form-col">
<div class="form-group">
@@ -273,6 +246,7 @@ import { ref, computed, onMounted, watch } from "vue";
import { useToast } from "primevue/usetoast";
import { useCompanyStore } from "../stores/companies";
import { useInvoicesStore } from "../stores/invoices";
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
import { format } from "date-fns";
import { ro } from "date-fns/locale";
import { exportToExcel, exportToPDF } from "../utils/exportUtils";
@@ -280,6 +254,7 @@ import { exportToExcel, exportToPDF } from "../utils/exportUtils";
const toast = useToast();
const companyStore = useCompanyStore();
const invoicesStore = useInvoicesStore();
const periodStore = useAccountingPeriodStore();
// State
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
@@ -287,8 +262,6 @@ const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
const filters = ref({
type: "CLIENTI",
paymentStatus: "neachitate", // Default to unpaid invoices
dateFrom: null,
dateTo: null,
searchTerm: "",
cont: "",
});
@@ -306,25 +279,8 @@ const totalSold = computed(() => {
});
const accountingPeriodText = computed(() => {
const months = [
"Ianuarie",
"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}`;
// Use the global period store
return periodStore.selectedPeriod?.display_name || "";
});
// Options
@@ -394,8 +350,6 @@ const clearFilters = async () => {
filters.value = {
type: "CLIENTI",
paymentStatus: "neachitate",
dateFrom: null,
dateTo: null,
searchTerm: "",
cont: "",
};
@@ -415,40 +369,27 @@ const refreshData = async () => {
const loadInvoices = async () => {
if (!companyStore.selectedCompany) return;
if (!periodStore.selectedPeriod) return; // Wait for period to be loaded
try {
// Set filters in store FIRST
invoicesStore.setFilters(filters.value);
invoicesStore.setPagination(pagination.value);
// Use luna/an from period store directly
const { luna, an } = periodStore.selectedPeriod;
const params = {
partner_type: filters.value.type, // FIX: Add partner_type filter
partner_type: filters.value.type,
page: pagination.value.page,
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) {
params.partner_name = filters.value.searchTerm; // FIX: Use partner_name not search
params.partner_name = filters.value.searchTerm;
}
if (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)
const fetchAllInvoicesData = async () => {
if (!companyStore.selectedCompany) return [];
if (!periodStore.selectedPeriod) return [];
try {
// Use luna/an from period store
const { luna, an } = periodStore.selectedPeriod;
const params = {
company: companyStore.selectedCompany.id_firma,
partner_type: filters.value.type, // FIX: Correctly pass partner_type
partner_type: filters.value.type,
page: 1,
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) {
params.partner_name = filters.value.searchTerm; // FIX: Use partner_name not search
params.partner_name = filters.value.searchTerm;
}
if (filters.value.cont) {
params.cont = filters.value.cont;
@@ -710,22 +638,29 @@ onMounted(async () => {
if (!companyStore.hasCompanies) {
await companyStore.loadCompanies();
}
// Load invoices if company is selected
if (companyStore.selectedCompany) {
await loadInvoices();
}
// Don't load here - let period watch handle it with immediate: true
});
// Watch for company changes
watch(
() => companyStore.selectedCompany,
async (newCompany) => {
if (newCompany) {
if (newCompany && periodStore.selectedPeriod) {
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>
<style scoped>

View File

@@ -238,11 +238,13 @@ import { ref, computed, onMounted, watch } from "vue";
import { useToast } from "primevue/usetoast";
import { useCompanyStore } from "../stores/companies";
import { useTrialBalanceStore } from "../stores/trialBalance";
import { useAccountingPeriodStore } from "../stores/accountingPeriod";
import { exportToExcel, exportToPDF } from "../utils/exportUtils";
const toast = useToast();
const companyStore = useCompanyStore();
const trialBalanceStore = useTrialBalanceStore();
const periodStore = useAccountingPeriodStore();
// State
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);
@@ -254,22 +256,8 @@ const localFilters = ref({
// Computed
const currentPeriodText = computed(() => {
const months = [
"Ianuarie",
"Februarie",
"Martie",
"Aprilie",
"Mai",
"Iunie",
"Iulie",
"August",
"Septembrie",
"Octombrie",
"Noiembrie",
"Decembrie",
];
const monthName = months[trialBalanceStore.filters.luna - 1] || "";
return `${monthName} ${trialBalanceStore.filters.an}`;
// Use the global period store
return periodStore.selectedPeriod?.display_name || "";
});
// Methods
@@ -599,6 +587,14 @@ onMounted(async () => {
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
if (companyStore.selectedCompany) {
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>
<style scoped>