feat: Add shared components, refactor stores, improve data-entry workflow

Shared Components:
- Add CompanySelector.vue and PeriodSelector.vue components
- Add AppHeader.vue and SlideMenu.vue layout components
- Add shared stores factories (companies.js, accountingPeriod.js)
- Add shared routes factories (companies.py, calendar.py)
- Add shared models (company.py, calendar.py)
- Add shared layout styles (header.css, navigation.css)

Data Entry App:
- Update CLAUDE.md with prod/test server documentation
- Improve nomenclature sync service with better error handling
- Update receipts router and CRUD operations
- Add company/period stores using shared factories
- Update App.vue layout with shared components
- Fix OCRUploadZone file handling

Reports App:
- Refactor stores to use shared factories
- Update App.vue to use shared layout components

Infrastructure:
- Replace start-data-entry.sh with separate dev/test scripts
- Add .claude/rules for authentication, backend patterns, etc.
- Add implementation plan for OCR receipt improvements
- Clean up old documentation files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-15 15:00:45 +02:00
parent c5fde510a8
commit 1a6e9b17d2
47 changed files with 4079 additions and 2595 deletions

View File

@@ -0,0 +1,555 @@
<template>
<div :class="selectorClass" ref="dropdownContainer">
<div class="company-dropdown" ref="dropdown">
<button
class="company-trigger"
@click="toggleDropdown"
:aria-expanded="dropdownOpen"
aria-label="Selectare firma"
title="Alt+Q pentru selectare rapida"
>
<div class="company-info">
<span class="company-name">{{ selectedCompanyName }}</span>
<span v-if="showFiscalCode" class="company-code">{{ selectedCompanyCode }}</span>
</div>
<i
class="pi pi-chevron-down"
:class="{ 'rotate-180': dropdownOpen }"
></i>
</button>
<div
v-show="dropdownOpen"
class="company-dropdown-panel"
:class="{ 'panel-open': dropdownOpen }"
>
<div class="dropdown-search">
<div class="search-wrapper">
<i class="pi pi-search search-icon"></i>
<input
ref="searchInput"
type="text"
v-model="searchQuery"
placeholder="Cauta firma..."
class="search-input"
@keydown="handleKeyDown"
/>
</div>
</div>
<div class="company-list">
<div
v-for="(company, index) in filteredCompanies"
:key="company.id_firma"
class="company-item"
:class="{
active: company.id_firma === selectedCompany?.id_firma,
'keyboard-highlighted': isHighlighted(index),
}"
@click="selectCompany(company)"
@mouseenter="highlightedIndex = index"
>
<div class="company-details">
<div class="company-main-name">{{ company.name }}</div>
<div v-if="showFiscalCode" class="company-sub-info">
<span class="company-cui">CUI: {{ company.fiscal_code || '-' }}</span>
</div>
</div>
<i
v-if="company.id_firma === selectedCompany?.id_firma"
class="pi pi-check company-selected-icon"
></i>
</div>
</div>
<div v-if="filteredCompanies.length === 0" class="no-results">
<i class="pi pi-info-circle"></i>
<span>Nu s-au gasit firme</span>
</div>
</div>
</div>
</div>
</template>
<script>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from "vue";
export default {
name: "CompanySelector",
props: {
// The companies store instance
companiesStore: {
type: Object,
required: true,
},
// Optional v-model binding
modelValue: {
type: Object,
default: null,
},
// Show fiscal code in display
showFiscalCode: {
type: Boolean,
default: true,
},
// Variant: 'default' (white background) or 'header' (transparent for dark headers)
variant: {
type: String,
default: "default",
validator: (value) => ['default', 'header'].includes(value),
},
},
emits: ["update:modelValue", "company-changed"],
setup(props, { emit }) {
const dropdown = ref(null);
const dropdownContainer = ref(null);
const searchInput = ref(null);
const dropdownOpen = ref(false);
const searchQuery = ref("");
const highlightedIndex = ref(-1);
const selectedCompany = computed({
get: () => props.modelValue || props.companiesStore.selectedCompany,
set: (value) => {
emit("update:modelValue", value);
props.companiesStore.setSelectedCompany(value);
},
});
const selectedCompanyName = computed(() => {
return selectedCompany.value?.name || "Selectare firma";
});
const selectedCompanyCode = computed(() => {
return selectedCompany.value?.fiscal_code
? `CUI: ${selectedCompany.value.fiscal_code}`
: "";
});
const selectorClass = computed(() => ({
'company-selector': true,
'company-selector--header': props.variant === 'header'
}));
const filteredCompanies = computed(() => {
const companies = props.companiesStore.companies || [];
if (!searchQuery.value || searchQuery.value.trim() === "") {
return companies;
}
const query = searchQuery.value.toLowerCase().trim();
return companies.filter(
(company) =>
company.name?.toLowerCase().includes(query) ||
company.fiscal_code?.toLowerCase().includes(query)
);
});
const toggleDropdown = async () => {
dropdownOpen.value = !dropdownOpen.value;
if (dropdownOpen.value) {
searchQuery.value = "";
highlightedIndex.value = -1;
await nextTick();
searchInput.value?.focus();
}
};
const closeDropdown = () => {
dropdownOpen.value = false;
searchQuery.value = "";
};
const selectCompany = (company) => {
selectedCompany.value = company;
emit("company-changed", company);
closeDropdown();
};
const scrollToHighlighted = () => {
nextTick(() => {
const highlightedElement = document.querySelector(
".company-item.keyboard-highlighted"
);
if (highlightedElement) {
highlightedElement.scrollIntoView({
block: "nearest",
behavior: "smooth",
});
}
});
};
const handleKeyDown = (event) => {
if (!dropdownOpen.value || filteredCompanies.value.length === 0) return;
switch (event.key) {
case "ArrowDown":
event.preventDefault();
highlightedIndex.value =
(highlightedIndex.value + 1) % filteredCompanies.value.length;
scrollToHighlighted();
break;
case "ArrowUp":
event.preventDefault();
if (highlightedIndex.value <= 0) {
highlightedIndex.value = filteredCompanies.value.length - 1;
} else {
highlightedIndex.value--;
}
scrollToHighlighted();
break;
case "Enter":
event.preventDefault();
if (
highlightedIndex.value >= 0 &&
highlightedIndex.value < filteredCompanies.value.length
) {
selectCompany(filteredCompanies.value[highlightedIndex.value]);
}
break;
case "Escape":
closeDropdown();
break;
}
};
const isHighlighted = (index) => {
return index === highlightedIndex.value;
};
const openWithShortcut = async () => {
if (dropdownContainer.value) {
dropdownContainer.value.scrollIntoView({
behavior: "smooth",
block: "start",
});
}
await new Promise((resolve) => setTimeout(resolve, 300));
if (!dropdownOpen.value) {
dropdownOpen.value = true;
highlightedIndex.value = -1;
searchQuery.value = "";
await nextTick();
searchInput.value?.focus();
} else {
searchInput.value?.focus();
}
};
const handleGlobalKeyDown = (event) => {
if (event.altKey && event.key === "q") {
event.preventDefault();
openWithShortcut();
}
};
const handleClickOutside = (event) => {
if (dropdown.value && !dropdown.value.contains(event.target)) {
closeDropdown();
}
};
watch(searchQuery, () => {
highlightedIndex.value = -1;
});
onMounted(() => {
document.addEventListener("click", handleClickOutside);
document.addEventListener("keydown", handleGlobalKeyDown);
// Load companies if not already loaded
if (props.companiesStore.companies.length === 0) {
props.companiesStore.loadCompanies();
}
});
onUnmounted(() => {
document.removeEventListener("click", handleClickOutside);
document.removeEventListener("keydown", handleGlobalKeyDown);
});
return {
dropdown,
dropdownContainer,
searchInput,
dropdownOpen,
searchQuery,
highlightedIndex,
selectedCompany,
selectedCompanyName,
selectedCompanyCode,
selectorClass,
filteredCompanies,
toggleDropdown,
closeDropdown,
selectCompany,
handleKeyDown,
isHighlighted,
};
},
};
</script>
<style scoped>
.company-selector {
position: relative;
max-width: 450px;
}
.company-dropdown {
position: relative;
}
.company-trigger {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-sm, 8px);
padding: var(--space-sm, 8px) var(--space-md, 12px);
background: var(--color-bg, #fff);
border: 1px solid var(--color-border, #e5e7eb);
border-radius: var(--radius-md, 6px);
cursor: pointer;
transition: all 0.15s ease;
width: 100%;
text-align: left;
min-width: 300px;
}
.company-trigger:hover {
border-color: var(--color-primary, #2563eb);
background: var(--color-bg-secondary, #f9fafb);
}
.company-info {
flex: 1;
min-width: 0;
}
.company-name {
display: block;
font-size: var(--text-sm, 14px);
font-weight: 500;
color: var(--color-text, #111827);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.company-code {
display: block;
font-size: var(--text-xs, 12px);
color: var(--color-text-secondary, #6b7280);
margin-top: 2px;
}
.pi-chevron-down {
transition: transform 0.15s ease;
color: var(--color-text-secondary, #6b7280);
font-size: var(--text-xs, 12px);
}
.rotate-180 {
transform: rotate(180deg);
}
.company-dropdown-panel {
position: absolute;
top: calc(100% + 4px);
left: 0;
right: 0;
background: var(--color-bg, #fff);
border: 1px solid var(--color-border, #e5e7eb);
border-radius: var(--radius-md, 6px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
z-index: 1000;
max-height: 300px;
overflow: hidden;
opacity: 0;
transform: translateY(-10px);
transition: all 0.15s ease;
}
.panel-open {
opacity: 1;
transform: translateY(0);
}
.dropdown-search {
padding: var(--space-sm, 8px);
border-bottom: 1px solid var(--color-border, #e5e7eb);
}
.search-wrapper {
position: relative;
}
.search-icon {
position: absolute;
left: var(--space-sm, 8px);
top: 50%;
transform: translateY(-50%);
color: var(--color-text-secondary, #6b7280);
font-size: var(--text-sm, 14px);
pointer-events: none;
}
.search-input {
width: 100%;
padding: var(--space-sm, 8px) var(--space-sm, 8px) var(--space-sm, 8px) var(--space-xl, 32px);
border: 1px solid var(--color-border, #e5e7eb);
border-radius: var(--radius-sm, 4px);
font-size: var(--text-sm, 14px);
background: var(--color-bg, #fff);
color: var(--color-text, #111827);
transition: border-color 0.15s ease;
}
.search-input:focus {
outline: none;
border-color: var(--color-primary, #2563eb);
}
.company-list {
max-height: 200px;
overflow-y: auto;
}
.company-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--space-md, 12px);
cursor: pointer;
transition: background-color 0.15s ease;
border-bottom: 1px solid var(--color-border-light, #f3f4f6);
}
.company-item:last-child {
border-bottom: none;
}
.company-item:hover {
background: var(--color-bg-secondary, #f9fafb);
}
.company-item.active {
background: var(--color-primary, #2563eb);
color: #fff;
}
.company-item.keyboard-highlighted {
background: var(--color-bg-secondary, #f9fafb);
outline: 2px solid var(--color-primary, #2563eb);
outline-offset: -2px;
}
.company-item.active.keyboard-highlighted {
outline: 2px solid rgba(255, 255, 255, 0.5);
}
.company-details {
flex: 1;
min-width: 0;
}
.company-main-name {
font-size: var(--text-sm, 14px);
font-weight: 500;
color: inherit;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 2px;
}
.company-sub-info {
display: flex;
align-items: center;
gap: var(--space-xs, 4px);
font-size: var(--text-xs, 12px);
opacity: 0.8;
}
.company-selected-icon {
color: inherit;
font-size: var(--text-sm, 14px);
}
.no-results {
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-sm, 8px);
padding: var(--space-xl, 24px);
color: var(--color-text-secondary, #6b7280);
font-size: var(--text-sm, 14px);
}
/* Mobile adjustments */
@media (max-width: 768px) {
.company-selector {
max-width: 200px;
width: auto;
}
.company-trigger {
min-width: auto;
max-width: 200px;
padding: var(--space-xs, 4px) var(--space-sm, 8px);
}
.company-info {
max-width: 140px;
}
.company-name {
font-size: var(--text-xs, 12px);
max-width: 140px;
}
.company-code {
font-size: 10px;
}
.company-dropdown-panel {
position: fixed;
left: 8px;
right: 8px;
top: 60px;
width: auto;
max-height: 70vh;
}
}
/* Header variant - transparent background, white text for dark headers */
.company-selector--header .company-trigger {
background: transparent;
border-color: rgba(255, 255, 255, 0.3);
}
.company-selector--header .company-trigger:hover {
background: rgba(255, 255, 255, 0.1);
border-color: rgba(255, 255, 255, 0.5);
}
.company-selector--header .company-name {
color: white;
}
.company-selector--header .company-code {
color: rgba(255, 255, 255, 0.8);
}
.company-selector--header .pi-chevron-down {
color: rgba(255, 255, 255, 0.8);
}
/* Dropdown panel keeps default styling (white background) */
</style>

View File

@@ -0,0 +1,441 @@
<template>
<div :class="selectorClass" ref="dropdownContainer">
<div class="period-dropdown" ref="dropdown">
<button
class="period-trigger"
@click="toggleDropdown"
:disabled="!hasSelectedCompany"
:aria-expanded="dropdownOpen"
aria-label="Selectare perioada contabila"
>
<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 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="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";
export default {
name: "PeriodSelector",
props: {
// The accounting period store instance
periodStore: {
type: Object,
required: true,
},
// The company store instance (to check if company is selected)
companiesStore: {
type: Object,
required: true,
},
// Variant: 'default' (white background) or 'header' (transparent for dark headers)
variant: {
type: String,
default: "default",
validator: (value) => ['default', 'header'].includes(value),
},
},
emits: ["period-changed"],
setup(props, { emit }) {
const dropdown = ref(null);
const dropdownContainer = ref(null);
const dropdownOpen = ref(false);
const highlightedIndex = ref(-1);
const hasSelectedCompany = computed(() => {
return !!props.companiesStore.selectedCompany;
});
const periods = computed(() => {
return props.periodStore.periods || [];
});
const selectedPeriodDisplay = computed(() => {
return props.periodStore.selectedPeriod?.display_name || "Selectare perioada";
});
const selectorClass = computed(() => ({
'period-selector': true,
'period-selector--header': props.variant === 'header'
}));
const isSelected = (period) => {
if (!props.periodStore.selectedPeriod) return false;
return (
period.an === props.periodStore.selectedPeriod.an &&
period.luna === props.periodStore.selectedPeriod.luna
);
};
const isHighlighted = (index) => {
return index === highlightedIndex.value;
};
const toggleDropdown = async () => {
if (!hasSelectedCompany.value) return;
dropdownOpen.value = !dropdownOpen.value;
if (dropdownOpen.value) {
highlightedIndex.value = -1;
}
};
const closeDropdown = () => {
dropdownOpen.value = false;
};
const selectPeriod = (period) => {
props.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 || periods.value.length === 0) return;
switch (event.key) {
case "ArrowDown":
event.preventDefault();
highlightedIndex.value =
(highlightedIndex.value + 1) % periods.value.length;
scrollToHighlighted();
break;
case "ArrowUp":
event.preventDefault();
if (highlightedIndex.value <= 0) {
highlightedIndex.value = periods.value.length - 1;
} else {
highlightedIndex.value--;
}
scrollToHighlighted();
break;
case "Enter":
event.preventDefault();
if (
highlightedIndex.value >= 0 &&
highlightedIndex.value < periods.value.length
) {
selectPeriod(periods.value[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
watch(
() => props.companiesStore.selectedCompany,
async (newCompany) => {
if (newCompany) {
await props.periodStore.loadPeriods(newCompany.id_firma);
} else {
props.periodStore.reset();
}
},
{ immediate: true }
);
onMounted(() => {
document.addEventListener("click", handleClickOutside);
document.addEventListener("keydown", handleKeyDown);
});
onUnmounted(() => {
document.removeEventListener("click", handleClickOutside);
document.removeEventListener("keydown", handleKeyDown);
});
return {
dropdown,
dropdownContainer,
dropdownOpen,
highlightedIndex,
hasSelectedCompany,
periods,
selectedPeriodDisplay,
selectorClass,
isSelected,
isHighlighted,
toggleDropdown,
closeDropdown,
selectPeriod,
};
},
};
</script>
<style scoped>
.period-selector {
position: relative;
max-width: 220px;
}
.period-dropdown {
position: relative;
}
.period-trigger {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-sm, 8px);
padding: var(--space-sm, 8px) var(--space-md, 12px);
background: var(--color-bg, #fff);
border: 1px solid var(--color-border, #e5e7eb);
border-radius: var(--radius-md, 6px);
cursor: pointer;
transition: all 0.15s ease;
width: 100%;
text-align: left;
min-width: 200px;
}
.period-trigger:hover:not(:disabled) {
border-color: var(--color-primary, #2563eb);
background: var(--color-bg-secondary, #f9fafb);
}
.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, 12px);
color: var(--color-text-secondary, #6b7280);
}
.period-name {
font-size: var(--text-sm, 14px);
font-weight: 500;
color: var(--color-text, #111827);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.pi-chevron-down {
transition: transform 0.15s ease;
color: var(--color-text-secondary, #6b7280);
font-size: var(--text-xs, 12px);
}
.rotate-180 {
transform: rotate(180deg);
}
.period-dropdown-panel {
position: absolute;
top: calc(100% + 4px);
left: 0;
right: 0;
background: var(--color-bg, #fff);
border: 1px solid var(--color-border, #e5e7eb);
border-radius: var(--radius-md, 6px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
z-index: 1000;
max-height: 300px;
overflow: hidden;
opacity: 0;
transform: translateY(-10px);
transition: all 0.15s ease;
}
.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, 8px) var(--space-md, 12px);
cursor: pointer;
transition: background-color 0.15s ease;
border-bottom: 1px solid var(--color-border-light, #f3f4f6);
}
.period-item:last-child {
border-bottom: none;
}
.period-item:hover {
background: var(--color-bg-secondary, #f9fafb);
}
.period-item.active {
background: var(--color-primary, #2563eb);
color: #fff;
}
.period-item.keyboard-highlighted {
background: var(--color-bg-secondary, #f9fafb);
outline: 2px solid var(--color-primary, #2563eb);
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, 14px);
}
.period-selected-icon {
color: inherit;
font-size: var(--text-sm, 14px);
}
.no-results {
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-sm, 8px);
padding: var(--space-xl, 24px);
color: var(--color-text-secondary, #6b7280);
font-size: var(--text-sm, 14px);
}
/* Mobile adjustments */
@media (max-width: 768px) {
.period-selector {
max-width: 140px;
width: auto;
}
.period-trigger {
min-width: auto;
padding: var(--space-xs, 4px) var(--space-sm, 8px);
}
.period-info {
flex-direction: row;
align-items: center;
gap: var(--space-xs, 4px);
}
.period-label {
display: none;
}
.period-name {
font-size: var(--text-xs, 12px);
}
.period-dropdown-panel {
position: fixed;
left: 8px;
right: 8px;
top: 60px;
width: auto;
max-height: 70vh;
}
}
/* Header variant - transparent background, white text for dark headers */
.period-selector--header .period-trigger {
background: transparent;
border-color: rgba(255, 255, 255, 0.3);
}
.period-selector--header .period-trigger:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.1);
border-color: rgba(255, 255, 255, 0.5);
}
.period-selector--header .period-trigger:disabled {
border-color: rgba(255, 255, 255, 0.15);
}
.period-selector--header .period-label {
color: rgba(255, 255, 255, 0.7);
}
.period-selector--header .period-name {
color: white;
}
.period-selector--header .pi-chevron-down {
color: rgba(255, 255, 255, 0.8);
}
/* Dropdown panel keeps default styling (white background) */
</style>

View File

@@ -0,0 +1,132 @@
<template>
<header class="header-container" :class="headerClass">
<nav class="header-nav">
<!-- Left side: Hamburger + Brand -->
<div class="header-left">
<button
class="hamburger-btn"
:class="{ active: menuOpen }"
@click="$emit('menu-toggle')"
aria-label="Toggle navigation menu"
>
<span class="hamburger-line"></span>
<span class="hamburger-line"></span>
<span class="hamburger-line"></span>
</button>
<router-link :to="brandLink" class="header-brand">
<slot name="brand">
<span>{{ title }}</span>
</slot>
</router-link>
</div>
<!-- Right side: Period + Company + User -->
<div class="header-actions">
<PeriodSelector
v-if="showPeriod && selectedCompany"
:period-store="periodStore"
:companies-store="companiesStore"
variant="header"
@period-changed="onPeriodChanged"
/>
<CompanySelector
v-if="showCompany"
:companies-store="companiesStore"
:show-fiscal-code="true"
variant="header"
@company-changed="onCompanyChanged"
/>
<slot name="user-menu">
<div v-if="showUser && currentUser" class="header-user" @click="$emit('user-menu-toggle')">
<i class="pi pi-user"></i>
<span class="desktop-only">{{ currentUser?.username || 'User' }}</span>
</div>
</slot>
</div>
</nav>
</header>
</template>
<script>
import { computed } from "vue";
import CompanySelector from "../CompanySelector.vue";
import PeriodSelector from "../PeriodSelector.vue";
export default {
name: "AppHeader",
components: {
CompanySelector,
PeriodSelector,
},
props: {
// Header title/brand text
title: {
type: String,
default: "ROA2WEB",
},
// Router link for brand click
brandLink: {
type: String,
default: "/",
},
// Additional CSS class for header (e.g., 'header-container--gradient')
headerClass: {
type: String,
default: "",
},
// Is hamburger menu open?
menuOpen: {
type: Boolean,
default: false,
},
// Companies store instance (required for selectors)
companiesStore: {
type: Object,
required: true,
},
// Period store instance (required for period selector)
periodStore: {
type: Object,
required: true,
},
// Current user object for display
currentUser: {
type: Object,
default: null,
},
// Show/hide period selector
showPeriod: {
type: Boolean,
default: true,
},
// Show/hide company selector
showCompany: {
type: Boolean,
default: true,
},
// Show/hide user info
showUser: {
type: Boolean,
default: true,
},
},
emits: ["menu-toggle", "company-changed", "period-changed", "user-menu-toggle"],
setup(props, { emit }) {
const selectedCompany = computed(() => props.companiesStore.selectedCompany);
const onCompanyChanged = (company) => {
emit("company-changed", company);
};
const onPeriodChanged = (period) => {
emit("period-changed", period);
};
return {
selectedCompany,
onCompanyChanged,
onPeriodChanged,
};
},
};
</script>

View File

@@ -0,0 +1,101 @@
<template>
<div>
<!-- Menu Overlay -->
<div
class="slide-menu-overlay"
:class="{ open: isOpen }"
@click="$emit('close')"
></div>
<!-- Slide Menu -->
<nav class="slide-menu" :class="{ open: isOpen }">
<!-- Dynamic Menu Sections -->
<div
v-for="section in menuItems"
:key="section.title"
class="menu-section"
>
<h3 class="menu-title">{{ section.title }}</h3>
<ul class="menu-list">
<li
v-for="item in section.items"
:key="item.to"
class="menu-item"
>
<router-link
:to="item.to"
class="menu-link"
:class="{ active: isRouteActive(item.to) }"
@click="$emit('close')"
>
<i :class="['menu-icon', item.icon]"></i>
<span>{{ item.label }}</span>
<span v-if="item.badge" class="menu-badge">{{ item.badge }}</span>
</router-link>
</li>
</ul>
</div>
<!-- Profile Section (at bottom) -->
<div class="menu-section menu-profile">
<div class="profile-info">
<i class="pi pi-user"></i>
<span>{{ currentUser?.username || 'Utilizator' }}</span>
</div>
<ul class="menu-list">
<slot name="profile-items"></slot>
<li class="menu-item">
<a href="#" class="menu-link" @click.prevent="handleLogout">
<i class="menu-icon pi pi-sign-out"></i>
<span>Deconectare</span>
</a>
</li>
</ul>
</div>
</nav>
</div>
</template>
<script>
import { useRoute } from "vue-router";
export default {
name: "SlideMenu",
props: {
// Is menu open?
isOpen: {
type: Boolean,
default: false,
},
// Menu items configuration
// Format: [{ title: 'Section', items: [{ to: '/path', icon: 'pi pi-icon', label: 'Label', badge: null }] }]
menuItems: {
type: Array,
default: () => [],
},
// Current user object
currentUser: {
type: Object,
default: null,
},
},
emits: ["close", "logout"],
setup(props, { emit }) {
const route = useRoute();
const isRouteActive = (path) => {
return route.path === path;
};
const handleLogout = () => {
emit("logout");
emit("close");
};
return {
isRouteActive,
handleLogout,
};
},
};
</script>

View File

@@ -0,0 +1,158 @@
/**
* Shared Accounting Period Store Factory
*
* Creates a Pinia store for accounting period selection that can be used by any ROA2WEB application.
* Each app passes its own apiService and store references.
*
* Usage:
* import { createAccountingPeriodStore } from '@shared/frontend/stores/accountingPeriod';
* import { apiService } from '../services/api';
* import { useAuthStore } from './auth';
* import { useCompanyStore } from './companies';
* export const useAccountingPeriodStore = createAccountingPeriodStore(apiService, useAuthStore, useCompanyStore);
*/
import { defineStore } from "pinia";
import { ref, computed } from "vue";
/**
* Factory function to create an accounting period store
* @param {Object} apiService - Axios instance configured for the app's API
* @param {Function} useAuthStore - Reference to the auth store function
* @param {Function} useCompanyStore - Reference to the company store function
* @returns {Function} Pinia store definition
*/
export function createAccountingPeriodStore(apiService, useAuthStore, useCompanyStore) {
return 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,
};
});
// 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));
}
};
// 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;
};
return {
// State
periods,
selectedPeriod,
isLoading,
error,
// Getters
hasPeriods,
currentPeriod,
dateRange,
// Actions
loadPeriods,
setSelectedPeriod,
resetToLatest,
reset,
};
});
}

View File

@@ -0,0 +1,196 @@
/**
* Shared Companies Store Factory
*
* Creates a Pinia store for company selection that can be used by any ROA2WEB application.
* Each app passes its own apiService and auth store instances.
*
* Usage:
* import { createCompaniesStore } from '@shared/frontend/stores/companies';
* import { apiService } from '../services/api';
* import { useAuthStore } from './auth';
* export const useCompanyStore = createCompaniesStore(apiService, useAuthStore);
*/
import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
/**
* Factory function to create a companies store
* @param {Object} apiService - Axios instance configured for the app's API
* @param {Function} useAuthStore - Reference to the auth store function
* @returns {Function} Pinia store definition
*/
export function createCompaniesStore(apiService, useAuthStore) {
return defineStore("companies", () => {
// State
const companies = ref([]);
const selectedCompany = ref(null);
const isLoading = ref(false);
const error = ref(null);
// Initialize from localStorage - per user
const initializeSelectedCompany = () => {
const authStore = useAuthStore();
const username = authStore.user?.username;
if (!username) {
console.log("[Companies] No username available for initialization");
return null;
}
const key = `selected_company_${username}`;
const saved = localStorage.getItem(key);
if (saved) {
try {
const company = JSON.parse(saved);
console.log(`[Companies] Loaded saved company for ${username}:`, company.name);
return company;
} catch (e) {
console.error("Failed to parse saved company", e);
localStorage.removeItem(key);
}
}
return null;
};
// Watch for auth user changes to restore selected company
const authStore = useAuthStore();
watch(
() => authStore.user,
(newUser) => {
if (newUser && newUser.username && !selectedCompany.value) {
const restoredCompany = initializeSelectedCompany();
if (restoredCompany) {
selectedCompany.value = restoredCompany;
console.log("[Companies] Restored selected company:", restoredCompany.name);
}
}
},
{ immediate: true }
);
// Getters
const companyList = computed(() => companies.value);
const hasCompanies = computed(() => companies.value.length > 0);
const selectedCompanyId = computed(() => selectedCompany.value?.id_firma || null);
const companyListFormatted = computed(() => {
return companies.value.map((company) => ({
...company,
displayName: company.fiscal_code
? `${company.name} (${company.fiscal_code})`
: company.name,
}));
});
// Actions
const loadCompanies = async () => {
isLoading.value = true;
error.value = null;
try {
console.log("[Companies] Loading companies...");
const response = await apiService.get("/companies");
companies.value = response.data.companies || [];
console.log("[Companies] Loaded", companies.value.length, "companies");
// Validate saved company is still accessible
if (selectedCompany.value) {
const exists = companies.value.find(
(c) => c.id_firma === selectedCompany.value.id_firma
);
if (!exists) {
console.warn("[Companies] Saved company not accessible, clearing");
clearSelectedCompany();
}
}
return { success: true };
} catch (err) {
error.value = err.response?.data?.detail || "Failed to load companies";
console.error("Failed to load companies:", err);
return { success: false, error: error.value };
} finally {
isLoading.value = false;
}
};
const setSelectedCompany = (company) => {
selectedCompany.value = company;
const authStore = useAuthStore();
const username = authStore.user?.username;
if (!username) {
console.warn("[Companies] Cannot save - no username");
return;
}
const key = `selected_company_${username}`;
if (company) {
localStorage.setItem(key, JSON.stringify(company));
console.log(`[Companies] Saved company for ${username}:`, company.name);
} else {
localStorage.removeItem(key);
}
};
const clearSelectedCompany = () => {
selectedCompany.value = null;
const authStore = useAuthStore();
const username = authStore.user?.username;
if (username) {
const key = `selected_company_${username}`;
localStorage.removeItem(key);
}
};
const getCompanyById = (id_firma) => {
return companies.value.find(
(company) => company.id_firma === parseInt(id_firma)
);
};
const clearError = () => {
error.value = null;
};
const reset = () => {
companies.value = [];
selectedCompany.value = null;
isLoading.value = false;
error.value = null;
const authStore = useAuthStore();
const username = authStore.user?.username;
if (username) {
const key = `selected_company_${username}`;
localStorage.removeItem(key);
}
};
return {
// State
companies,
selectedCompany,
isLoading,
error,
// Getters
companyList,
companyListFormatted,
hasCompanies,
selectedCompanyId,
// Actions
loadCompanies,
setSelectedCompany,
clearSelectedCompany,
getCompanyById,
clearError,
reset,
};
});
}

View File

@@ -0,0 +1,167 @@
/* Shared Header Styles - ROA2WEB */
/* Header Container */
.header-container {
position: sticky;
top: 0;
z-index: var(--z-header, 100);
background: var(--color-bg, #fff);
border-bottom: 1px solid var(--color-border, #e5e7eb);
height: var(--header-height, 60px);
padding: 0 var(--space-lg, 24px);
}
/* Gradient Header Variant */
.header-container--gradient {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-bottom: none;
}
.header-container--gradient .header-brand {
color: white;
}
.header-container--gradient .hamburger-line {
background-color: white;
}
/* Header Navigation */
.header-nav {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
height: 100%;
max-width: 1600px;
margin: 0 auto;
}
/* Header Left Section */
.header-left {
display: flex;
align-items: center;
gap: var(--space-md, 16px);
}
/* Brand/Logo */
.header-brand {
display: flex;
align-items: center;
gap: var(--space-sm, 8px);
font-size: var(--text-lg, 18px);
font-weight: var(--font-semibold, 600);
color: var(--color-primary, #2563eb);
text-decoration: none;
white-space: nowrap;
}
.header-brand:hover {
opacity: 0.9;
}
/* Header Actions (right side) */
.header-actions {
display: flex;
align-items: center;
gap: var(--space-md, 16px);
}
/* Hamburger Button */
.hamburger-btn {
display: flex;
flex-direction: column;
justify-content: space-around;
width: 32px;
height: 32px;
background: transparent;
border: none;
cursor: pointer;
padding: 4px;
z-index: 10;
transition: all 0.3s ease;
}
.hamburger-btn:hover {
opacity: 0.7;
}
.hamburger-line {
width: 100%;
height: 3px;
background-color: var(--color-primary, #2563eb);
border-radius: 2px;
transition: all 0.3s ease;
transform-origin: center;
}
/* Hamburger Animation - X state */
.hamburger-btn.active .hamburger-line:nth-child(1) {
transform: translateY(9px) rotate(45deg);
}
.hamburger-btn.active .hamburger-line:nth-child(2) {
opacity: 0;
}
.hamburger-btn.active .hamburger-line:nth-child(3) {
transform: translateY(-9px) rotate(-45deg);
}
/* Header User Menu */
.header-user {
display: flex;
align-items: center;
gap: var(--space-sm, 8px);
padding: var(--space-sm, 8px);
border-radius: var(--radius-md, 6px);
cursor: pointer;
transition: background-color 0.15s ease;
color: var(--color-text, #111827);
}
.header-user:hover {
background-color: var(--color-bg-secondary, #f9fafb);
}
/* Gradient header user menu */
.header-container--gradient .header-user {
color: white;
}
.header-container--gradient .header-user:hover {
background-color: rgba(255, 255, 255, 0.1);
}
/* Mobile Responsive */
@media (max-width: 768px) {
.header-container {
padding: 0 var(--space-md, 12px);
}
.header-left {
gap: var(--space-sm, 8px);
}
.header-actions {
gap: var(--space-sm, 8px);
}
.header-brand {
font-size: var(--text-base, 16px);
}
/* Hide text-only elements on mobile */
.desktop-only {
display: none;
}
}
@media (max-width: 480px) {
.header-brand span {
display: none;
}
.header-brand i {
font-size: 1.5rem;
}
}

View File

@@ -0,0 +1,151 @@
/* Shared Navigation Styles - ROA2WEB */
/* Slide-out Menu */
.slide-menu {
position: fixed;
top: var(--header-height, 60px);
left: 0;
width: var(--sidebar-width, 280px);
height: calc(100vh - var(--header-height, 60px));
background: var(--color-bg, #fff);
border-right: 1px solid var(--color-border, #e5e7eb);
box-shadow: var(--shadow-lg, 0 10px 15px -3px rgba(0, 0, 0, 0.1));
transform: translateX(-100%);
transition: transform 0.3s ease;
z-index: var(--z-modal, 1000);
overflow-y: auto;
/* Flex container for profile section at bottom */
display: flex;
flex-direction: column;
}
.slide-menu.open {
transform: translateX(0);
}
/* Menu Overlay */
.slide-menu-overlay {
position: fixed;
top: var(--header-height, 60px);
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
z-index: var(--z-modal-backdrop, 999);
}
.slide-menu-overlay.open {
opacity: 1;
visibility: visible;
}
/* Menu Sections */
.menu-section {
padding: var(--space-lg, 24px);
border-bottom: 1px solid var(--color-border, #e5e7eb);
}
.menu-section:last-child {
border-bottom: none;
}
/* Profile section at bottom */
.menu-section.menu-profile {
margin-top: auto;
border-top: 1px solid var(--color-border, #e5e7eb);
border-bottom: none;
}
.menu-title {
font-size: var(--text-sm, 14px);
font-weight: var(--font-semibold, 600);
color: var(--color-text-secondary, #6b7280);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: var(--space-md, 12px);
}
.menu-list {
list-style: none;
margin: 0;
padding: 0;
}
.menu-item {
margin-bottom: var(--space-xs, 4px);
}
.menu-link {
display: flex;
align-items: center;
gap: var(--space-sm, 8px);
padding: var(--space-sm, 8px) var(--space-md, 12px);
color: var(--color-text, #111827);
text-decoration: none;
border-radius: var(--radius-md, 6px);
transition: all 0.15s ease;
font-size: var(--text-sm, 14px);
}
.menu-link:hover,
.menu-link.active {
background-color: var(--color-bg-secondary, #f9fafb);
color: var(--color-primary, #2563eb);
}
.menu-icon {
width: 18px;
height: 18px;
flex-shrink: 0;
font-size: 16px;
}
/* Profile Info */
.profile-info {
display: flex;
align-items: center;
gap: var(--space-sm, 8px);
padding: var(--space-sm, 8px) var(--space-md, 12px);
margin-bottom: var(--space-sm, 8px);
font-weight: var(--font-medium, 500);
color: var(--color-text, #111827);
}
.profile-info i {
font-size: 1.25rem;
color: var(--color-primary, #2563eb);
}
/* Badge for menu items */
.menu-badge {
margin-left: auto;
background: var(--color-danger, #ef4444);
color: white;
font-size: var(--text-xs, 12px);
font-weight: var(--font-semibold, 600);
padding: 2px 6px;
border-radius: var(--radius-full, 9999px);
min-width: 20px;
text-align: center;
}
/* Mobile Responsive */
@media (max-width: 768px) {
.slide-menu {
width: 280px;
}
.menu-section {
padding: var(--space-md, 12px);
}
}
@media (max-width: 480px) {
.slide-menu {
width: 100vw;
max-width: 320px;
}
}

11
shared/models/__init__.py Normal file
View File

@@ -0,0 +1,11 @@
"""Shared Pydantic models for ROA2WEB applications."""
from .company import Company, CompanyListResponse
from .calendar import CalendarPeriod, CalendarPeriodsResponse
__all__ = [
"Company",
"CompanyListResponse",
"CalendarPeriod",
"CalendarPeriodsResponse",
]

18
shared/models/calendar.py Normal file
View File

@@ -0,0 +1,18 @@
"""Calendar/accounting period models for ROA2WEB applications."""
from typing import List, Optional
from pydantic import BaseModel
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
total_count: int

19
shared/models/company.py Normal file
View File

@@ -0,0 +1,19 @@
"""Company models for ROA2WEB applications."""
from typing import List, Optional
from pydantic import BaseModel
class Company(BaseModel):
"""Model for a company/firma."""
id_firma: int
name: str
schema_name: str
fiscal_code: Optional[str] = None
is_active: bool = True
class CompanyListResponse(BaseModel):
"""Response model for list of companies."""
companies: List[Company]
total_count: int

21
shared/routes/__init__.py Normal file
View File

@@ -0,0 +1,21 @@
"""
Shared Routes for ROA2WEB Applications
This module provides factory functions for creating common API routers
that can be mounted in both reports-app and data-entry-app.
Usage:
from shared.routes import create_companies_router, create_calendar_router
# In main.py
companies_router = create_companies_router(oracle_pool)
app.include_router(companies_router, prefix="/api/companies")
"""
from .companies import create_companies_router
from .calendar import create_calendar_router
__all__ = [
"create_companies_router",
"create_calendar_router",
]

136
shared/routes/calendar.py Normal file
View File

@@ -0,0 +1,136 @@
"""
Shared Calendar Router Factory for ROA2WEB Applications
Creates a FastAPI router for /api/calendar endpoints that can be used
by both reports-app and data-entry-app.
Usage:
from shared.routes.calendar import create_calendar_router
calendar_router = create_calendar_router(oracle_pool, cache_decorator=cached)
app.include_router(calendar_router, prefix="/api/calendar")
"""
import logging
from typing import Optional, Callable, List
from fastapi import APIRouter, Depends, HTTPException, Query
from auth.dependencies import get_current_user
from auth.models import CurrentUser
from models.calendar import CalendarPeriod, CalendarPeriodsResponse
logger = logging.getLogger(__name__)
# Romanian month names
MONTH_NAMES_RO = [
"Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie",
"Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
]
def create_calendar_router(
oracle_pool,
cache_decorator: Optional[Callable] = None,
tags: Optional[List[str]] = None
) -> APIRouter:
"""
Factory function to create a calendar router.
Args:
oracle_pool: The Oracle connection pool instance
cache_decorator: Optional caching decorator (e.g., @cached)
tags: OpenAPI tags for the router
Returns:
Configured FastAPI router for calendar endpoints
"""
router = APIRouter(
redirect_slashes=False,
tags=tags or ["calendar"]
)
# Helper to get schema for company
async def _get_schema_for_company(company_id: int) -> Optional[str]:
"""Get Oracle schema for company ID."""
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
# Apply cache to schema lookup if decorator provided
if cache_decorator:
_get_schema_for_company = cache_decorator(
cache_type='schema',
key_params=['company_id']
)(_get_schema_for_company)
# Helper to get periods - can be cached
async def _get_available_periods(company_id: int) -> CalendarPeriodsResponse:
"""Get available accounting periods for a company."""
schema = await _get_schema_for_company(company_id)
if not schema:
logger.warning(f"Schema not found for company {company_id}")
return CalendarPeriodsResponse(periods=[], current_period=None, total_count=0)
try:
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 = 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)} periods for company {company_id}")
return CalendarPeriodsResponse(
periods=periods,
current_period=current_period,
total_count=len(periods)
)
except Exception as e:
logger.error(f"Error fetching periods for company {company_id}: {e}")
return CalendarPeriodsResponse(periods=[], current_period=None, total_count=0)
# Apply cache decorator if provided
if cache_decorator:
_get_available_periods = cache_decorator(
cache_type='calendar_periods',
key_params=['company_id']
)(_get_available_periods)
@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(403, f"Nu aveți acces la firma {company}")
return await _get_available_periods(company)
return router

175
shared/routes/companies.py Normal file
View File

@@ -0,0 +1,175 @@
"""
Shared Companies Router Factory for ROA2WEB Applications
Creates a FastAPI router for /api/companies endpoints that can be used
by both reports-app and data-entry-app.
Usage:
from shared.routes.companies import create_companies_router
companies_router = create_companies_router(oracle_pool, cache_decorator=cached)
app.include_router(companies_router, prefix="/api/companies")
"""
import logging
from typing import Optional, Callable, List
from fastapi import APIRouter, Depends, HTTPException, Request
from auth.dependencies import get_current_user
from auth.models import CurrentUser
from models.company import Company, CompanyListResponse
logger = logging.getLogger(__name__)
def create_companies_router(
oracle_pool,
cache_decorator: Optional[Callable] = None,
tags: Optional[List[str]] = None
) -> APIRouter:
"""
Factory function to create a companies router.
Args:
oracle_pool: The Oracle connection pool instance
cache_decorator: Optional caching decorator (e.g., @cached)
tags: OpenAPI tags for the router
Returns:
Configured FastAPI router for company endpoints
"""
router = APIRouter(
redirect_slashes=False,
tags=tags or ["companies"]
)
# Helper function to get companies - can be cached
async def _get_user_companies_data(username: str) -> List[Company]:
"""
Get list of companies for a user from Oracle.
"""
companies = []
async with oracle_pool.get_connection() as connection:
with connection.cursor() as cursor:
try:
# Get user ID
cursor.execute("""
SELECT ID_UTIL, UTILIZATOR
FROM UTILIZATORI
WHERE UPPER(UTILIZATOR) = :username
""", {'username': username.upper()})
user_row = cursor.fetchone()
if not user_row:
logger.warning(f"User {username} not found in UTILIZATORI")
return []
user_id = user_row[0]
# Get companies for user (program 2 = data entry/reports)
cursor.execute("""
SELECT A.ID_FIRMA, A.FIRMA, A.SCHEMA, A.COD_FISCAL
FROM V_NOM_FIRME A
WHERE A.ID_FIRMA IN (
SELECT ID_FIRMA
FROM VDEF_UTIL_FIRME
WHERE ID_PROGRAM = 2 AND ID_UTIL = :user_id
)
ORDER BY A.FIRMA
""", {'user_id': user_id})
for row in cursor.fetchall():
companies.append(Company(
id_firma=row[0],
name=row[1],
schema_name=row[2],
fiscal_code=row[3],
is_active=True
))
logger.info(f"Found {len(companies)} companies for user {username}")
except Exception as e:
logger.error(f"Error fetching companies: {e}")
return companies
# Apply cache decorator if provided
if cache_decorator:
_get_user_companies_data = cache_decorator(
cache_type='companies',
key_params=['username']
)(_get_user_companies_data)
@router.get("", response_model=CompanyListResponse)
@router.get("/", response_model=CompanyListResponse)
async def get_user_companies(
request: Request,
current_user: CurrentUser = Depends(get_current_user)
):
"""Get list of companies the user has access to."""
try:
companies = await _get_user_companies_data(current_user.username)
return CompanyListResponse(
companies=companies,
total_count=len(companies)
)
except Exception as e:
logger.error(f"Error in get_user_companies: {e}")
raise HTTPException(500, f"Eroare la obținerea listei de firme: {str(e)}")
@router.get("/{company_id}", response_model=Company)
async def get_company_details(
company_id: str,
current_user: CurrentUser = Depends(get_current_user)
):
"""Get details of a specific company."""
# Validate access
if company_id not in current_user.companies:
raise HTTPException(403, f"Nu aveți acces la firma {company_id}")
try:
async with oracle_pool.get_connection() as connection:
with connection.cursor() as cursor:
cursor.execute("""
SELECT ID_FIRMA, FIRMA, SCHEMA, COD_FISCAL
FROM V_NOM_FIRME
WHERE ID_FIRMA = :company_id
""", {'company_id': int(company_id)})
row = cursor.fetchone()
if not row:
raise HTTPException(404, f"Firma {company_id} nu a fost găsită")
return Company(
id_firma=row[0],
name=row[1],
schema_name=row[2],
fiscal_code=row[3] or "",
is_active=True
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, f"Eroare la obținerea detaliilor firmei: {str(e)}")
@router.get("/{company_id}/validate")
async def validate_company_access(
company_id: str,
current_user: CurrentUser = Depends(get_current_user)
):
"""Validate if user has access to a company."""
has_access = company_id in current_user.companies
return {
"company_id": company_id,
"has_access": has_access,
"user": current_user.username,
"message": "Acces validat" if has_access else "Acces refuzat"
}
return router