feat: system settings, dynamic logos, template numbering, permission consolidation
- System settings page with tabs: Security, System, Firma
- Configurable attendance rules (break thresholds, rounding) from DB
- Configurable document numbering with template patterns ({YYYY}/{PREFIX}/{NNN})
- Dynamic logo upload (light/dark variants) served from DB instead of static files
- Email settings (SMTP from/name, alert/leave emails) configurable in UI
- Currency and VAT rate lists configurable, used across all modules
- Permissions simplified: offers.settings + settings.roles + settings.security → settings.manage
- Leaflet bundled locally, removed unpkg.com from CSP
- Silent catch blocks fixed with proper logging
- console.log replaced with app.log.info in server.ts
- Schema renamed: company-settings.schema → settings.schema
- App info section: version, Node.js, uptime, memory, DB status, NAS status
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -19,7 +19,7 @@
|
||||
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="shortcut icon" href="/favicon.ico" />
|
||||
<title>BOHA | Admin</title>
|
||||
<title>Admin</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
29
package-lock.json
generated
29
package-lock.json
generated
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "boha-app-ts",
|
||||
"name": "app-ts",
|
||||
"version": "1.1.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "boha-app-ts",
|
||||
"name": "app-ts",
|
||||
"version": "1.1.4",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
@@ -28,6 +28,7 @@
|
||||
"framer-motion": "^12.38.0",
|
||||
"hi-base32": "^0.5.1",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"leaflet": "^1.9.4",
|
||||
"node-cron": "^4.2.1",
|
||||
"nodemailer": "^8.0.2",
|
||||
"otpauth": "^9.5.0",
|
||||
@@ -45,6 +46,7 @@
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"@types/mysql": "^2.15.27",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/node-cron": "^3.0.11",
|
||||
@@ -1504,6 +1506,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/geojson": {
|
||||
"version": "7946.0.16",
|
||||
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
|
||||
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/jsonwebtoken": {
|
||||
"version": "9.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
|
||||
@@ -1515,6 +1524,16 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/leaflet": {
|
||||
"version": "1.9.21",
|
||||
"resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.21.tgz",
|
||||
"integrity": "sha512-TbAd9DaPGSnzp6QvtYngntMZgcRk+igFELwR2N99XZn7RXUdKgsXMR+28bUO0rPsWp8MIu/f47luLIQuSLYv/w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/geojson": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/methods": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||
@@ -3699,6 +3718,12 @@
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/leaflet": {
|
||||
"version": "1.9.4",
|
||||
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
|
||||
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/light-my-request": {
|
||||
"version": "6.6.0",
|
||||
"resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz",
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"framer-motion": "^12.38.0",
|
||||
"hi-base32": "^0.5.1",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"leaflet": "^1.9.4",
|
||||
"node-cron": "^4.2.1",
|
||||
"nodemailer": "^8.0.2",
|
||||
"otpauth": "^9.5.0",
|
||||
@@ -60,6 +61,7 @@
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"@types/mysql": "^2.15.27",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/node-cron": "^3.0.11",
|
||||
|
||||
1
prisma/migrations/20260327_add_dark_logo/migration.sql
Normal file
1
prisma/migrations/20260327_add_dark_logo/migration.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE `company_settings` ADD COLUMN `logo_data_dark` MEDIUMBLOB NULL AFTER `logo_data`;
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE `company_settings`
|
||||
ADD COLUMN `offer_number_pattern` VARCHAR(100) NULL,
|
||||
ADD COLUMN `order_number_pattern` VARCHAR(100) NULL,
|
||||
ADD COLUMN `invoice_number_pattern` VARCHAR(100) NULL;
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE `company_settings`
|
||||
ADD COLUMN `smtp_from` VARCHAR(255) NULL,
|
||||
ADD COLUMN `smtp_from_name` VARCHAR(255) NULL;
|
||||
13
prisma/migrations/20260327_add_system_settings/migration.sql
Normal file
13
prisma/migrations/20260327_add_system_settings/migration.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
-- System settings columns on company_settings
|
||||
ALTER TABLE `company_settings`
|
||||
ADD COLUMN `break_threshold_hours` DECIMAL(4,2) DEFAULT 6,
|
||||
ADD COLUMN `break_duration_short` INT DEFAULT 15,
|
||||
ADD COLUMN `break_duration_long` INT DEFAULT 30,
|
||||
ADD COLUMN `clock_rounding_minutes` INT DEFAULT 15,
|
||||
ADD COLUMN `invoice_alert_email` VARCHAR(255) NULL,
|
||||
ADD COLUMN `leave_notify_email` VARCHAR(255) NULL,
|
||||
ADD COLUMN `max_login_attempts` INT DEFAULT 5,
|
||||
ADD COLUMN `lockout_minutes` INT DEFAULT 15,
|
||||
ADD COLUMN `max_requests_per_minute` INT DEFAULT 300,
|
||||
ADD COLUMN `available_vat_rates` LONGTEXT NULL,
|
||||
ADD COLUMN `available_currencies` LONGTEXT NULL;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Create new unified permission
|
||||
INSERT INTO permissions (name, display_name, description, module)
|
||||
VALUES ('settings.manage', 'Správa nastavení', 'Správa všech nastavení systému', 'settings')
|
||||
ON DUPLICATE KEY UPDATE display_name = VALUES(display_name);
|
||||
|
||||
-- Grant to all roles that had any of the old 3
|
||||
INSERT IGNORE INTO role_permissions (role_id, permission_id)
|
||||
SELECT DISTINCT rp.role_id, (SELECT id FROM permissions WHERE name = 'settings.manage')
|
||||
FROM role_permissions rp
|
||||
JOIN permissions p ON p.id = rp.permission_id
|
||||
WHERE p.name IN ('offers.settings', 'settings.roles', 'settings.security');
|
||||
|
||||
-- Clean up old role_permissions
|
||||
DELETE FROM role_permissions
|
||||
WHERE permission_id IN (SELECT id FROM permissions WHERE name IN ('offers.settings', 'settings.roles', 'settings.security'));
|
||||
|
||||
-- Remove old permissions
|
||||
DELETE FROM permissions WHERE name IN ('offers.settings', 'settings.roles', 'settings.security');
|
||||
@@ -100,6 +100,7 @@ model company_settings {
|
||||
vat_id String? @db.VarChar(50)
|
||||
custom_fields String? @db.LongText
|
||||
logo_data Bytes?
|
||||
logo_data_dark Bytes?
|
||||
quotation_prefix String? @db.VarChar(20)
|
||||
default_currency String? @default("CZK") @db.VarChar(10)
|
||||
default_vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
@@ -109,7 +110,23 @@ model company_settings {
|
||||
sync_version Int? @default(0)
|
||||
order_type_code String? @db.VarChar(10)
|
||||
invoice_type_code String? @db.VarChar(10)
|
||||
require_2fa Boolean @default(false)
|
||||
require_2fa Boolean @default(false)
|
||||
break_threshold_hours Decimal? @default(6) @db.Decimal(4, 2)
|
||||
break_duration_short Int? @default(15)
|
||||
break_duration_long Int? @default(30)
|
||||
clock_rounding_minutes Int? @default(15)
|
||||
invoice_alert_email String? @db.VarChar(255)
|
||||
leave_notify_email String? @db.VarChar(255)
|
||||
max_login_attempts Int? @default(5)
|
||||
lockout_minutes Int? @default(15)
|
||||
max_requests_per_minute Int? @default(300)
|
||||
available_vat_rates String? @db.LongText
|
||||
available_currencies String? @db.LongText
|
||||
smtp_from String? @db.VarChar(255)
|
||||
smtp_from_name String? @db.VarChar(255)
|
||||
offer_number_pattern String? @db.VarChar(100)
|
||||
order_number_pattern String? @db.VarChar(100)
|
||||
invoice_number_pattern String? @db.VarChar(100)
|
||||
}
|
||||
|
||||
model customers {
|
||||
|
||||
@@ -32,7 +32,6 @@ const Offers = lazy(() => import("./pages/Offers"));
|
||||
const OfferDetail = lazy(() => import("./pages/OfferDetail"));
|
||||
const OffersCustomers = lazy(() => import("./pages/OffersCustomers"));
|
||||
const OffersTemplates = lazy(() => import("./pages/OffersTemplates"));
|
||||
const CompanySettings = lazy(() => import("./pages/CompanySettings"));
|
||||
const Orders = lazy(() => import("./pages/Orders"));
|
||||
const OrderDetail = lazy(() => import("./pages/OrderDetail"));
|
||||
const Projects = lazy(() => import("./pages/Projects"));
|
||||
@@ -91,7 +90,6 @@ export default function AdminApp() {
|
||||
<Route path="offers/:id" element={<OfferDetail />} />
|
||||
<Route path="offers/customers" element={<OffersCustomers />} />
|
||||
<Route path="offers/templates" element={<OffersTemplates />} />
|
||||
<Route path="company/settings" element={<CompanySettings />} />
|
||||
<Route path="orders" element={<Orders />} />
|
||||
<Route path="orders/:id" element={<OrderDetail />} />
|
||||
<Route path="projects" element={<Projects />} />
|
||||
|
||||
@@ -330,22 +330,6 @@ const menuSections: MenuSection[] = [
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/company/settings",
|
||||
label: "Firma",
|
||||
permission: "offers.settings",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
|
||||
<polyline points="9 22 9 12 15 12 15 22" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -372,7 +356,7 @@ const menuSections: MenuSection[] = [
|
||||
{
|
||||
path: "/settings",
|
||||
label: "Nastavení",
|
||||
permission: ["settings.roles", "settings.security"],
|
||||
permission: "settings.manage",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
@@ -464,11 +448,17 @@ export default function Sidebar({ isOpen, onClose, onLogout }: SidebarProps) {
|
||||
<img
|
||||
src={
|
||||
theme === "dark"
|
||||
? "/images/logo-dark.png"
|
||||
: "/images/logo-light.png"
|
||||
? "/api/admin/company-settings/logo?variant=dark"
|
||||
: "/api/admin/company-settings/logo?variant=light"
|
||||
}
|
||||
alt="Logo"
|
||||
className="admin-sidebar-logo"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).src =
|
||||
theme === "dark"
|
||||
? "/images/logo-dark.png"
|
||||
: "/images/logo-light.png";
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
onClick={onClose}
|
||||
|
||||
@@ -358,6 +358,7 @@ function buildPrintHtml(
|
||||
userSections: string,
|
||||
emptyMsg: string,
|
||||
filterNote: string,
|
||||
companyName: string,
|
||||
): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="cs">
|
||||
@@ -424,10 +425,10 @@ function buildPrintHtml(
|
||||
<thead><tr><td>
|
||||
<div class="print-header">
|
||||
<div class="print-header-left">
|
||||
<img src="/images/logo-light.png" alt="BOHA" class="print-logo" />
|
||||
<img src="/api/admin/company-settings/logo?variant=light" alt="" class="print-logo" />
|
||||
<div class="print-header-text">
|
||||
<h1>EVIDENCE DOCHÁZKY</h1>
|
||||
<div class="company">BOHA Automation s.r.o.</div>
|
||||
<div class="company">${companyName}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="print-header-right">
|
||||
@@ -1010,9 +1011,16 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
||||
// =========================================================================
|
||||
const handlePrint = async () => {
|
||||
try {
|
||||
let url = `${API_BASE}/attendance?action=print&month=${month}`;
|
||||
if (filterUserId) url += `&user_id=${filterUserId}`;
|
||||
const response = await apiFetch(url);
|
||||
const [response, settingsRes] = await Promise.all([
|
||||
apiFetch(
|
||||
`${API_BASE}/attendance?action=print&month=${month}${filterUserId ? `&user_id=${filterUserId}` : ""}`,
|
||||
),
|
||||
apiFetch(`${API_BASE}/company-settings`),
|
||||
]);
|
||||
const settingsData = await settingsRes.json();
|
||||
const companyName = settingsData.success
|
||||
? settingsData.data.company_name || ""
|
||||
: "";
|
||||
if (response.status === 401) return;
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
@@ -1034,6 +1042,7 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
||||
userSections,
|
||||
emptyMsg,
|
||||
filterNote,
|
||||
companyName,
|
||||
);
|
||||
const printWindow = window.open("", "_blank");
|
||||
if (printWindow) {
|
||||
|
||||
@@ -126,6 +126,7 @@ export default function AttendanceHistory() {
|
||||
const alert = useAlert();
|
||||
const { user, hasPermission } = useAuth();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const printRef = useRef<HTMLDivElement>(null);
|
||||
const [month, setMonth] = useState(() => {
|
||||
const now = new Date();
|
||||
@@ -156,6 +157,15 @@ export default function AttendanceHistory() {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch(`${API_BASE}/company-settings`)
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
if (d.success) setCompanyName(d.data.company_name || "");
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const computed = useMemo(() => {
|
||||
const [yearStr, monthStr] = month.split("-");
|
||||
const monthIndex = parseInt(monthStr, 10) - 1;
|
||||
@@ -637,13 +647,13 @@ export default function AttendanceHistory() {
|
||||
<div className="print-header">
|
||||
<div className="print-header-left">
|
||||
<img
|
||||
src="/images/logo-light.png"
|
||||
alt="BOHA"
|
||||
src="/api/admin/company-settings/logo?variant=light"
|
||||
alt=""
|
||||
className="print-logo"
|
||||
/>
|
||||
<div className="print-header-text">
|
||||
<h1>EVIDENCE DOCHÁZKY</h1>
|
||||
<div className="company">BOHA Automation s.r.o.</div>
|
||||
<div className="company">{companyName}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="print-header-right">
|
||||
|
||||
@@ -5,12 +5,13 @@ import Forbidden from "../components/Forbidden";
|
||||
import { useNavigate, useParams, Link } from "react-router-dom";
|
||||
import { motion } from "framer-motion";
|
||||
|
||||
import L from "leaflet";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
|
||||
import { formatDate, formatTime } from "../utils/attendanceHelpers";
|
||||
import apiFetch from "../utils/api";
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
declare const L: any;
|
||||
|
||||
interface LocationRecord {
|
||||
user_name: string;
|
||||
shift_date: string;
|
||||
@@ -74,23 +75,6 @@ export default function AttendanceLocation() {
|
||||
|
||||
if (!hasAnyLocation || !mapRef.current) return;
|
||||
|
||||
const loadLeaflet = async () => {
|
||||
if ((window as unknown as Record<string, unknown>).L) {
|
||||
initMap();
|
||||
return;
|
||||
}
|
||||
|
||||
const link = document.createElement("link");
|
||||
link.rel = "stylesheet";
|
||||
link.href = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.css";
|
||||
document.head.appendChild(link);
|
||||
|
||||
const script = document.createElement("script");
|
||||
script.src = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.js";
|
||||
script.onload = initMap;
|
||||
document.body.appendChild(script);
|
||||
};
|
||||
|
||||
const initMap = () => {
|
||||
if (mapInstanceRef.current) {
|
||||
(mapInstanceRef.current as { remove: () => void }).remove();
|
||||
@@ -175,7 +159,7 @@ export default function AttendanceLocation() {
|
||||
}
|
||||
};
|
||||
|
||||
loadLeaflet();
|
||||
initMap();
|
||||
|
||||
return () => {
|
||||
if (mapInstanceRef.current) {
|
||||
|
||||
@@ -24,8 +24,6 @@ const FIELD_LABELS: Record<string, string> = {
|
||||
vat_id: "DIČ",
|
||||
};
|
||||
|
||||
const currentYear = new Date().getFullYear().toString().slice(-2);
|
||||
|
||||
interface CustomField {
|
||||
name: string;
|
||||
value: string;
|
||||
@@ -41,11 +39,6 @@ interface CompanyForm {
|
||||
country: string;
|
||||
company_id: string;
|
||||
vat_id: string;
|
||||
quotation_prefix: string;
|
||||
default_currency: string;
|
||||
default_vat_rate: number;
|
||||
order_type_code: string;
|
||||
invoice_type_code: string;
|
||||
}
|
||||
|
||||
interface BankAccount {
|
||||
@@ -69,14 +62,19 @@ interface BankForm {
|
||||
is_default: boolean;
|
||||
}
|
||||
|
||||
export default function CompanySettings() {
|
||||
export default function CompanySettings({
|
||||
embedded,
|
||||
}: { embedded?: boolean } = {}) {
|
||||
const alert = useAlert();
|
||||
const { hasPermission } = useAuth();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [uploadingLogo, setUploadingLogo] = useState(false);
|
||||
const [uploadingLogoDark, setUploadingLogoDark] = useState(false);
|
||||
const [logoUrl, setLogoUrl] = useState<string | null>(null);
|
||||
const [logoUrlDark, setLogoUrlDark] = useState<string | null>(null);
|
||||
const logoUrlRef = useRef<string | null>(null);
|
||||
const logoUrlDarkRef = useRef<string | null>(null);
|
||||
const [form, setForm] = useState<CompanyForm>({
|
||||
company_name: "",
|
||||
street: "",
|
||||
@@ -85,11 +83,6 @@ export default function CompanySettings() {
|
||||
country: "",
|
||||
company_id: "",
|
||||
vat_id: "",
|
||||
quotation_prefix: "N",
|
||||
default_currency: "EUR",
|
||||
default_vat_rate: 21,
|
||||
order_type_code: "71",
|
||||
invoice_type_code: "81",
|
||||
});
|
||||
const [customFields, setCustomFields] = useState<CustomField[]>([]);
|
||||
const customFieldKeyCounter = useRef(0);
|
||||
@@ -97,6 +90,12 @@ export default function CompanySettings() {
|
||||
...DEFAULT_FIELD_ORDER,
|
||||
]);
|
||||
const [bankAccounts, setBankAccounts] = useState<BankAccount[]>([]);
|
||||
const [availableCurrencies, setAvailableCurrencies] = useState<string[]>([
|
||||
"CZK",
|
||||
"EUR",
|
||||
"USD",
|
||||
"GBP",
|
||||
]);
|
||||
const [bankLoading, setBankLoading] = useState(true);
|
||||
const [bankSaving, setBankSaving] = useState(false);
|
||||
const [editingBank, setEditingBank] = useState<number | null>(null);
|
||||
@@ -151,17 +150,28 @@ export default function CompanySettings() {
|
||||
return key;
|
||||
};
|
||||
|
||||
const fetchLogo = useCallback(async () => {
|
||||
const fetchLogo = useCallback(async (variant: "light" | "dark" = "light") => {
|
||||
try {
|
||||
const resp = await apiFetch(`${API_BASE}/company-settings/logo`);
|
||||
const resp = await apiFetch(
|
||||
`${API_BASE}/company-settings/logo?variant=${variant}`,
|
||||
);
|
||||
if (resp.ok) {
|
||||
const blob = await resp.blob();
|
||||
setLogoUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
const url = URL.createObjectURL(blob);
|
||||
logoUrlRef.current = url;
|
||||
return url;
|
||||
});
|
||||
if (variant === "dark") {
|
||||
setLogoUrlDark((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
const url = URL.createObjectURL(blob);
|
||||
logoUrlDarkRef.current = url;
|
||||
return url;
|
||||
});
|
||||
} else {
|
||||
setLogoUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
const url = URL.createObjectURL(blob);
|
||||
logoUrlRef.current = url;
|
||||
return url;
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore - no logo
|
||||
@@ -183,11 +193,6 @@ export default function CompanySettings() {
|
||||
country: d.country || "",
|
||||
company_id: d.company_id || "",
|
||||
vat_id: d.vat_id || "",
|
||||
quotation_prefix: d.quotation_prefix || "N",
|
||||
default_currency: d.default_currency || "EUR",
|
||||
default_vat_rate: d.default_vat_rate || 21,
|
||||
order_type_code: d.order_type_code || "71",
|
||||
invoice_type_code: d.invoice_type_code || "81",
|
||||
});
|
||||
const cf =
|
||||
Array.isArray(d.custom_fields) && d.custom_fields.length > 0
|
||||
@@ -207,8 +212,17 @@ export default function CompanySettings() {
|
||||
} else {
|
||||
setFieldOrder([...DEFAULT_FIELD_ORDER]);
|
||||
}
|
||||
if (
|
||||
Array.isArray(d.available_currencies) &&
|
||||
d.available_currencies.length > 0
|
||||
) {
|
||||
setAvailableCurrencies(d.available_currencies);
|
||||
}
|
||||
if (d.has_logo) {
|
||||
fetchLogo();
|
||||
fetchLogo("light");
|
||||
}
|
||||
if (d.has_logo_dark) {
|
||||
fetchLogo("dark");
|
||||
}
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se načíst nastavení");
|
||||
@@ -316,10 +330,11 @@ export default function CompanySettings() {
|
||||
fetchBankAccounts();
|
||||
}, [fetchData, fetchBankAccounts]);
|
||||
|
||||
// Cleanup blob URL on unmount
|
||||
// Cleanup blob URLs on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (logoUrlRef.current) URL.revokeObjectURL(logoUrlRef.current);
|
||||
if (logoUrlDarkRef.current) URL.revokeObjectURL(logoUrlDarkRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -351,30 +366,38 @@ export default function CompanySettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const handleLogoUpload = async (
|
||||
e: React.ChangeEvent<HTMLInputElement>,
|
||||
variant: "light" | "dark" = "light",
|
||||
) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setUploadingLogo(true);
|
||||
const setUploading =
|
||||
variant === "dark" ? setUploadingLogoDark : setUploadingLogo;
|
||||
setUploading(true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("logo", file);
|
||||
|
||||
const response = await apiFetch(`${API_BASE}/company-settings/logo`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
const response = await apiFetch(
|
||||
`${API_BASE}/company-settings/logo?variant=${variant}`,
|
||||
{
|
||||
method: "POST",
|
||||
body: formData,
|
||||
},
|
||||
);
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
alert.success(result.message || "Logo bylo nahráno");
|
||||
fetchLogo();
|
||||
fetchLogo(variant);
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se nahrát logo");
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
} finally {
|
||||
setUploadingLogo(false);
|
||||
setUploading(false);
|
||||
e.target.value = "";
|
||||
}
|
||||
};
|
||||
@@ -383,7 +406,7 @@ export default function CompanySettings() {
|
||||
setForm((prev) => ({ ...prev, [field]: value }));
|
||||
};
|
||||
|
||||
if (!hasPermission("offers.settings")) return <Forbidden />;
|
||||
if (!embedded && !hasPermission("settings.manage")) return <Forbidden />;
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -464,33 +487,33 @@ export default function CompanySettings() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<motion.div
|
||||
className="admin-page-header"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25 }}
|
||||
>
|
||||
<div>
|
||||
<h1 className="admin-page-title">Nastavení firmy</h1>
|
||||
<p className="admin-page-subtitle">
|
||||
Firemní údaje, číslování dokladů a výchozí hodnoty
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={saving}
|
||||
{!embedded && (
|
||||
<motion.div
|
||||
className="admin-page-header"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25 }}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Ukládání...
|
||||
</>
|
||||
) : (
|
||||
"Uložit nastavení"
|
||||
)}
|
||||
</button>
|
||||
</motion.div>
|
||||
<div>
|
||||
<h1 className="admin-page-title">Nastavení firmy</h1>
|
||||
<p className="admin-page-subtitle">Firemní údaje a bankovní účty</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Ukládání...
|
||||
</>
|
||||
) : (
|
||||
"Uložit nastavení"
|
||||
)}
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<div className="offers-settings-grid">
|
||||
{/* Company Info */}
|
||||
@@ -898,10 +921,11 @@ export default function CompanySettings() {
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="CZK">CZK</option>
|
||||
<option value="EUR">EUR</option>
|
||||
<option value="USD">USD</option>
|
||||
<option value="GBP">GBP</option>
|
||||
{availableCurrencies.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{c}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
</div>
|
||||
@@ -1055,177 +1079,135 @@ export default function CompanySettings() {
|
||||
<h3 className="admin-card-title">Logo</h3>
|
||||
</div>
|
||||
<div className="admin-card-body">
|
||||
<div className="offers-logo-section">
|
||||
{logoUrl && (
|
||||
<div className="offers-logo-preview">
|
||||
<img src={logoUrl} alt="Logo" />
|
||||
</div>
|
||||
)}
|
||||
<label
|
||||
className="admin-btn admin-btn-secondary"
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
{uploadingLogo ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Nahrávání...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="17 8 12 3 7 8" />
|
||||
<line x1="12" y1="3" x2="12" y2="15" />
|
||||
</svg>
|
||||
Nahrát logo
|
||||
</>
|
||||
<div className="admin-form-row">
|
||||
<div className="offers-logo-section">
|
||||
<label
|
||||
className="admin-form-label"
|
||||
style={{ display: "block", marginBottom: 4 }}
|
||||
>
|
||||
Logo (světlý režim)
|
||||
</label>
|
||||
{logoUrl && (
|
||||
<div className="offers-logo-preview">
|
||||
<img src={logoUrl} alt="Logo (světlý režim)" />
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleLogoUpload}
|
||||
style={{ display: "none" }}
|
||||
disabled={uploadingLogo}
|
||||
/>
|
||||
</label>
|
||||
<small className="admin-form-hint">
|
||||
PNG, JPEG, GIF nebo WebP, max 5 MB
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Cislovani dokladu */}
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.15 }}
|
||||
>
|
||||
<div className="admin-card-header">
|
||||
<h3 className="admin-card-title">Číslování dokladů</h3>
|
||||
</div>
|
||||
<div className="admin-card-body">
|
||||
<div className="admin-form">
|
||||
<FormField label="Nabídky — prefix">
|
||||
<input
|
||||
type="text"
|
||||
value={form.quotation_prefix}
|
||||
onChange={(e) =>
|
||||
updateField("quotation_prefix", e.target.value)
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="N"
|
||||
style={{ maxWidth: 120 }}
|
||||
/>
|
||||
<small className="admin-form-hint">
|
||||
Formát: ROK/PREFIX/ČÍSLO — ukázka: {new Date().getFullYear()}/
|
||||
{form.quotation_prefix || "N"}/001
|
||||
</small>
|
||||
</FormField>
|
||||
<hr
|
||||
style={{
|
||||
border: "none",
|
||||
borderTop: "1px solid var(--border-color)",
|
||||
margin: "0.75rem 0",
|
||||
}}
|
||||
/>
|
||||
<FormField label="Objednávky a projekty — typový kód">
|
||||
<input
|
||||
type="text"
|
||||
value={form.order_type_code}
|
||||
onChange={(e) =>
|
||||
updateField("order_type_code", e.target.value)
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="71"
|
||||
style={{ maxWidth: 120 }}
|
||||
/>
|
||||
<small className="admin-form-hint">
|
||||
Formát: RRKÓD#### — ukázka: {currentYear}
|
||||
{form.order_type_code || "71"}0001
|
||||
</small>
|
||||
</FormField>
|
||||
<hr
|
||||
style={{
|
||||
border: "none",
|
||||
borderTop: "1px solid var(--border-color)",
|
||||
margin: "0.75rem 0",
|
||||
}}
|
||||
/>
|
||||
<FormField label="Faktury — typový kód">
|
||||
<input
|
||||
type="text"
|
||||
value={form.invoice_type_code}
|
||||
onChange={(e) =>
|
||||
updateField("invoice_type_code", e.target.value)
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="81"
|
||||
style={{ maxWidth: 120 }}
|
||||
/>
|
||||
<small className="admin-form-hint">
|
||||
Formát: RRKÓD#### — ukázka: {currentYear}
|
||||
{form.invoice_type_code || "81"}0001
|
||||
</small>
|
||||
</FormField>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Default values */}
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.15 }}
|
||||
>
|
||||
<div className="admin-card-header">
|
||||
<h3 className="admin-card-title">Výchozí hodnoty</h3>
|
||||
</div>
|
||||
<div className="admin-card-body">
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Výchozí měna">
|
||||
<select
|
||||
value={form.default_currency}
|
||||
onChange={(e) =>
|
||||
updateField("default_currency", e.target.value)
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="EUR">EUR</option>
|
||||
<option value="USD">USD</option>
|
||||
<option value="CZK">CZK</option>
|
||||
<option value="GBP">GBP</option>
|
||||
</select>
|
||||
</FormField>
|
||||
<FormField label="Výchozí sazba DPH (%)">
|
||||
<label
|
||||
className="admin-btn admin-btn-secondary"
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
{uploadingLogo ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Nahrávání...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="17 8 12 3 7 8" />
|
||||
<line x1="12" y1="3" x2="12" y2="15" />
|
||||
</svg>
|
||||
Nahrát logo
|
||||
</>
|
||||
)}
|
||||
<input
|
||||
type="number"
|
||||
value={form.default_vat_rate}
|
||||
onChange={(e) =>
|
||||
updateField(
|
||||
"default_vat_rate",
|
||||
parseFloat(e.target.value) || 0,
|
||||
)
|
||||
}
|
||||
className="admin-form-input"
|
||||
step="0.1"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={(e) => handleLogoUpload(e, "light")}
|
||||
style={{ display: "none" }}
|
||||
disabled={uploadingLogo}
|
||||
/>
|
||||
</FormField>
|
||||
</label>
|
||||
<small className="admin-form-hint">
|
||||
PNG, JPEG, GIF nebo WebP, max 5 MB
|
||||
</small>
|
||||
</div>
|
||||
<div className="offers-logo-section">
|
||||
<label
|
||||
className="admin-form-label"
|
||||
style={{ display: "block", marginBottom: 4 }}
|
||||
>
|
||||
Logo (tmavý režim)
|
||||
</label>
|
||||
{logoUrlDark && (
|
||||
<div className="offers-logo-preview">
|
||||
<img src={logoUrlDark} alt="Logo (tmavý režim)" />
|
||||
</div>
|
||||
)}
|
||||
<label
|
||||
className="admin-btn admin-btn-secondary"
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
{uploadingLogoDark ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Nahrávání...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="17 8 12 3 7 8" />
|
||||
<line x1="12" y1="3" x2="12" y2="15" />
|
||||
</svg>
|
||||
Nahrát logo
|
||||
</>
|
||||
)}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={(e) => handleLogoUpload(e, "dark")}
|
||||
style={{ display: "none" }}
|
||||
disabled={uploadingLogoDark}
|
||||
/>
|
||||
</label>
|
||||
<small className="admin-form-hint">
|
||||
PNG, JPEG, GIF nebo WebP, max 5 MB
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{embedded && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.2 }}
|
||||
>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="admin-btn admin-btn-primary"
|
||||
style={{ width: "100%", marginTop: "1rem" }}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Ukládání...
|
||||
</>
|
||||
) : (
|
||||
"Uložit nastavení firmy"
|
||||
)}
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -56,12 +56,6 @@ const TRANSITION_CLASSES: Record<string, string> = {
|
||||
paid: "admin-btn admin-btn-primary",
|
||||
};
|
||||
|
||||
const VAT_OPTIONS = [
|
||||
{ value: 21, label: "21%" },
|
||||
{ value: 12, label: "12%" },
|
||||
{ value: 0, label: "0%" },
|
||||
];
|
||||
|
||||
interface InvoiceItem {
|
||||
id?: number;
|
||||
_key: string;
|
||||
@@ -145,6 +139,7 @@ function SortableInvoiceRow({
|
||||
index,
|
||||
currency,
|
||||
apply_vat,
|
||||
vatOptions,
|
||||
onUpdate,
|
||||
onRemove,
|
||||
canDelete,
|
||||
@@ -153,6 +148,7 @@ function SortableInvoiceRow({
|
||||
index: number;
|
||||
currency: string;
|
||||
apply_vat: boolean;
|
||||
vatOptions: { value: number; label: string }[];
|
||||
onUpdate: (
|
||||
index: number,
|
||||
field: keyof InvoiceItem,
|
||||
@@ -266,7 +262,7 @@ function SortableInvoiceRow({
|
||||
minWidth: "4.5rem",
|
||||
}}
|
||||
>
|
||||
{VAT_OPTIONS.map((o) => (
|
||||
{vatOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
@@ -309,6 +305,7 @@ function SortableInvoiceEditRow({
|
||||
item,
|
||||
index,
|
||||
apply_vat,
|
||||
vatOptions,
|
||||
onUpdate,
|
||||
onRemove,
|
||||
canDelete,
|
||||
@@ -316,6 +313,7 @@ function SortableInvoiceEditRow({
|
||||
item: InvoiceItem;
|
||||
index: number;
|
||||
apply_vat: boolean;
|
||||
vatOptions: { value: number; label: string }[];
|
||||
onUpdate: (index: number, field: string, value: string | number) => void;
|
||||
onRemove: (index: number) => void;
|
||||
canDelete: boolean;
|
||||
@@ -427,7 +425,7 @@ function SortableInvoiceEditRow({
|
||||
minWidth: "4.5rem",
|
||||
}}
|
||||
>
|
||||
{VAT_OPTIONS.map((o) => (
|
||||
{vatOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
@@ -543,6 +541,45 @@ export default function InvoiceDetail() {
|
||||
const [customerSearch, setCustomerSearch] = useState("");
|
||||
const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
|
||||
|
||||
const [companySettings, setCompanySettings] = useState<{
|
||||
default_currency: string;
|
||||
default_vat_rate: number;
|
||||
available_currencies: string[];
|
||||
available_vat_rates: number[];
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch(`${API_BASE}/company-settings`)
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
if (d.success) setCompanySettings(d.data);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const vatOptions = (
|
||||
companySettings?.available_vat_rates || [0, 10, 12, 15, 21]
|
||||
).map((v) => ({
|
||||
value: v,
|
||||
label: `${v}%`,
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
if (companySettings && !isEdit) {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
currency:
|
||||
prev.currency === "CZK"
|
||||
? companySettings.default_currency || "CZK"
|
||||
: prev.currency,
|
||||
vat_rate:
|
||||
prev.vat_rate === 21
|
||||
? (companySettings.default_vat_rate ?? 21)
|
||||
: prev.vat_rate,
|
||||
}));
|
||||
}
|
||||
}, [companySettings, isEdit]);
|
||||
|
||||
const DRAFT_KEY = "boha_invoice_draft";
|
||||
|
||||
const clearDraft = useCallback(() => {
|
||||
@@ -634,13 +671,16 @@ export default function InvoiceDetail() {
|
||||
const orderData = await results[3].json();
|
||||
if (orderData.success) {
|
||||
const order = orderData.data;
|
||||
const vatRate = Number(order.vat_rate) || 21;
|
||||
const vatRate =
|
||||
Number(order.vat_rate) ||
|
||||
(companySettings?.default_vat_rate ?? 21);
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
customer_id: order.customer_id,
|
||||
customer_name: order.customer_name || "",
|
||||
order_id: order.id,
|
||||
currency: order.currency || "CZK",
|
||||
currency:
|
||||
order.currency || companySettings?.default_currency || "CZK",
|
||||
apply_vat: Number(order.apply_vat) || 0,
|
||||
vat_rate: vatRate,
|
||||
}));
|
||||
@@ -963,7 +1003,8 @@ export default function InvoiceDetail() {
|
||||
quantity: Number(item.quantity) || 1,
|
||||
unit: item.unit || "",
|
||||
unit_price: Number(item.unit_price) || 0,
|
||||
vat_rate: Number(item.vat_rate) || 21,
|
||||
vat_rate:
|
||||
Number(item.vat_rate) || (companySettings?.default_vat_rate ?? 21),
|
||||
})),
|
||||
);
|
||||
setEditingItems(true);
|
||||
@@ -988,7 +1029,7 @@ export default function InvoiceDetail() {
|
||||
quantity: 1,
|
||||
unit: "ks",
|
||||
unit_price: 0,
|
||||
vat_rate: 21,
|
||||
vat_rate: companySettings?.default_vat_rate ?? 21,
|
||||
},
|
||||
]);
|
||||
};
|
||||
@@ -1373,9 +1414,18 @@ export default function InvoiceDetail() {
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="CZK">CZK (Kč)</option>
|
||||
<option value="EUR">EUR</option>
|
||||
<option value="USD">USD ($)</option>
|
||||
{(
|
||||
companySettings?.available_currencies || [
|
||||
"CZK",
|
||||
"EUR",
|
||||
"USD",
|
||||
"GBP",
|
||||
]
|
||||
).map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{c}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
<FormField label="Jazyk faktury">
|
||||
@@ -1514,6 +1564,7 @@ export default function InvoiceDetail() {
|
||||
index={index}
|
||||
currency={form.currency}
|
||||
apply_vat={!!form.apply_vat}
|
||||
vatOptions={vatOptions}
|
||||
onUpdate={updateItem}
|
||||
onRemove={removeItem}
|
||||
canDelete={items.length > 1}
|
||||
@@ -1851,6 +1902,7 @@ export default function InvoiceDetail() {
|
||||
item={item}
|
||||
index={index}
|
||||
apply_vat={!!Number(invoice.apply_vat)}
|
||||
vatOptions={vatOptions}
|
||||
onUpdate={updateEditItem}
|
||||
onRemove={removeEditItem}
|
||||
canDelete={editItems.length > 1}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "react";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import ConfirmModal from "../components/ConfirmModal";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
@@ -119,7 +119,11 @@ export default function Invoices() {
|
||||
const alert = useAlert();
|
||||
const { hasPermission } = useAuth();
|
||||
|
||||
const [activeTab, setActiveTab] = useState("issued");
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const activeTab =
|
||||
searchParams.get("tab") === "received" ? "received" : "issued";
|
||||
const setActiveTab = (tab: string) =>
|
||||
setSearchParams({ tab }, { replace: true });
|
||||
const [receivedUploadOpen, setReceivedUploadOpen] = useState(false);
|
||||
const { sort, order, handleSort, activeSort } =
|
||||
useTableSort("invoice_number");
|
||||
|
||||
@@ -190,11 +190,17 @@ export default function Login() {
|
||||
<img
|
||||
src={
|
||||
theme === "dark"
|
||||
? "/images/logo-dark.png"
|
||||
: "/images/logo-light.png"
|
||||
? "/api/admin/company-settings/logo?variant=dark"
|
||||
: "/api/admin/company-settings/logo?variant=light"
|
||||
}
|
||||
alt="Logo"
|
||||
className="admin-login-logo"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).src =
|
||||
theme === "dark"
|
||||
? "/images/logo-dark.png"
|
||||
: "/images/logo-light.png";
|
||||
}}
|
||||
/>
|
||||
<h1 className="admin-login-title">Interní systém</h1>
|
||||
<p className="admin-login-subtitle">Přihlaste se ke svému účtu</p>
|
||||
|
||||
@@ -98,7 +98,7 @@ const emptyForm: OfferForm = {
|
||||
customer_name: "",
|
||||
created_at: new Date().toISOString().split("T")[0],
|
||||
valid_until: "",
|
||||
currency: "EUR",
|
||||
currency: "CZK",
|
||||
language: "EN",
|
||||
vat_rate: 21,
|
||||
apply_vat: false,
|
||||
@@ -327,6 +327,12 @@ export default function OfferDetail() {
|
||||
const [customerOrderNumber, setCustomerOrderNumber] = useState("");
|
||||
const [orderAttachment, setOrderAttachment] = useState<File | null>(null);
|
||||
const [pdfLoading, setPdfLoading] = useState(false);
|
||||
const [companySettings, setCompanySettings] = useState<{
|
||||
default_currency: string;
|
||||
default_vat_rate: number;
|
||||
available_currencies: string[];
|
||||
available_vat_rates: number[];
|
||||
} | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<{
|
||||
user_id: number;
|
||||
username: string;
|
||||
@@ -336,6 +342,31 @@ export default function OfferDetail() {
|
||||
|
||||
useModalLock(showOrderModal);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch(`${API_BASE}/company-settings`)
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
if (d.success) setCompanySettings(d.data);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (companySettings && !isEdit) {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
currency:
|
||||
prev.currency === "EUR"
|
||||
? companySettings.default_currency || "CZK"
|
||||
: prev.currency,
|
||||
vat_rate:
|
||||
prev.vat_rate === 21
|
||||
? (companySettings.default_vat_rate ?? 21)
|
||||
: prev.vat_rate,
|
||||
}));
|
||||
}
|
||||
}, [companySettings, isEdit]);
|
||||
|
||||
const isInvalidated = offerStatus === "invalidated";
|
||||
const isLockedByOther = !!lockedBy;
|
||||
const isExpiredNotInvalidated =
|
||||
@@ -362,9 +393,9 @@ export default function OfferDetail() {
|
||||
valid_until: d.valid_until
|
||||
? String(d.valid_until).substring(0, 10)
|
||||
: "",
|
||||
currency: d.currency || "EUR",
|
||||
currency: d.currency || companySettings?.default_currency || "CZK",
|
||||
language: d.language || "EN",
|
||||
vat_rate: d.vat_rate ?? 21,
|
||||
vat_rate: d.vat_rate ?? companySettings?.default_vat_rate ?? 21,
|
||||
apply_vat: !!d.apply_vat,
|
||||
exchange_rate: d.exchange_rate || "",
|
||||
scope_title: d.scope_title || "",
|
||||
@@ -408,7 +439,7 @@ export default function OfferDetail() {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id, alert, navigate, hasPermission]);
|
||||
}, [id, alert, navigate, hasPermission, companySettings]);
|
||||
|
||||
// Heartbeat to keep lock alive + cleanup on unmount
|
||||
useEffect(() => {
|
||||
@@ -1125,10 +1156,18 @@ export default function OfferDetail() {
|
||||
className="admin-form-select"
|
||||
disabled={isInvalidated || isLockedByOther}
|
||||
>
|
||||
<option value="EUR">EUR</option>
|
||||
<option value="USD">USD</option>
|
||||
<option value="CZK">CZK</option>
|
||||
<option value="GBP">GBP</option>
|
||||
{(
|
||||
companySettings?.available_currencies || [
|
||||
"CZK",
|
||||
"EUR",
|
||||
"USD",
|
||||
"GBP",
|
||||
]
|
||||
).map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{c}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
<FormField label="Jazyk nabídky">
|
||||
@@ -1147,16 +1186,22 @@ export default function OfferDetail() {
|
||||
<div className="offers-form-row-3">
|
||||
<FormField label="Sazba DPH (%)">
|
||||
<div className="flex-row-gap">
|
||||
<input
|
||||
type="number"
|
||||
<select
|
||||
value={form.vat_rate}
|
||||
onChange={(e) =>
|
||||
updateForm("vat_rate", parseFloat(e.target.value) || 0)
|
||||
}
|
||||
className="admin-form-input flex-1"
|
||||
step="0.1"
|
||||
readOnly={isInvalidated || isLockedByOther}
|
||||
/>
|
||||
className="admin-form-select flex-1"
|
||||
disabled={isInvalidated || isLockedByOther}
|
||||
>
|
||||
{(
|
||||
companySettings?.available_vat_rates || [0, 10, 12, 15, 21]
|
||||
).map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}%
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label
|
||||
className="admin-form-checkbox"
|
||||
style={{ whiteSpace: "nowrap" }}
|
||||
|
||||
@@ -324,7 +324,7 @@ export default function Offers() {
|
||||
</p>
|
||||
</div>
|
||||
<div className="admin-page-actions">
|
||||
{hasPermission("offers.settings") && (
|
||||
{hasPermission("settings.manage") && (
|
||||
<Link
|
||||
to="/offers/templates"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function OffersTemplates() {
|
||||
const { hasPermission } = useAuth();
|
||||
const [activeTab, setActiveTab] = useState<"items" | "scopes">("items");
|
||||
|
||||
if (!hasPermission("offers.settings")) return <Forbidden />;
|
||||
if (!hasPermission("settings.manage")) return <Forbidden />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
||||
@@ -21,8 +21,8 @@ const STATUS_CLASSES: Record<string, string> = {
|
||||
unpaid: "admin-badge-invoice-overdue",
|
||||
paid: "admin-badge-invoice-paid",
|
||||
};
|
||||
const CURRENCY_OPTIONS = ["CZK", "EUR", "USD", "GBP"];
|
||||
const VAT_RATE_OPTIONS = [0, 10, 12, 15, 21];
|
||||
const DEFAULT_CURRENCIES = ["CZK", "EUR", "USD", "GBP"];
|
||||
const DEFAULT_VAT_RATES = [0, 10, 12, 15, 21];
|
||||
|
||||
const MONTH_NAMES = [
|
||||
"leden",
|
||||
@@ -124,13 +124,20 @@ function formatCzkWithDetail(
|
||||
return { value: formatMultiCurrency(amounts), detail: null };
|
||||
}
|
||||
|
||||
function emptyMeta(): UploadMeta {
|
||||
interface CompanySettings {
|
||||
default_currency: string;
|
||||
default_vat_rate: number;
|
||||
available_currencies: string[];
|
||||
available_vat_rates: number[];
|
||||
}
|
||||
|
||||
function emptyMeta(settings: CompanySettings | null): UploadMeta {
|
||||
return {
|
||||
supplier_name: "",
|
||||
invoice_number: "",
|
||||
amount: "",
|
||||
currency: "CZK",
|
||||
vat_rate: "21",
|
||||
currency: settings?.default_currency || "CZK",
|
||||
vat_rate: String(settings?.default_vat_rate ?? 21),
|
||||
issue_date: "",
|
||||
due_date: "",
|
||||
notes: "",
|
||||
@@ -168,6 +175,8 @@ export default function ReceivedInvoices({
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const [supplierNames, setSupplierNames] = useState<string[]>([]);
|
||||
const [companySettings, setCompanySettings] =
|
||||
useState<CompanySettings | null>(null);
|
||||
|
||||
const [uploadFiles, setUploadFiles] = useState<File[]>([]);
|
||||
const [uploadMeta, setUploadMeta] = useState<UploadMeta[]>([]);
|
||||
@@ -231,6 +240,22 @@ export default function ReceivedInvoices({
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch(`${API_BASE}/company-settings`)
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
if (d.success) setCompanySettings(d.data);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const currencyOptions =
|
||||
companySettings?.available_currencies || DEFAULT_CURRENCIES;
|
||||
const vatRateOptions =
|
||||
companySettings?.available_vat_rates || DEFAULT_VAT_RATES;
|
||||
const defaultCurrency = companySettings?.default_currency || "CZK";
|
||||
const defaultVatRate = String(companySettings?.default_vat_rate ?? 21);
|
||||
|
||||
// Fetch stats (silent refresh without animation)
|
||||
const refreshStats = useCallback(async () => {
|
||||
try {
|
||||
@@ -292,7 +317,10 @@ export default function ReceivedInvoices({
|
||||
return true;
|
||||
});
|
||||
setUploadFiles((prev) => [...prev, ...valid]);
|
||||
setUploadMeta((prev) => [...prev, ...valid.map(() => emptyMeta())]);
|
||||
setUploadMeta((prev) => [
|
||||
...prev,
|
||||
...valid.map(() => emptyMeta(companySettings)),
|
||||
]);
|
||||
e.target.value = "";
|
||||
};
|
||||
|
||||
@@ -1041,12 +1069,14 @@ export default function ReceivedInvoices({
|
||||
<FormField label="Měna" style={{ width: "90px" }}>
|
||||
<select
|
||||
className="admin-form-select"
|
||||
value={uploadMeta[idx]?.currency || "CZK"}
|
||||
value={
|
||||
uploadMeta[idx]?.currency || defaultCurrency
|
||||
}
|
||||
onChange={(e) =>
|
||||
updateMeta(idx, "currency", e.target.value)
|
||||
}
|
||||
>
|
||||
{CURRENCY_OPTIONS.map((c) => (
|
||||
{currencyOptions.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{c}
|
||||
</option>
|
||||
@@ -1056,12 +1086,14 @@ export default function ReceivedInvoices({
|
||||
<FormField label="DPH %" style={{ width: "90px" }}>
|
||||
<select
|
||||
className="admin-form-select"
|
||||
value={uploadMeta[idx]?.vat_rate || "21"}
|
||||
value={
|
||||
uploadMeta[idx]?.vat_rate || defaultVatRate
|
||||
}
|
||||
onChange={(e) =>
|
||||
updateMeta(idx, "vat_rate", e.target.value)
|
||||
}
|
||||
>
|
||||
{VAT_RATE_OPTIONS.map((r) => (
|
||||
{vatRateOptions.map((r) => (
|
||||
<option key={r} value={String(r)}>
|
||||
{r}%
|
||||
</option>
|
||||
@@ -1085,14 +1117,14 @@ export default function ReceivedInvoices({
|
||||
uploadMeta[idx].amount || "0",
|
||||
);
|
||||
const r = parseFloat(
|
||||
uploadMeta[idx].vat_rate || "21",
|
||||
uploadMeta[idx].vat_rate || defaultVatRate,
|
||||
);
|
||||
return r > 0
|
||||
? Math.round((a - a / (1 + r / 100)) * 100) /
|
||||
100
|
||||
: 0;
|
||||
})(),
|
||||
uploadMeta[idx].currency || "CZK",
|
||||
uploadMeta[idx].currency || defaultCurrency,
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -1255,7 +1287,7 @@ export default function ReceivedInvoices({
|
||||
}
|
||||
disabled={ro}
|
||||
>
|
||||
{CURRENCY_OPTIONS.map((c) => (
|
||||
{currencyOptions.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{c}
|
||||
</option>
|
||||
@@ -1275,7 +1307,7 @@ export default function ReceivedInvoices({
|
||||
}
|
||||
disabled={ro}
|
||||
>
|
||||
{VAT_RATE_OPTIONS.map((r) => (
|
||||
{vatRateOptions.map((r) => (
|
||||
<option key={r} value={String(r)}>
|
||||
{r}%
|
||||
</option>
|
||||
@@ -1296,14 +1328,14 @@ export default function ReceivedInvoices({
|
||||
(() => {
|
||||
const a = parseFloat(editInvoice.amount || "0");
|
||||
const r = parseFloat(
|
||||
editInvoice.vat_rate || "21",
|
||||
editInvoice.vat_rate || defaultVatRate,
|
||||
);
|
||||
return r > 0
|
||||
? Math.round((a - a / (1 + r / 100)) * 100) /
|
||||
100
|
||||
: 0;
|
||||
})(),
|
||||
editInvoice.currency || "CZK",
|
||||
editInvoice.currency || defaultCurrency,
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -89,6 +89,7 @@ export default function TripsAdmin() {
|
||||
const alert = useAlert();
|
||||
const { hasPermission } = useAuth();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const [filterMonth, setFilterMonth] = useState(() =>
|
||||
String(new Date().getMonth() + 1),
|
||||
);
|
||||
@@ -124,13 +125,16 @@ export default function TripsAdmin() {
|
||||
useEffect(() => {
|
||||
const fetchLookups = async () => {
|
||||
try {
|
||||
const [vRes, uRes] = await Promise.all([
|
||||
const [vRes, uRes, csRes] = await Promise.all([
|
||||
apiFetch(`${API_BASE}/vehicles`),
|
||||
apiFetch(`${API_BASE}/users?limit=1000`),
|
||||
apiFetch(`${API_BASE}/company-settings`),
|
||||
]);
|
||||
const vJson = await vRes.json();
|
||||
const uJson = await uRes.json();
|
||||
const csJson = await csRes.json();
|
||||
if (vJson.success) setVehicles(vJson.data);
|
||||
if (csJson.success) setCompanyName(csJson.data.company_name || "");
|
||||
if (uJson.success) {
|
||||
setUsers(
|
||||
uJson.data.map(
|
||||
@@ -886,13 +890,13 @@ export default function TripsAdmin() {
|
||||
<div className="print-header">
|
||||
<div className="print-header-left">
|
||||
<img
|
||||
src="/images/logo-light.png"
|
||||
alt="BOHA"
|
||||
src="/api/admin/company-settings/logo?variant=light"
|
||||
alt=""
|
||||
className="print-logo"
|
||||
/>
|
||||
<div className="print-header-text">
|
||||
<h1>KNIHA JÍZD</h1>
|
||||
<div className="company">BOHA Automation s.r.o.</div>
|
||||
<div className="company">{companyName}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="print-header-right">
|
||||
|
||||
@@ -63,7 +63,7 @@ export const config = {
|
||||
contactTo: process.env.CONTACT_EMAIL_TO || "",
|
||||
contactFrom: process.env.CONTACT_EMAIL_FROM || "",
|
||||
smtpFrom: process.env.SMTP_FROM || "",
|
||||
smtpFromName: process.env.SMTP_FROM_NAME || "BOHA Automation",
|
||||
smtpFromName: process.env.SMTP_FROM_NAME || "",
|
||||
leaveNotify: process.env.LEAVE_NOTIFY_EMAIL || "",
|
||||
invoiceAlert: process.env.INVOICE_ALERT_EMAIL || "",
|
||||
},
|
||||
@@ -75,8 +75,6 @@ export const config = {
|
||||
},
|
||||
|
||||
security: {
|
||||
maxLoginAttempts: 5,
|
||||
lockoutMinutes: 15,
|
||||
bcryptCost: 12,
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -22,8 +22,8 @@ export async function securityHeaders(
|
||||
"Content-Security-Policy",
|
||||
[
|
||||
"default-src 'self'",
|
||||
"script-src 'self' https://unpkg.com",
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://unpkg.com",
|
||||
"script-src 'self'",
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
||||
"font-src 'self' https://fonts.gstatic.com",
|
||||
"img-src 'self' data: blob: https://*.tile.openstreetmap.org",
|
||||
"connect-src 'self' https://nominatim.openstreetmap.org",
|
||||
|
||||
@@ -14,7 +14,7 @@ export default async function bankAccountsRoutes(
|
||||
): Promise<void> {
|
||||
fastify.get(
|
||||
"/",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (_request, reply) => {
|
||||
const accounts = await prisma.bank_accounts.findMany({
|
||||
orderBy: { position: "asc" },
|
||||
@@ -25,7 +25,7 @@ export default async function bankAccountsRoutes(
|
||||
|
||||
fastify.post(
|
||||
"/",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const parsed = parseBody(CreateBankAccountSchema, request.body);
|
||||
if ("error" in parsed) return error(reply, parsed.error, 400);
|
||||
@@ -59,7 +59,7 @@ export default async function bankAccountsRoutes(
|
||||
|
||||
fastify.put<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
@@ -126,7 +126,7 @@ export default async function bankAccountsRoutes(
|
||||
|
||||
fastify.delete<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
|
||||
@@ -5,7 +5,13 @@ import { logAudit } from "../../services/audit";
|
||||
import { success, error } from "../../utils/response";
|
||||
import multipart from "@fastify/multipart";
|
||||
import { parseBody } from "../../schemas/common";
|
||||
import { UpdateCompanySettingsSchema } from "../../schemas/company-settings.schema";
|
||||
import { UpdateCompanySettingsSchema } from "../../schemas/settings.schema";
|
||||
import { invalidateSettingsCache } from "../../services/system-settings";
|
||||
import os from "os";
|
||||
import { config } from "../../config/env";
|
||||
import { NasFileManager } from "../../services/nas-file-manager";
|
||||
import { nasFinancialsManager } from "../../services/nas-financials-manager";
|
||||
import { nasOffersManager } from "../../services/nas-offers-manager";
|
||||
|
||||
/** Encode custom_fields + supplier_field_order into a single JSON blob (matching PHP format) */
|
||||
function encodeCustomFields(
|
||||
@@ -53,27 +59,37 @@ export default async function companySettingsRoutes(
|
||||
): Promise<void> {
|
||||
await fastify.register(multipart, { limits: { fileSize: 5 * 1024 * 1024 } });
|
||||
|
||||
// GET /api/admin/company-settings/logo
|
||||
fastify.get("/logo", { preHandler: requireAuth }, async (_request, reply) => {
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { logo_data: true },
|
||||
});
|
||||
if (!settings?.logo_data) return error(reply, "Logo nenalezeno", 404);
|
||||
// GET /api/admin/company-settings/logo?variant=light|dark
|
||||
fastify.get("/logo", { preHandler: requireAuth }, async (request, reply) => {
|
||||
const query = request.query as Record<string, string>;
|
||||
const variant = query.variant === "dark" ? "dark" : "light";
|
||||
const column = variant === "dark" ? "logo_data_dark" : "logo_data";
|
||||
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { [column]: true },
|
||||
});
|
||||
const buf = settings?.[column] as Buffer | null;
|
||||
if (!buf) return error(reply, "Logo nenalezeno", 404);
|
||||
|
||||
// Detect image type from magic bytes
|
||||
const buf = settings.logo_data;
|
||||
let mime = "image/png";
|
||||
if (buf[0] === 0xff && buf[1] === 0xd8) mime = "image/jpeg";
|
||||
else if (buf[0] === 0x47 && buf[1] === 0x49) mime = "image/gif";
|
||||
|
||||
return reply.type(mime).send(buf);
|
||||
return reply
|
||||
.type(mime)
|
||||
.header("Cache-Control", "public, max-age=3600")
|
||||
.send(buf);
|
||||
});
|
||||
|
||||
// POST /api/admin/company-settings/logo
|
||||
// POST /api/admin/company-settings/logo?variant=light|dark
|
||||
fastify.post(
|
||||
"/logo",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const query = request.query as Record<string, string>;
|
||||
const variant = query.variant === "dark" ? "dark" : "light";
|
||||
const column = variant === "dark" ? "logo_data_dark" : "logo_data";
|
||||
|
||||
const file = await request.file();
|
||||
if (!file) return error(reply, "Nebyl nahrán žádný soubor", 400);
|
||||
|
||||
@@ -92,7 +108,7 @@ export default async function companySettingsRoutes(
|
||||
|
||||
await prisma.company_settings.update({
|
||||
where: { id: existing.id },
|
||||
data: { logo_data: new Uint8Array(buffer), modified_at: new Date() },
|
||||
data: { [column]: new Uint8Array(buffer), modified_at: new Date() },
|
||||
});
|
||||
|
||||
await logAudit({
|
||||
@@ -101,7 +117,7 @@ export default async function companySettingsRoutes(
|
||||
action: "update",
|
||||
entityType: "company_settings",
|
||||
entityId: existing.id,
|
||||
description: "Nahráno logo",
|
||||
description: `Nahráno logo (${variant})`,
|
||||
});
|
||||
return success(reply, null, 200, "Logo nahráno");
|
||||
},
|
||||
@@ -129,6 +145,22 @@ export default async function companySettingsRoutes(
|
||||
order_type_code: true,
|
||||
invoice_type_code: true,
|
||||
require_2fa: true,
|
||||
break_threshold_hours: true,
|
||||
break_duration_short: true,
|
||||
break_duration_long: true,
|
||||
clock_rounding_minutes: true,
|
||||
invoice_alert_email: true,
|
||||
leave_notify_email: true,
|
||||
max_login_attempts: true,
|
||||
lockout_minutes: true,
|
||||
max_requests_per_minute: true,
|
||||
available_vat_rates: true,
|
||||
available_currencies: true,
|
||||
smtp_from: true,
|
||||
smtp_from_name: true,
|
||||
offer_number_pattern: true,
|
||||
order_number_pattern: true,
|
||||
invoice_number_pattern: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -160,6 +192,17 @@ export default async function companySettingsRoutes(
|
||||
order_type_code: true,
|
||||
invoice_type_code: true,
|
||||
require_2fa: true,
|
||||
break_threshold_hours: true,
|
||||
break_duration_short: true,
|
||||
break_duration_long: true,
|
||||
clock_rounding_minutes: true,
|
||||
invoice_alert_email: true,
|
||||
leave_notify_email: true,
|
||||
max_login_attempts: true,
|
||||
lockout_minutes: true,
|
||||
max_requests_per_minute: true,
|
||||
available_vat_rates: true,
|
||||
available_currencies: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -167,25 +210,134 @@ export default async function companySettingsRoutes(
|
||||
// Check if logo exists
|
||||
const logoCheck = await prisma.company_settings.findFirst({
|
||||
where: { id: settings.id },
|
||||
select: { logo_data: true },
|
||||
select: { logo_data: true, logo_data_dark: true },
|
||||
});
|
||||
const has_logo = !!logoCheck?.logo_data;
|
||||
const has_logo_dark = !!logoCheck?.logo_data_dark;
|
||||
|
||||
const { custom_fields, supplier_field_order } = decodeCustomFields(
|
||||
settings.custom_fields as string | null,
|
||||
);
|
||||
|
||||
const pkg = await import("../../../package.json", {
|
||||
assert: { type: "json" },
|
||||
});
|
||||
|
||||
let available_vat_rates: number[] = [0, 10, 12, 15, 21];
|
||||
try {
|
||||
const raw = settings.available_vat_rates as string | null;
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed) && parsed.length > 0)
|
||||
available_vat_rates = parsed;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
let available_currencies: string[] = ["CZK", "EUR", "USD", "GBP"];
|
||||
try {
|
||||
const raw = settings.available_currencies as string | null;
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed) && parsed.length > 0)
|
||||
available_currencies = parsed;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
return success(reply, {
|
||||
...settings,
|
||||
custom_fields,
|
||||
supplier_field_order,
|
||||
available_vat_rates,
|
||||
available_currencies,
|
||||
has_logo,
|
||||
has_logo_dark,
|
||||
app_version: pkg.default.version,
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/admin/company-settings/system-info
|
||||
fastify.get(
|
||||
"/system-info",
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const pkg = await import("../../../package.json", {
|
||||
assert: { type: "json" },
|
||||
});
|
||||
const uptimeSec = process.uptime();
|
||||
const days = Math.floor(uptimeSec / 86400);
|
||||
const hours = Math.floor((uptimeSec % 86400) / 3600);
|
||||
const mins = Math.floor((uptimeSec % 3600) / 60);
|
||||
const uptimeStr =
|
||||
days > 0
|
||||
? `${days}d ${hours}h ${mins}m`
|
||||
: hours > 0
|
||||
? `${hours}h ${mins}m`
|
||||
: `${mins}m`;
|
||||
|
||||
const mem = process.memoryUsage();
|
||||
const totalMem = os.totalmem();
|
||||
const freeMem = os.freemem();
|
||||
|
||||
// DB connection check
|
||||
let dbStatus = "ok";
|
||||
let migrationCount = 0;
|
||||
try {
|
||||
const result = await prisma.$queryRaw<[{ cnt: bigint }]>`
|
||||
SELECT COUNT(*) as cnt FROM _prisma_migrations WHERE finished_at IS NOT NULL
|
||||
`;
|
||||
migrationCount = Number(result[0]?.cnt ?? 0);
|
||||
} catch (err) {
|
||||
dbStatus = "error";
|
||||
request.log.error(err, "DB health check failed");
|
||||
}
|
||||
|
||||
// NAS status
|
||||
const projectNas = new NasFileManager();
|
||||
|
||||
return success(reply, {
|
||||
app_version: pkg.default.version,
|
||||
node_version: process.version,
|
||||
platform: `${os.type()} ${os.release()}`,
|
||||
uptime: uptimeStr,
|
||||
environment: config.appEnv,
|
||||
timezone:
|
||||
process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
memory: {
|
||||
rss: `${Math.round(mem.rss / 1024 / 1024)} MB`,
|
||||
heap_used: `${Math.round(mem.heapUsed / 1024 / 1024)} MB`,
|
||||
heap_total: `${Math.round(mem.heapTotal / 1024 / 1024)} MB`,
|
||||
system_total: `${Math.round(totalMem / 1024 / 1024)} MB`,
|
||||
system_free: `${Math.round(freeMem / 1024 / 1024)} MB`,
|
||||
},
|
||||
database: {
|
||||
status: dbStatus,
|
||||
migrations_applied: migrationCount,
|
||||
},
|
||||
nas: {
|
||||
projects: {
|
||||
configured: projectNas.isConfigured(),
|
||||
path: config.nas.path || "—",
|
||||
},
|
||||
financials: {
|
||||
configured: nasFinancialsManager.isConfigured(),
|
||||
path: config.nas.financialsPath || "—",
|
||||
},
|
||||
offers: {
|
||||
configured: nasOffersManager.isConfigured(),
|
||||
path: config.nas.offersPath || "—",
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.put(
|
||||
"/",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const parsed = parseBody(UpdateCompanySettingsSchema, request.body);
|
||||
if ("error" in parsed) return error(reply, parsed.error, 400);
|
||||
@@ -207,6 +359,13 @@ export default async function companySettingsRoutes(
|
||||
"default_currency",
|
||||
"order_type_code",
|
||||
"invoice_type_code",
|
||||
"invoice_alert_email",
|
||||
"leave_notify_email",
|
||||
"smtp_from",
|
||||
"smtp_from_name",
|
||||
"offer_number_pattern",
|
||||
"order_number_pattern",
|
||||
"invoice_number_pattern",
|
||||
];
|
||||
const bodyRec = body as Record<string, unknown>;
|
||||
for (const f of strFields) {
|
||||
@@ -216,6 +375,24 @@ export default async function companySettingsRoutes(
|
||||
if (body.default_vat_rate !== undefined)
|
||||
data.default_vat_rate = Number(body.default_vat_rate);
|
||||
if (body.require_2fa !== undefined) data.require_2fa = !!body.require_2fa;
|
||||
|
||||
const numFields = [
|
||||
"break_threshold_hours",
|
||||
"break_duration_short",
|
||||
"break_duration_long",
|
||||
"clock_rounding_minutes",
|
||||
"max_login_attempts",
|
||||
"lockout_minutes",
|
||||
"max_requests_per_minute",
|
||||
] as const;
|
||||
for (const f of numFields) {
|
||||
if (bodyRec[f] !== undefined) data[f] = Number(bodyRec[f]);
|
||||
}
|
||||
|
||||
if (body.available_vat_rates !== undefined)
|
||||
data.available_vat_rates = JSON.stringify(body.available_vat_rates);
|
||||
if (body.available_currencies !== undefined)
|
||||
data.available_currencies = JSON.stringify(body.available_currencies);
|
||||
if (
|
||||
body.custom_fields !== undefined ||
|
||||
body.supplier_field_order !== undefined
|
||||
@@ -247,6 +424,8 @@ export default async function companySettingsRoutes(
|
||||
data,
|
||||
});
|
||||
|
||||
invalidateSettingsCache();
|
||||
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
|
||||
@@ -236,7 +236,7 @@ export default async function receivedInvoicesRoutes(
|
||||
try {
|
||||
invoicesMeta = JSON.parse(part.value as string);
|
||||
} catch {
|
||||
/* ignore parse error */
|
||||
// Malformed invoices metadata — ignore, use defaults
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ export default async function rolesRoutes(
|
||||
// GET /api/admin/roles
|
||||
fastify.get(
|
||||
"/",
|
||||
{ preHandler: requirePermission("settings.roles") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const roles = await prisma.roles.findMany({
|
||||
include: {
|
||||
@@ -35,7 +35,7 @@ export default async function rolesRoutes(
|
||||
// GET /api/admin/roles/permissions
|
||||
fastify.get(
|
||||
"/permissions",
|
||||
{ preHandler: requirePermission("settings.roles") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (_request, reply) => {
|
||||
const permissions = await prisma.permissions.findMany({
|
||||
orderBy: { module: "asc" },
|
||||
@@ -47,7 +47,7 @@ export default async function rolesRoutes(
|
||||
// POST /api/admin/roles
|
||||
fastify.post(
|
||||
"/",
|
||||
{ preHandler: requirePermission("settings.roles") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const parsed = parseBody(CreateRoleSchema, request.body);
|
||||
if ("error" in parsed) return error(reply, parsed.error, 400);
|
||||
@@ -86,7 +86,7 @@ export default async function rolesRoutes(
|
||||
// PUT /api/admin/roles/:id
|
||||
fastify.put<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("settings.roles") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
@@ -136,7 +136,7 @@ export default async function rolesRoutes(
|
||||
// DELETE /api/admin/roles/:id
|
||||
fastify.delete<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("settings.roles") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
|
||||
@@ -22,7 +22,7 @@ export default async function scopeTemplatesRoutes(
|
||||
// Legacy ?action= dispatcher for item templates
|
||||
fastify.get(
|
||||
"/",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const query = request.query as Record<string, unknown>;
|
||||
const action = query.action ? String(query.action) : null;
|
||||
@@ -53,7 +53,7 @@ export default async function scopeTemplatesRoutes(
|
||||
// Item template CRUD via ?action=item
|
||||
fastify.post(
|
||||
"/",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const query = request.query as Record<string, unknown>;
|
||||
|
||||
@@ -121,7 +121,7 @@ export default async function scopeTemplatesRoutes(
|
||||
// Item template delete via DELETE ?action=item&id=X
|
||||
fastify.delete(
|
||||
"/",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const query = request.query as Record<string, unknown>;
|
||||
|
||||
@@ -140,7 +140,7 @@ export default async function scopeTemplatesRoutes(
|
||||
|
||||
fastify.get<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
@@ -161,7 +161,7 @@ export default async function scopeTemplatesRoutes(
|
||||
|
||||
fastify.put<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
@@ -208,7 +208,7 @@ export default async function scopeTemplatesRoutes(
|
||||
|
||||
fastify.delete<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("offers.settings") },
|
||||
{ preHandler: requirePermission("settings.manage") },
|
||||
async (request, reply) => {
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
|
||||
@@ -5,6 +5,7 @@ import prisma from "../../config/database";
|
||||
import { requireAuth, requirePermission } from "../../middleware/auth";
|
||||
import { success, error } from "../../utils/response";
|
||||
import { encrypt } from "../../utils/encryption";
|
||||
import { getSystemSettings } from "../../services/system-settings";
|
||||
import { OTPAuth } from "../../utils/totp";
|
||||
import * as OTPAuthLib from "otpauth";
|
||||
import { logAudit } from "../../services/audit";
|
||||
@@ -16,9 +17,18 @@ export default async function totpRoutes(
|
||||
): Promise<void> {
|
||||
// GET - generate new TOTP secret
|
||||
fastify.get("/setup", { preHandler: requireAuth }, async (request, reply) => {
|
||||
const settings = await getSystemSettings();
|
||||
const companyName =
|
||||
(
|
||||
await prisma.company_settings.findFirst({
|
||||
select: { company_name: true },
|
||||
})
|
||||
)?.company_name ||
|
||||
settings.smtp_from_name ||
|
||||
"System";
|
||||
const secret = new OTPAuthLib.Secret();
|
||||
const totp = new OTPAuthLib.TOTP({
|
||||
issuer: "BOHA Automation",
|
||||
issuer: companyName,
|
||||
label: request.authData!.email,
|
||||
secret,
|
||||
algorithm: "SHA1",
|
||||
@@ -153,7 +163,7 @@ export default async function totpRoutes(
|
||||
// GET - check if 2FA is required company-wide
|
||||
fastify.get(
|
||||
"/required",
|
||||
{ preHandler: [requireAuth, requirePermission("settings.security")] },
|
||||
{ preHandler: [requireAuth, requirePermission("settings.manage")] },
|
||||
async (request, reply) => {
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { require_2fa: true },
|
||||
@@ -167,7 +177,7 @@ export default async function totpRoutes(
|
||||
fastify.post(
|
||||
"/required",
|
||||
{
|
||||
preHandler: [requireAuth, requirePermission("settings.security")],
|
||||
preHandler: [requireAuth, requirePermission("settings.manage")],
|
||||
bodyLimit: 10240,
|
||||
},
|
||||
async (request, reply) => {
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const UpdateCompanySettingsSchema = z.object({
|
||||
company_name: z.string().nullish(),
|
||||
street: z.string().nullish(),
|
||||
city: z.string().nullish(),
|
||||
postal_code: z.string().nullish(),
|
||||
country: z.string().nullish(),
|
||||
company_id: z.string().nullish(),
|
||||
vat_id: z.string().nullish(),
|
||||
quotation_prefix: z.string().nullish(),
|
||||
default_currency: z.string().nullish(),
|
||||
order_type_code: z.string().nullish(),
|
||||
invoice_type_code: z.string().nullish(),
|
||||
default_vat_rate: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
require_2fa: z
|
||||
.preprocess((v) => v === true || v === 1 || v === "1", z.boolean())
|
||||
.optional(),
|
||||
custom_fields: z.array(z.any()).optional(),
|
||||
supplier_field_order: z.array(z.any()).optional(),
|
||||
});
|
||||
|
||||
export type UpdateCompanySettingsInput = z.infer<
|
||||
typeof UpdateCompanySettingsSchema
|
||||
>;
|
||||
65
src/schemas/settings.schema.ts
Normal file
65
src/schemas/settings.schema.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const UpdateCompanySettingsSchema = z.object({
|
||||
company_name: z.string().nullish(),
|
||||
street: z.string().nullish(),
|
||||
city: z.string().nullish(),
|
||||
postal_code: z.string().nullish(),
|
||||
country: z.string().nullish(),
|
||||
company_id: z.string().nullish(),
|
||||
vat_id: z.string().nullish(),
|
||||
quotation_prefix: z.string().nullish(),
|
||||
default_currency: z.string().nullish(),
|
||||
order_type_code: z.string().nullish(),
|
||||
invoice_type_code: z.string().nullish(),
|
||||
default_vat_rate: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
require_2fa: z
|
||||
.preprocess((v) => v === true || v === 1 || v === "1", z.boolean())
|
||||
.optional(),
|
||||
break_threshold_hours: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
break_duration_short: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
break_duration_long: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
clock_rounding_minutes: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
invoice_alert_email: z.string().nullish(),
|
||||
leave_notify_email: z.string().nullish(),
|
||||
smtp_from: z.string().nullish(),
|
||||
smtp_from_name: z.string().nullish(),
|
||||
offer_number_pattern: z.string().nullish(),
|
||||
order_number_pattern: z.string().nullish(),
|
||||
invoice_number_pattern: z.string().nullish(),
|
||||
max_login_attempts: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
lockout_minutes: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
max_requests_per_minute: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.optional(),
|
||||
available_vat_rates: z.array(z.number()).optional(),
|
||||
available_currencies: z.array(z.string()).optional(),
|
||||
custom_fields: z.array(z.any()).optional(),
|
||||
supplier_field_order: z.array(z.any()).optional(),
|
||||
});
|
||||
|
||||
export type UpdateCompanySettingsInput = z.infer<
|
||||
typeof UpdateCompanySettingsSchema
|
||||
>;
|
||||
@@ -189,14 +189,14 @@ async function start() {
|
||||
app.log.error(err, "Invoice alert cron failed");
|
||||
}
|
||||
});
|
||||
console.log("Invoice alert cron scheduled (daily 8:00)");
|
||||
app.log.info("Invoice alert cron scheduled (daily 8:00)");
|
||||
}
|
||||
|
||||
// --- Start ---
|
||||
const port = config.isProduction ? config.port : 3000;
|
||||
try {
|
||||
await app.listen({ port, host: config.host });
|
||||
console.log(`Server running on http://${config.host}:${port}`);
|
||||
app.log.info(`Server running on http://${config.host}:${port}`);
|
||||
} catch (err) {
|
||||
app.log.error(err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { attendance_leave_type, Prisma } from "@prisma/client";
|
||||
import prisma from "../config/database";
|
||||
import { getBusinessDaysInMonth } from "../utils/czech-holidays";
|
||||
import { localDateStr } from "../utils/date";
|
||||
import { getSystemSettings } from "./system-settings";
|
||||
|
||||
type AttendanceWithRelations = Prisma.attendanceGetPayload<{
|
||||
include: {
|
||||
@@ -48,13 +49,13 @@ function calcWorkedHours(
|
||||
return Math.max(0, mins) / 60;
|
||||
}
|
||||
|
||||
const roundUp15 = (d: Date) => {
|
||||
const ms = 15 * 60 * 1000;
|
||||
const roundUp = (d: Date, minutes: number) => {
|
||||
const ms = minutes * 60 * 1000;
|
||||
return new Date(Math.ceil(d.getTime() / ms) * ms);
|
||||
};
|
||||
|
||||
const roundDown15 = (d: Date) => {
|
||||
const ms = 15 * 60 * 1000;
|
||||
const roundDown = (d: Date, minutes: number) => {
|
||||
const ms = minutes * 60 * 1000;
|
||||
return new Date(Math.floor(d.getTime() / ms) * ms);
|
||||
};
|
||||
|
||||
@@ -1189,6 +1190,7 @@ export async function createLeave(data: LeaveData, authUserId: number) {
|
||||
}
|
||||
|
||||
export async function punchAction(userId: number, data: PunchData) {
|
||||
const settings = await getSystemSettings();
|
||||
const action = data.punch_action;
|
||||
const now = new Date();
|
||||
const y = now.getFullYear(),
|
||||
@@ -1223,7 +1225,7 @@ export async function punchAction(userId: number, data: PunchData) {
|
||||
return { error: "Máte již aktivní směnu. Nejdříve zaznamenejte odchod." };
|
||||
}
|
||||
|
||||
const arrivalTime = roundUp15(now);
|
||||
const arrivalTime = roundUp(now, settings.clock_rounding_minutes);
|
||||
const record = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
@@ -1257,7 +1259,7 @@ export async function punchAction(userId: number, data: PunchData) {
|
||||
return { error: "Nemáte aktivní směnu." };
|
||||
}
|
||||
|
||||
const departureTime = roundDown15(now);
|
||||
const departureTime = roundDown(now, settings.clock_rounding_minutes);
|
||||
|
||||
const updateData: Record<string, unknown> = {
|
||||
departure_time: departureTime,
|
||||
@@ -1270,9 +1272,12 @@ export async function punchAction(userId: number, data: PunchData) {
|
||||
if (!ongoing.break_start && ongoing.arrival_time) {
|
||||
const shiftMs = departureTime.getTime() - ongoing.arrival_time.getTime();
|
||||
const shiftHours = shiftMs / (1000 * 60 * 60);
|
||||
if (shiftHours > 6) {
|
||||
if (shiftHours > settings.break_threshold_hours) {
|
||||
const midpoint = new Date(ongoing.arrival_time.getTime() + shiftMs / 2);
|
||||
const breakMins = shiftHours > 12 ? 30 : 15;
|
||||
const breakMins =
|
||||
shiftHours > settings.break_threshold_hours * 2
|
||||
? settings.break_duration_long
|
||||
: settings.break_duration_short;
|
||||
updateData.break_start = midpoint;
|
||||
updateData.break_end = new Date(
|
||||
midpoint.getTime() + breakMins * 60 * 1000,
|
||||
@@ -1311,9 +1316,11 @@ export async function punchAction(userId: number, data: PunchData) {
|
||||
return { error: "Nemáte aktivní směnu bez přestávky." };
|
||||
}
|
||||
|
||||
const ms10 = 10 * 60 * 1000;
|
||||
const breakStart = new Date(Math.round(now.getTime() / ms10) * ms10);
|
||||
const breakEnd = new Date(breakStart.getTime() + 30 * 60 * 1000);
|
||||
const msRound = settings.clock_rounding_minutes * 60 * 1000;
|
||||
const breakStart = new Date(Math.round(now.getTime() / msRound) * msRound);
|
||||
const breakEnd = new Date(
|
||||
breakStart.getTime() + settings.break_duration_long * 60 * 1000,
|
||||
);
|
||||
|
||||
await prisma.attendance.update({
|
||||
where: { id: ongoing.id },
|
||||
|
||||
@@ -5,6 +5,7 @@ import { FastifyRequest, FastifyReply } from "fastify";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { AuthData, JwtPayload } from "../types";
|
||||
import { getSystemSettings } from "./system-settings";
|
||||
|
||||
// Pre-computed bcrypt hash for timing-safe comparison when user not found
|
||||
const DUMMY_HASH =
|
||||
@@ -121,14 +122,15 @@ export async function login(
|
||||
|
||||
const passwordValid = await bcrypt.compare(password, user.password_hash);
|
||||
if (!passwordValid) {
|
||||
const settings = await getSystemSettings();
|
||||
const attempts = (user.failed_login_attempts ?? 0) + 1;
|
||||
const updateData: Record<string, unknown> = {
|
||||
failed_login_attempts: attempts,
|
||||
};
|
||||
|
||||
if (attempts >= config.security.maxLoginAttempts) {
|
||||
if (attempts >= settings.max_login_attempts) {
|
||||
updateData.locked_until = new Date(
|
||||
Date.now() + config.security.lockoutMinutes * 60_000,
|
||||
Date.now() + settings.lockout_minutes * 60_000,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { sendMail } from "./mailer";
|
||||
import { localDateCzStr, localDateStr } from "../utils/date";
|
||||
import { getSystemSettings } from "./system-settings";
|
||||
|
||||
interface AlertInvoice {
|
||||
id: number;
|
||||
@@ -31,7 +32,8 @@ function formatAmount(n: number | { toNumber?: () => number }): string {
|
||||
}
|
||||
|
||||
export async function checkInvoiceAlerts(): Promise<void> {
|
||||
const alertEmail = config.email.invoiceAlert;
|
||||
const settings = await getSystemSettings();
|
||||
const alertEmail = settings.invoice_alert_email || config.email.invoiceAlert;
|
||||
if (!alertEmail) return;
|
||||
|
||||
const today = new Date();
|
||||
|
||||
@@ -69,8 +69,8 @@ export async function markOverdueInvoices() {
|
||||
where: { status: "issued", due_date: { lt: new Date() } },
|
||||
data: { status: "overdue" },
|
||||
});
|
||||
} catch {
|
||||
/* silent */
|
||||
} catch (err) {
|
||||
console.error("markOverdueInvoices failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,26 +141,7 @@ export async function listInvoices(params: ListInvoicesParams) {
|
||||
return { data: enriched, total, page, limit };
|
||||
}
|
||||
|
||||
export async function getNextInvoiceNumberFormatted() {
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { invoice_type_code: true },
|
||||
});
|
||||
const typeCode = settings?.invoice_type_code || "81";
|
||||
const yy = String(new Date().getFullYear()).slice(-2);
|
||||
const prefix = `${yy}${typeCode}`;
|
||||
const prefixLen = prefix.length;
|
||||
const likePattern = `${prefix}%`;
|
||||
|
||||
// MAX from existing invoices — same approach as offers/orders
|
||||
const result = await prisma.$queryRaw<[{ max_num: bigint | null }]>`
|
||||
SELECT COALESCE(MAX(CAST(SUBSTRING(invoice_number, ${prefixLen} + 1) AS UNSIGNED)), 0) as max_num
|
||||
FROM invoices
|
||||
WHERE invoice_number LIKE ${likePattern}
|
||||
`;
|
||||
const nextNum = Number(result[0]?.max_num ?? 0) + 1;
|
||||
const number = `${prefix}${String(nextNum).padStart(4, "0")}`;
|
||||
return { number, next_number: number };
|
||||
}
|
||||
export { generateInvoiceNumber as getNextInvoiceNumberFormatted } from "./numbering.service";
|
||||
|
||||
export async function getInvoiceStats(queryMonth?: number, queryYear?: number) {
|
||||
const now = new Date();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { sendMail } from "./mailer";
|
||||
import { config } from "../config/env";
|
||||
import { localDateCzStr, localDateTimeCzStr } from "../utils/date";
|
||||
import { getSystemSettings } from "./system-settings";
|
||||
|
||||
const LEAVE_TYPE_LABELS: Record<string, string> = {
|
||||
vacation: "Dovolená",
|
||||
@@ -38,7 +39,8 @@ export async function notifyNewLeaveRequest(
|
||||
request: LeaveRequestData,
|
||||
employeeName: string,
|
||||
): Promise<void> {
|
||||
const notifyEmail = config.email.leaveNotify;
|
||||
const settings = await getSystemSettings();
|
||||
const notifyEmail = settings.leave_notify_email || config.email.leaveNotify;
|
||||
if (!notifyEmail) return;
|
||||
|
||||
const leaveType = LEAVE_TYPE_LABELS[request.leave_type] || request.leave_type;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import nodemailer from "nodemailer";
|
||||
import { config } from "../config/env";
|
||||
import { getSystemSettings } from "./system-settings";
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
sendmail: true,
|
||||
@@ -12,14 +13,18 @@ export async function sendMail(
|
||||
subject: string,
|
||||
html: string,
|
||||
): Promise<boolean> {
|
||||
const settings = await getSystemSettings();
|
||||
const from =
|
||||
settings.smtp_from ||
|
||||
config.email.smtpFrom ||
|
||||
config.email.contactFrom ||
|
||||
"web@boha-automation.cz";
|
||||
"noreply@example.com";
|
||||
const fromName =
|
||||
settings.smtp_from_name || config.email.smtpFromName || "System";
|
||||
|
||||
try {
|
||||
await transporter.sendMail({
|
||||
from: { name: config.email.smtpFromName, address: from },
|
||||
from: { name: fromName, address: from },
|
||||
to,
|
||||
subject,
|
||||
html,
|
||||
|
||||
@@ -1,19 +1,122 @@
|
||||
import prisma from "../config/database";
|
||||
|
||||
// Default patterns (backward compatible with existing numbers)
|
||||
const DEFAULT_OFFER_PATTERN = "{YYYY}/{PREFIX}/{NNN}";
|
||||
const DEFAULT_ORDER_PATTERN = "{YY}{CODE}{NNNN}";
|
||||
const DEFAULT_INVOICE_PATTERN = "{YY}{CODE}{NNNN}";
|
||||
|
||||
/**
|
||||
* Shared number generator for orders and projects.
|
||||
* Format: YYtypeCode + 4-digit sequence (e.g., 26710003)
|
||||
* Queries MAX from both orders and projects tables.
|
||||
* Apply a numbering pattern template.
|
||||
* Placeholders: {YYYY}, {YY}, {PREFIX}, {CODE}, {N+} (padding = count of N's)
|
||||
*/
|
||||
function applyPattern(
|
||||
pattern: string,
|
||||
vars: { year: number; prefix: string; code: string; seq: number },
|
||||
): string {
|
||||
const yyyy = String(vars.year);
|
||||
const yy = yyyy.slice(-2);
|
||||
|
||||
return pattern.replace(/\{(\w+)\}/g, (match, key: string) => {
|
||||
if (key === "YYYY") return yyyy;
|
||||
if (key === "YY") return yy;
|
||||
if (key === "PREFIX") return vars.prefix;
|
||||
if (key === "CODE") return vars.code;
|
||||
if (/^N+$/.test(key)) return String(vars.seq).padStart(key.length, "0");
|
||||
return match;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the static prefix and sequence position from a pattern.
|
||||
* Used to build SQL LIKE patterns for MAX(seq) queries.
|
||||
*/
|
||||
function buildLikePattern(
|
||||
pattern: string,
|
||||
vars: { year: number; prefix: string; code: string },
|
||||
): { likePattern: string; prefixLen: number } {
|
||||
const yyyy = String(vars.year);
|
||||
const yy = yyyy.slice(-2);
|
||||
|
||||
let staticPrefix = "";
|
||||
let foundSeq = false;
|
||||
const parts = pattern.split(/(\{[^}]+\})/);
|
||||
|
||||
for (const part of parts) {
|
||||
const m = part.match(/^\{(\w+)\}$/);
|
||||
if (!m) {
|
||||
staticPrefix += part;
|
||||
continue;
|
||||
}
|
||||
const key = m[1];
|
||||
if (/^N+$/.test(key)) {
|
||||
foundSeq = true;
|
||||
break;
|
||||
}
|
||||
if (key === "YYYY") staticPrefix += yyyy;
|
||||
else if (key === "YY") staticPrefix += yy;
|
||||
else if (key === "PREFIX") staticPrefix += vars.prefix;
|
||||
else if (key === "CODE") staticPrefix += vars.code;
|
||||
}
|
||||
|
||||
if (!foundSeq) {
|
||||
return { likePattern: staticPrefix + "%", prefixLen: staticPrefix.length };
|
||||
}
|
||||
|
||||
return { likePattern: staticPrefix + "%", prefixLen: staticPrefix.length };
|
||||
}
|
||||
|
||||
async function getSettings() {
|
||||
return prisma.company_settings.findFirst({
|
||||
select: {
|
||||
quotation_prefix: true,
|
||||
order_type_code: true,
|
||||
invoice_type_code: true,
|
||||
offer_number_pattern: true,
|
||||
order_number_pattern: true,
|
||||
invoice_number_pattern: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Next offer/quotation number.
|
||||
*/
|
||||
export async function generateOfferNumber(): Promise<string> {
|
||||
const settings = await getSettings();
|
||||
const pattern = settings?.offer_number_pattern || DEFAULT_OFFER_PATTERN;
|
||||
const prefix = settings?.quotation_prefix || "NA";
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
const { likePattern, prefixLen } = buildLikePattern(pattern, {
|
||||
year,
|
||||
prefix,
|
||||
code: "",
|
||||
});
|
||||
|
||||
const result = await prisma.$queryRaw<[{ max_seq: bigint | null }]>`
|
||||
SELECT COALESCE(MAX(CAST(SUBSTRING(quotation_number, ${prefixLen} + 1) AS UNSIGNED)), 0) as max_seq
|
||||
FROM quotations
|
||||
WHERE quotation_number LIKE ${likePattern}
|
||||
`;
|
||||
const nextNum = Number(result[0]?.max_seq ?? 0) + 1;
|
||||
|
||||
return applyPattern(pattern, { year, prefix, code: "", seq: nextNum });
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared number for orders and projects.
|
||||
*/
|
||||
export async function generateSharedNumber(): Promise<string> {
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { order_type_code: true },
|
||||
const settings = await getSettings();
|
||||
const pattern = settings?.order_number_pattern || DEFAULT_ORDER_PATTERN;
|
||||
const code = settings?.order_type_code || "71";
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
const { likePattern, prefixLen } = buildLikePattern(pattern, {
|
||||
year,
|
||||
prefix: "",
|
||||
code,
|
||||
});
|
||||
const typeCode = settings?.order_type_code || "71";
|
||||
const yy = String(new Date().getFullYear()).slice(-2);
|
||||
const prefix = `${yy}${typeCode}`;
|
||||
const prefixLen = prefix.length;
|
||||
const likePattern = `${prefix}%`;
|
||||
|
||||
const result = await prisma.$queryRaw<[{ max_seq: bigint | null }]>`
|
||||
SELECT COALESCE(MAX(seq), 0) as max_seq FROM (
|
||||
@@ -25,51 +128,53 @@ export async function generateSharedNumber(): Promise<string> {
|
||||
) combined
|
||||
`;
|
||||
const nextNum = Number(result[0]?.max_seq ?? 0) + 1;
|
||||
return `${prefix}${String(nextNum).padStart(4, "0")}`;
|
||||
|
||||
return applyPattern(pattern, { year, prefix: "", code, seq: nextNum });
|
||||
}
|
||||
|
||||
/**
|
||||
* Next offer number. Queries MAX from quotations table.
|
||||
* Format: YEAR/PREFIX/NNN (e.g., 2026/NA/008)
|
||||
* Next invoice number.
|
||||
*/
|
||||
export async function generateOfferNumber(): Promise<string> {
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { quotation_prefix: true },
|
||||
});
|
||||
const prefix = settings?.quotation_prefix || "NA";
|
||||
const year = new Date().getFullYear();
|
||||
const likePattern = `${year}/${prefix}/%`;
|
||||
export async function generateInvoiceNumber(
|
||||
_year?: number,
|
||||
): Promise<{ number: string; next_number: string }> {
|
||||
const settings = await getSettings();
|
||||
const pattern = settings?.invoice_number_pattern || DEFAULT_INVOICE_PATTERN;
|
||||
const code = settings?.invoice_type_code || "81";
|
||||
const year = _year || new Date().getFullYear();
|
||||
|
||||
const result = await prisma.$queryRaw<[{ max_num: bigint | null }]>`
|
||||
SELECT COALESCE(MAX(CAST(SUBSTRING_INDEX(quotation_number, '/', -1) AS UNSIGNED)), 0) as max_num
|
||||
FROM quotations
|
||||
WHERE quotation_number LIKE ${likePattern}
|
||||
const { likePattern, prefixLen } = buildLikePattern(pattern, {
|
||||
year,
|
||||
prefix: "",
|
||||
code,
|
||||
});
|
||||
|
||||
const result = await prisma.$queryRaw<[{ max_seq: bigint | null }]>`
|
||||
SELECT COALESCE(MAX(CAST(SUBSTRING(invoice_number, ${prefixLen} + 1) AS UNSIGNED)), 0) as max_seq
|
||||
FROM invoices
|
||||
WHERE invoice_number LIKE ${likePattern}
|
||||
`;
|
||||
const nextNum = Number(result[0]?.max_num ?? 0) + 1;
|
||||
return `${year}/${prefix}/${String(nextNum).padStart(3, "0")}`;
|
||||
const nextNum = Number(result[0]?.max_seq ?? 0) + 1;
|
||||
|
||||
const number = applyPattern(pattern, {
|
||||
year,
|
||||
prefix: "",
|
||||
code,
|
||||
seq: nextNum,
|
||||
});
|
||||
return { number, next_number: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* Next invoice number via atomic sequence table.
|
||||
*/
|
||||
export async function generateInvoiceNumber(year: number): Promise<number> {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const existing = await tx.number_sequences.findFirst({
|
||||
where: { type: "invoice", year },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
const nextNum = (existing.last_number ?? 0) + 1;
|
||||
await tx.number_sequences.update({
|
||||
where: { id: existing.id },
|
||||
data: { last_number: nextNum },
|
||||
});
|
||||
return nextNum;
|
||||
}
|
||||
|
||||
await tx.number_sequences.create({
|
||||
data: { type: "invoice", year, last_number: 1 },
|
||||
});
|
||||
return 1;
|
||||
/** Preview what a pattern would produce (for settings UI) */
|
||||
export function previewPattern(
|
||||
pattern: string,
|
||||
prefix: string,
|
||||
code: string,
|
||||
): string {
|
||||
return applyPattern(pattern, {
|
||||
year: new Date().getFullYear(),
|
||||
prefix,
|
||||
code,
|
||||
seq: 1,
|
||||
});
|
||||
}
|
||||
|
||||
97
src/services/system-settings.ts
Normal file
97
src/services/system-settings.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import prisma from "../config/database";
|
||||
|
||||
interface SystemSettings {
|
||||
break_threshold_hours: number;
|
||||
break_duration_short: number;
|
||||
break_duration_long: number;
|
||||
clock_rounding_minutes: number;
|
||||
invoice_alert_email: string;
|
||||
leave_notify_email: string;
|
||||
max_login_attempts: number;
|
||||
lockout_minutes: number;
|
||||
max_requests_per_minute: number;
|
||||
default_currency: string;
|
||||
default_vat_rate: number;
|
||||
available_vat_rates: number[];
|
||||
available_currencies: string[];
|
||||
smtp_from: string;
|
||||
smtp_from_name: string;
|
||||
}
|
||||
|
||||
const DEFAULTS: SystemSettings = {
|
||||
break_threshold_hours: 6,
|
||||
break_duration_short: 15,
|
||||
break_duration_long: 30,
|
||||
clock_rounding_minutes: 15,
|
||||
invoice_alert_email: "",
|
||||
leave_notify_email: "",
|
||||
max_login_attempts: 5,
|
||||
lockout_minutes: 15,
|
||||
max_requests_per_minute: 300,
|
||||
default_currency: "CZK",
|
||||
default_vat_rate: 21,
|
||||
available_vat_rates: [0, 10, 12, 15, 21],
|
||||
available_currencies: ["CZK", "EUR", "USD", "GBP"],
|
||||
smtp_from: "",
|
||||
smtp_from_name: "",
|
||||
};
|
||||
|
||||
let cache: SystemSettings | null = null;
|
||||
let cacheTime = 0;
|
||||
const CACHE_TTL = 60_000; // 60 seconds
|
||||
|
||||
export async function getSystemSettings(): Promise<SystemSettings> {
|
||||
if (cache && Date.now() - cacheTime < CACHE_TTL) return cache;
|
||||
|
||||
const row = await prisma.company_settings.findFirst();
|
||||
if (!row) {
|
||||
cache = { ...DEFAULTS };
|
||||
cacheTime = Date.now();
|
||||
return cache;
|
||||
}
|
||||
|
||||
let vatRates = DEFAULTS.available_vat_rates;
|
||||
let currencies = DEFAULTS.available_currencies;
|
||||
try {
|
||||
if (row.available_vat_rates) vatRates = JSON.parse(row.available_vat_rates);
|
||||
} catch {
|
||||
/* keep default */
|
||||
}
|
||||
try {
|
||||
if (row.available_currencies)
|
||||
currencies = JSON.parse(row.available_currencies);
|
||||
} catch {
|
||||
/* keep default */
|
||||
}
|
||||
|
||||
cache = {
|
||||
break_threshold_hours: Number(
|
||||
row.break_threshold_hours ?? DEFAULTS.break_threshold_hours,
|
||||
),
|
||||
break_duration_short:
|
||||
row.break_duration_short ?? DEFAULTS.break_duration_short,
|
||||
break_duration_long:
|
||||
row.break_duration_long ?? DEFAULTS.break_duration_long,
|
||||
clock_rounding_minutes:
|
||||
row.clock_rounding_minutes ?? DEFAULTS.clock_rounding_minutes,
|
||||
invoice_alert_email: row.invoice_alert_email || "",
|
||||
leave_notify_email: row.leave_notify_email || "",
|
||||
max_login_attempts: row.max_login_attempts ?? DEFAULTS.max_login_attempts,
|
||||
lockout_minutes: row.lockout_minutes ?? DEFAULTS.lockout_minutes,
|
||||
max_requests_per_minute:
|
||||
row.max_requests_per_minute ?? DEFAULTS.max_requests_per_minute,
|
||||
default_currency: row.default_currency || DEFAULTS.default_currency,
|
||||
default_vat_rate: Number(row.default_vat_rate ?? DEFAULTS.default_vat_rate),
|
||||
available_vat_rates: vatRates,
|
||||
available_currencies: currencies,
|
||||
smtp_from: row.smtp_from || "",
|
||||
smtp_from_name: row.smtp_from_name || DEFAULTS.smtp_from_name,
|
||||
};
|
||||
cacheTime = Date.now();
|
||||
return cache;
|
||||
}
|
||||
|
||||
export function invalidateSettingsCache(): void {
|
||||
cache = null;
|
||||
cacheTime = 0;
|
||||
}
|
||||
Reference in New Issue
Block a user