Compare commits
5 Commits
f793d4cce6
...
1dc74947f4
| Author | SHA1 | Date | |
|---|---|---|---|
| 1dc74947f4 | |||
| f63e793c88 | |||
| 29a84b899d | |||
| be706a70f8 | |||
| 474b3e762c |
@@ -8,9 +8,108 @@ import {
|
|||||||
files,
|
files,
|
||||||
filetags,
|
filetags,
|
||||||
incominginvoices,
|
incominginvoices,
|
||||||
|
vendors,
|
||||||
} from "../../../db/schema"
|
} from "../../../db/schema"
|
||||||
|
|
||||||
import { eq, and, isNull, not } from "drizzle-orm"
|
import { eq, and, isNull, not, desc } from "drizzle-orm"
|
||||||
|
|
||||||
|
type InvoiceAccount = {
|
||||||
|
account?: number | null
|
||||||
|
description?: string | null
|
||||||
|
taxType?: string | number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizeAccounts = (accounts: unknown): InvoiceAccount[] => {
|
||||||
|
if (!Array.isArray(accounts)) return []
|
||||||
|
return accounts
|
||||||
|
.map((entry: any) => ({
|
||||||
|
account: typeof entry?.account === "number" ? entry.account : null,
|
||||||
|
description: typeof entry?.description === "string" ? entry.description : null,
|
||||||
|
taxType: entry?.taxType ?? null,
|
||||||
|
}))
|
||||||
|
.filter((entry) => entry.account !== null || entry.description || entry.taxType !== null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildLearningContext = (historicalInvoices: any[]) => {
|
||||||
|
if (!historicalInvoices.length) return null
|
||||||
|
|
||||||
|
const vendorProfiles = new Map<number, {
|
||||||
|
vendorName: string
|
||||||
|
paymentTypes: Map<string, number>
|
||||||
|
accountUsage: Map<number, number>
|
||||||
|
sampleDescriptions: string[]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const recentExamples: any[] = []
|
||||||
|
|
||||||
|
for (const invoice of historicalInvoices) {
|
||||||
|
const accounts = normalizeAccounts(invoice.accounts)
|
||||||
|
const vendorId = typeof invoice.vendorId === "number" ? invoice.vendorId : null
|
||||||
|
const vendorName = typeof invoice.vendorName === "string" ? invoice.vendorName : "Unknown"
|
||||||
|
|
||||||
|
if (vendorId) {
|
||||||
|
if (!vendorProfiles.has(vendorId)) {
|
||||||
|
vendorProfiles.set(vendorId, {
|
||||||
|
vendorName,
|
||||||
|
paymentTypes: new Map(),
|
||||||
|
accountUsage: new Map(),
|
||||||
|
sampleDescriptions: [],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const profile = vendorProfiles.get(vendorId)!
|
||||||
|
if (invoice.paymentType) {
|
||||||
|
const key = String(invoice.paymentType)
|
||||||
|
profile.paymentTypes.set(key, (profile.paymentTypes.get(key) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
for (const account of accounts) {
|
||||||
|
if (typeof account.account === "number") {
|
||||||
|
profile.accountUsage.set(account.account, (profile.accountUsage.get(account.account) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (invoice.description && profile.sampleDescriptions.length < 3) {
|
||||||
|
profile.sampleDescriptions.push(String(invoice.description).slice(0, 120))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recentExamples.length < 20) {
|
||||||
|
recentExamples.push({
|
||||||
|
vendorId,
|
||||||
|
vendorName,
|
||||||
|
paymentType: invoice.paymentType ?? null,
|
||||||
|
accounts: accounts.map((entry) => ({
|
||||||
|
account: entry.account,
|
||||||
|
description: entry.description ?? null,
|
||||||
|
taxType: entry.taxType ?? null,
|
||||||
|
})),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const vendorPatterns = Array.from(vendorProfiles.entries())
|
||||||
|
.map(([vendorId, profile]) => {
|
||||||
|
const commonPaymentType = Array.from(profile.paymentTypes.entries())
|
||||||
|
.sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
|
||||||
|
const topAccounts = Array.from(profile.accountUsage.entries())
|
||||||
|
.sort((a, b) => b[1] - a[1])
|
||||||
|
.slice(0, 4)
|
||||||
|
.map(([accountId, count]) => ({ accountId, count }))
|
||||||
|
|
||||||
|
return {
|
||||||
|
vendorId,
|
||||||
|
vendorName: profile.vendorName,
|
||||||
|
commonPaymentType,
|
||||||
|
topAccounts,
|
||||||
|
sampleDescriptions: profile.sampleDescriptions,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.slice(0, 50)
|
||||||
|
|
||||||
|
return JSON.stringify({
|
||||||
|
vendorPatterns,
|
||||||
|
recentExamples,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export function prepareIncomingInvoices(server: FastifyInstance) {
|
export function prepareIncomingInvoices(server: FastifyInstance) {
|
||||||
const processInvoices = async (tenantId:number) => {
|
const processInvoices = async (tenantId:number) => {
|
||||||
@@ -72,13 +171,34 @@ export function prepareIncomingInvoices(server: FastifyInstance) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const historicalInvoices = await server.db
|
||||||
|
.select({
|
||||||
|
vendorId: incominginvoices.vendor,
|
||||||
|
vendorName: vendors.name,
|
||||||
|
paymentType: incominginvoices.paymentType,
|
||||||
|
description: incominginvoices.description,
|
||||||
|
accounts: incominginvoices.accounts,
|
||||||
|
})
|
||||||
|
.from(incominginvoices)
|
||||||
|
.leftJoin(vendors, eq(incominginvoices.vendor, vendors.id))
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(incominginvoices.tenant, tenantId),
|
||||||
|
eq(incominginvoices.archived, false)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.orderBy(desc(incominginvoices.createdAt))
|
||||||
|
.limit(120)
|
||||||
|
|
||||||
|
const learningContext = buildLearningContext(historicalInvoices)
|
||||||
|
|
||||||
// -------------------------------------------------------------
|
// -------------------------------------------------------------
|
||||||
// 3️⃣ Jede Datei einzeln durch GPT jagen & IncomingInvoice erzeugen
|
// 3️⃣ Jede Datei einzeln durch GPT jagen & IncomingInvoice erzeugen
|
||||||
// -------------------------------------------------------------
|
// -------------------------------------------------------------
|
||||||
for (const file of filesRes) {
|
for (const file of filesRes) {
|
||||||
console.log(`Processing file ${file.id} for tenant ${tenantId}`)
|
console.log(`Processing file ${file.id} for tenant ${tenantId}`)
|
||||||
|
|
||||||
const data = await getInvoiceDataFromGPT(server,file, tenantId)
|
const data = await getInvoiceDataFromGPT(server,file, tenantId, learningContext ?? undefined)
|
||||||
|
|
||||||
if (!data) {
|
if (!data) {
|
||||||
server.log.warn(`GPT returned no data for file ${file.id}`)
|
server.log.warn(`GPT returned no data for file ${file.id}`)
|
||||||
|
|||||||
@@ -5,26 +5,33 @@ import swaggerUi from "@fastify/swagger-ui";
|
|||||||
|
|
||||||
export default fp(async (server: FastifyInstance) => {
|
export default fp(async (server: FastifyInstance) => {
|
||||||
await server.register(swagger, {
|
await server.register(swagger, {
|
||||||
mode: "dynamic", // wichtig: generiert echtes OpenAPI JSON
|
mode: "dynamic",
|
||||||
openapi: {
|
openapi: {
|
||||||
info: {
|
info: {
|
||||||
title: "Multi-Tenant API",
|
title: "FEDEO Backend API",
|
||||||
description: "API Dokumentation für dein Backend",
|
description: "OpenAPI specification for the FEDEO backend",
|
||||||
version: "1.0.0",
|
version: "1.0.0",
|
||||||
},
|
},
|
||||||
servers: [{ url: "http://localhost:3000" }],
|
servers: [{ url: "/" }],
|
||||||
|
components: {
|
||||||
|
securitySchemes: {
|
||||||
|
bearerAuth: {
|
||||||
|
type: "http",
|
||||||
|
scheme: "bearer",
|
||||||
|
bearerFormat: "JWT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
await server.register(swaggerUi, {
|
await server.register(swaggerUi, {
|
||||||
routePrefix: "/docs", // UI erreichbar unter http://localhost:3000/docs
|
routePrefix: "/docs",
|
||||||
swagger: {
|
});
|
||||||
info: {
|
|
||||||
title: "Multi-Tenant API",
|
// Stable raw spec path
|
||||||
version: "1.0.0",
|
server.get("/openapi.json", async (_req, reply) => {
|
||||||
},
|
return reply.send(server.swagger());
|
||||||
},
|
|
||||||
exposeRoute: true,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,11 +1,60 @@
|
|||||||
import { FastifyInstance } from "fastify"
|
import { FastifyInstance } from "fastify"
|
||||||
import bcrypt from "bcrypt"
|
import bcrypt from "bcrypt"
|
||||||
import { eq } from "drizzle-orm"
|
import { eq } from "drizzle-orm"
|
||||||
|
import jwt from "jsonwebtoken"
|
||||||
|
import { secrets } from "../../utils/secrets"
|
||||||
|
|
||||||
import { authUsers } from "../../../db/schema" // wichtig: Drizzle Schema importieren!
|
import { authUsers } from "../../../db/schema" // wichtig: Drizzle Schema importieren!
|
||||||
|
|
||||||
export default async function authRoutesAuthenticated(server: FastifyInstance) {
|
export default async function authRoutesAuthenticated(server: FastifyInstance) {
|
||||||
|
|
||||||
|
server.post("/auth/refresh", {
|
||||||
|
schema: {
|
||||||
|
tags: ["Auth"],
|
||||||
|
summary: "Refresh JWT for current authenticated user",
|
||||||
|
response: {
|
||||||
|
200: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
token: { type: "string" },
|
||||||
|
},
|
||||||
|
required: ["token"],
|
||||||
|
},
|
||||||
|
401: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
error: { type: "string" },
|
||||||
|
},
|
||||||
|
required: ["error"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, async (req, reply) => {
|
||||||
|
if (!req.user?.user_id) {
|
||||||
|
return reply.code(401).send({ error: "Unauthorized" })
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = jwt.sign(
|
||||||
|
{
|
||||||
|
user_id: req.user.user_id,
|
||||||
|
email: req.user.email,
|
||||||
|
tenant_id: req.user.tenant_id,
|
||||||
|
},
|
||||||
|
secrets.JWT_SECRET!,
|
||||||
|
{ expiresIn: "6h" }
|
||||||
|
)
|
||||||
|
|
||||||
|
reply.setCookie("token", token, {
|
||||||
|
path: "/",
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
maxAge: 60 * 60 * 6,
|
||||||
|
})
|
||||||
|
|
||||||
|
return { token }
|
||||||
|
})
|
||||||
|
|
||||||
server.post("/auth/password/change", {
|
server.post("/auth/password/change", {
|
||||||
schema: {
|
schema: {
|
||||||
tags: ["Auth"],
|
tags: ["Auth"],
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ export default async function authRoutes(server: FastifyInstance) {
|
|||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
|
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
|
||||||
secure: process.env.NODE_ENV === "production",
|
secure: process.env.NODE_ENV === "production",
|
||||||
maxAge: 60 * 60 * 3,
|
maxAge: 60 * 60 * 6,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { token };
|
return { token };
|
||||||
|
|||||||
@@ -100,20 +100,25 @@ export default async function functionRoutes(server: FastifyInstance) {
|
|||||||
|
|
||||||
server.get('/functions/check-zip/:zip', async (req, reply) => {
|
server.get('/functions/check-zip/:zip', async (req, reply) => {
|
||||||
const { zip } = req.params as { zip: string }
|
const { zip } = req.params as { zip: string }
|
||||||
|
const normalizedZip = String(zip || "").replace(/\D/g, "")
|
||||||
|
|
||||||
if (!zip) {
|
if (normalizedZip.length !== 5) {
|
||||||
return reply.code(400).send({ error: 'ZIP is required' })
|
return reply.code(400).send({ error: 'ZIP must contain exactly 5 digits' })
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
//@ts-ignore
|
const data = await server.db
|
||||||
const data = await server.db.select().from(citys).where(eq(citys.zip,zip))
|
.select()
|
||||||
|
.from(citys)
|
||||||
|
.where(eq(citys.zip, Number(normalizedZip)))
|
||||||
|
|
||||||
|
|
||||||
if (!data) {
|
if (!data.length) {
|
||||||
return reply.code(404).send({ error: 'ZIP not found' })
|
return reply.code(404).send({ error: 'ZIP not found' })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const city = data[0]
|
||||||
|
|
||||||
//districtMap
|
//districtMap
|
||||||
const bundeslaender = [
|
const bundeslaender = [
|
||||||
{ code: 'DE-BW', name: 'Baden-Württemberg' },
|
{ code: 'DE-BW', name: 'Baden-Württemberg' },
|
||||||
@@ -137,9 +142,8 @@ export default async function functionRoutes(server: FastifyInstance) {
|
|||||||
|
|
||||||
|
|
||||||
return reply.send({
|
return reply.send({
|
||||||
...data,
|
...city,
|
||||||
//@ts-ignore
|
state_code: bundeslaender.find(i => i.name === city.countryName)?.code || null
|
||||||
state_code: bundeslaender.find(i => i.name === data.countryName)
|
|
||||||
})
|
})
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err)
|
console.log(err)
|
||||||
|
|||||||
@@ -91,7 +91,8 @@ const InstructionFormat = z.object({
|
|||||||
export const getInvoiceDataFromGPT = async function (
|
export const getInvoiceDataFromGPT = async function (
|
||||||
server: FastifyInstance,
|
server: FastifyInstance,
|
||||||
file: any,
|
file: any,
|
||||||
tenantId: number
|
tenantId: number,
|
||||||
|
learningContext?: string
|
||||||
) {
|
) {
|
||||||
await initOpenAi();
|
await initOpenAi();
|
||||||
|
|
||||||
@@ -188,8 +189,13 @@ export const getInvoiceDataFromGPT = async function (
|
|||||||
"You extract structured invoice data.\n\n" +
|
"You extract structured invoice data.\n\n" +
|
||||||
`VENDORS: ${JSON.stringify(vendorList)}\n` +
|
`VENDORS: ${JSON.stringify(vendorList)}\n` +
|
||||||
`ACCOUNTS: ${JSON.stringify(accountList)}\n\n` +
|
`ACCOUNTS: ${JSON.stringify(accountList)}\n\n` +
|
||||||
|
(learningContext
|
||||||
|
? `HISTORICAL_PATTERNS: ${learningContext}\n\n`
|
||||||
|
: "") +
|
||||||
"Match issuer by name to vendor.id.\n" +
|
"Match issuer by name to vendor.id.\n" +
|
||||||
"Match invoice items to account id based on label/number.\n" +
|
"Match invoice items to account id based on label/number.\n" +
|
||||||
|
"Use historical patterns as soft hints for vendor/account/payment mapping.\n" +
|
||||||
|
"Do not invent values when the invoice text contradicts the hints.\n" +
|
||||||
"Convert dates to YYYY-MM-DD.\n" +
|
"Convert dates to YYYY-MM-DD.\n" +
|
||||||
"Keep invoice items in original order.\n",
|
"Keep invoice items in original order.\n",
|
||||||
},
|
},
|
||||||
|
|||||||
43
frontend/components/SessionRefreshModal.vue
Normal file
43
frontend/components/SessionRefreshModal.vue
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
const auth = useAuthStore()
|
||||||
|
|
||||||
|
const remainingMinutes = computed(() => Math.floor(auth.sessionWarningRemainingSeconds / 60))
|
||||||
|
const remainingSeconds = computed(() => auth.sessionWarningRemainingSeconds % 60)
|
||||||
|
const remainingTimeLabel = computed(() => `${remainingMinutes.value}:${String(remainingSeconds.value).padStart(2, "0")}`)
|
||||||
|
|
||||||
|
const onRefresh = async () => {
|
||||||
|
await auth.refreshSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
const onLogout = async () => {
|
||||||
|
auth.sessionWarningVisible = false
|
||||||
|
await auth.logout()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<UModal v-model="auth.sessionWarningVisible" prevent-close>
|
||||||
|
<UCard>
|
||||||
|
<template #header>
|
||||||
|
<h3 class="text-lg font-semibold">Sitzung läuft bald ab</h3>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<p class="text-sm text-gray-600 dark:text-gray-300">
|
||||||
|
Deine Sitzung endet in
|
||||||
|
<span class="font-semibold">{{ remainingTimeLabel }}</span>.
|
||||||
|
Bitte bestätige, um eingeloggt zu bleiben.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<template #footer>
|
||||||
|
<div class="flex justify-end gap-2">
|
||||||
|
<UButton variant="outline" color="gray" @click="onLogout">
|
||||||
|
Abmelden
|
||||||
|
</UButton>
|
||||||
|
<UButton color="primary" @click="onRefresh">
|
||||||
|
Eingeloggt bleiben
|
||||||
|
</UButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</UCard>
|
||||||
|
</UModal>
|
||||||
|
</template>
|
||||||
@@ -50,12 +50,23 @@ export const useFunctions = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const useZipCheck = async (zip) => {
|
const useZipCheck = async (zip) => {
|
||||||
const returnData = await useNuxtApp().$api(`/api/functions/check-zip/${zip}`, {
|
const normalizedZip = String(zip || "").replace(/\D/g, "")
|
||||||
method: "GET",
|
if (!normalizedZip || normalizedZip.length > 5) {
|
||||||
})
|
return null
|
||||||
|
}
|
||||||
return returnData
|
const lookupZip = normalizedZip.padStart(5, "0")
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await useNuxtApp().$api(`/api/functions/check-zip/${lookupZip}`, {
|
||||||
|
method: "GET",
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
zip: String(data?.zip ?? lookupZip).replace(/\D/g, "").padStart(5, "0")
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -75,5 +86,5 @@ export const useFunctions = () => {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {getWorkingTimesEvaluationData, useNextNumber, useCreateTicket, useBankingGenerateLink, useZipCheck, useBankingCheckInstitutions, useBankingListRequisitions, useCreatePDF,useGetInvoiceData, useSendTelegramNotification}
|
return {getWorkingTimesEvaluationData, useNextNumber, useBankingGenerateLink, useZipCheck, useBankingCheckInstitutions, useBankingListRequisitions, useCreatePDF}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import GlobalMessages from "~/components/GlobalMessages.vue";
|
|||||||
import TenantDropdown from "~/components/TenantDropdown.vue";
|
import TenantDropdown from "~/components/TenantDropdown.vue";
|
||||||
import LabelPrinterButton from "~/components/LabelPrinterButton.vue";
|
import LabelPrinterButton from "~/components/LabelPrinterButton.vue";
|
||||||
import {useCalculatorStore} from '~/stores/calculator'
|
import {useCalculatorStore} from '~/stores/calculator'
|
||||||
|
import SessionRefreshModal from "~/components/SessionRefreshModal.vue";
|
||||||
|
|
||||||
const dataStore = useDataStore()
|
const dataStore = useDataStore()
|
||||||
const colorMode = useColorMode()
|
const colorMode = useColorMode()
|
||||||
@@ -130,6 +131,7 @@ const footerLinks = computed(() => [
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="!auth.loading">
|
<div v-if="!auth.loading">
|
||||||
|
<SessionRefreshModal />
|
||||||
<div v-if="auth.activeTenantData?.locked === 'maintenance_tenant'">
|
<div v-if="auth.activeTenantData?.locked === 'maintenance_tenant'">
|
||||||
<UContainer class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
|
<UContainer class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
|
||||||
<UCard class="max-w-lg text-center p-10">
|
<UCard class="max-w-lg text-center p-10">
|
||||||
|
|||||||
@@ -633,6 +633,27 @@ const removePosition = (id) => {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const normalizeZip = (value) => String(value || "").replace(/\D/g, "")
|
||||||
|
|
||||||
|
const sanitizeAddressZipInput = () => {
|
||||||
|
itemInfo.value.address.zip = normalizeZip(itemInfo.value.address.zip)
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkAddressZip = async () => {
|
||||||
|
const zip = normalizeZip(itemInfo.value.address.zip)
|
||||||
|
itemInfo.value.address.zip = zip
|
||||||
|
|
||||||
|
if (![4, 5].includes(zip.length)) return
|
||||||
|
|
||||||
|
const zipData = await useFunctions().useZipCheck(zip)
|
||||||
|
if (zipData?.zip) {
|
||||||
|
itemInfo.value.address.zip = zipData.zip
|
||||||
|
}
|
||||||
|
if (zipData?.short) {
|
||||||
|
itemInfo.value.address.city = zipData.short
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const findDocumentErrors = computed(() => {
|
const findDocumentErrors = computed(() => {
|
||||||
let errors = []
|
let errors = []
|
||||||
|
|
||||||
@@ -640,15 +661,15 @@ const findDocumentErrors = computed(() => {
|
|||||||
if (itemInfo.value.contact === null) errors.push({message: "Es ist kein Kontakt ausgewählt", type: "info"})
|
if (itemInfo.value.contact === null) errors.push({message: "Es ist kein Kontakt ausgewählt", type: "info"})
|
||||||
if (itemInfo.value.letterhead === null) errors.push({message: "Es ist kein Briefpapier ausgewählt", type: "breaking"})
|
if (itemInfo.value.letterhead === null) errors.push({message: "Es ist kein Briefpapier ausgewählt", type: "breaking"})
|
||||||
if (itemInfo.value.created_by === null || !itemInfo.value.created_by) errors.push({message: "Es ist kein Mitarbeiter ausgewählt", type: "breaking"})
|
if (itemInfo.value.created_by === null || !itemInfo.value.created_by) errors.push({message: "Es ist kein Mitarbeiter ausgewählt", type: "breaking"})
|
||||||
if (itemInfo.value.address.street === null) errors.push({
|
if (!itemInfo.value.address.street) errors.push({
|
||||||
message: "Es ist keine Straße im Adressat angegeben",
|
message: "Es ist keine Straße im Adressat angegeben",
|
||||||
type: "breaking"
|
type: "breaking"
|
||||||
})
|
})
|
||||||
if (itemInfo.value.address.zip === null) errors.push({
|
if (!itemInfo.value.address.zip) errors.push({
|
||||||
message: "Es ist keine Postleitzahl im Adressat angegeben",
|
message: "Es ist keine Postleitzahl im Adressat angegeben",
|
||||||
type: "breaking"
|
type: "breaking"
|
||||||
})
|
})
|
||||||
if (itemInfo.value.address.city === null) errors.push({
|
if (!itemInfo.value.address.city) errors.push({
|
||||||
message: "Es ist keine Stadt im Adressat angegeben",
|
message: "Es ist keine Stadt im Adressat angegeben",
|
||||||
type: "breaking"
|
type: "breaking"
|
||||||
})
|
})
|
||||||
@@ -1893,6 +1914,11 @@ const setRowData = async (row, service = {sellingPriceComposed: {}}, product = {
|
|||||||
<UInput
|
<UInput
|
||||||
class="flex-auto"
|
class="flex-auto"
|
||||||
v-model="itemInfo.address.zip"
|
v-model="itemInfo.address.zip"
|
||||||
|
type="text"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="5"
|
||||||
|
@input="sanitizeAddressZipInput"
|
||||||
|
@change="checkAddressZip"
|
||||||
:placeholder="itemInfo.customer ? customers.find(i => i.id === itemInfo.customer).infoData.zip : 'PLZ'"
|
:placeholder="itemInfo.customer ? customers.find(i => i.id === itemInfo.customer).infoData.zip : 'PLZ'"
|
||||||
:color="itemInfo.address.zip ? 'primary' : 'rose'"
|
:color="itemInfo.address.zip ? 'primary' : 'rose'"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { useDraggable } from '@vueuse/core'
|
|||||||
const dataStore = useDataStore()
|
const dataStore = useDataStore()
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const mode = ref(route.params.mode)
|
const mode = ref(route.params.mode)
|
||||||
|
const toast = useToast()
|
||||||
|
|
||||||
// --- Page Leave Logic ---
|
// --- Page Leave Logic ---
|
||||||
const isModified = ref(false) // Speichert, ob Änderungen vorgenommen wurden
|
const isModified = ref(false) // Speichert, ob Änderungen vorgenommen wurden
|
||||||
@@ -118,25 +119,49 @@ const totalCalculated = computed(() => {
|
|||||||
return { totalNet, totalAmount19Tax, totalAmount7Tax, totalGross }
|
return { totalNet, totalAmount19Tax, totalAmount7Tax, totalGross }
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const hasAmount = (value) => value !== null && value !== undefined && value !== ""
|
||||||
|
const hasValidNumber = (value) => hasAmount(value) && Number.isFinite(Number(value))
|
||||||
|
|
||||||
const recalculateItem = (item, source) => {
|
const recalculateItem = (item, source) => {
|
||||||
const taxRate = Number(taxOptions.value.find(i => i.key === item.taxType)?.percentage || 0);
|
const taxRate = Number(taxOptions.value.find(i => i.key === item.taxType)?.percentage || 0);
|
||||||
|
const calculateFromNet = () => {
|
||||||
if (source === 'net') {
|
if(!hasAmount(item.amountNet)) return
|
||||||
item.amountTax = Number((item.amountNet * (taxRate/100)).toFixed(2))
|
item.amountTax = Number((item.amountNet * (taxRate/100)).toFixed(2))
|
||||||
item.amountGross = Number((Number(item.amountNet) + item.amountTax).toFixed(2))
|
item.amountGross = Number((Number(item.amountNet) + item.amountTax).toFixed(2))
|
||||||
} else if (source === 'gross') {
|
}
|
||||||
|
const calculateFromGross = () => {
|
||||||
|
if(!hasAmount(item.amountGross)) return
|
||||||
item.amountNet = Number((item.amountGross / (1 + taxRate/100)).toFixed(2))
|
item.amountNet = Number((item.amountGross / (1 + taxRate/100)).toFixed(2))
|
||||||
item.amountTax = Number((item.amountGross - item.amountNet).toFixed(2))
|
item.amountTax = Number((item.amountGross - item.amountNet).toFixed(2))
|
||||||
} else if (source === 'taxType') {
|
|
||||||
if(item.amountNet) {
|
|
||||||
item.amountTax = Number((item.amountNet * (taxRate/100)).toFixed(2))
|
|
||||||
item.amountGross = Number((Number(item.amountNet) + item.amountTax).toFixed(2))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (source === 'net') {
|
||||||
|
calculateFromNet()
|
||||||
|
} else if (source === 'gross') {
|
||||||
|
calculateFromGross()
|
||||||
|
} else if (source === 'taxType' || source === 'manual') {
|
||||||
|
if(hasAmount(item.amountNet)) calculateFromNet()
|
||||||
|
else if(hasAmount(item.amountGross)) calculateFromGross()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const moveGrossToNet = (item) => {
|
||||||
|
if(!hasAmount(item.amountGross)) return
|
||||||
|
item.amountNet = Number(item.amountGross)
|
||||||
|
recalculateItem(item, 'net')
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Saving ---
|
// --- Saving ---
|
||||||
const updateIncomingInvoice = async (setBooked = false) => {
|
const updateIncomingInvoice = async (setBooked = false) => {
|
||||||
|
if (setBooked && hasBlockingIncomingInvoiceErrors.value) {
|
||||||
|
toast.add({
|
||||||
|
title: "Buchen nicht möglich",
|
||||||
|
description: "Bitte beheben Sie zuerst die rot markierten Pflichtfehler.",
|
||||||
|
color: "rose"
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
let item = { ...itemInfo.value }
|
let item = { ...itemInfo.value }
|
||||||
delete item.files
|
delete item.files
|
||||||
item.state = setBooked ? "Gebucht" : "Entwurf"
|
item.state = setBooked ? "Gebucht" : "Entwurf"
|
||||||
@@ -148,20 +173,32 @@ const updateIncomingInvoice = async (setBooked = false) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const findIncomingInvoiceErrors = computed(() => {
|
const findIncomingInvoiceErrors = computed(() => {
|
||||||
let errors = []
|
const errors = []
|
||||||
const i = itemInfo.value
|
const i = itemInfo.value
|
||||||
|
|
||||||
if(!i.vendor) errors.push({message: "Es ist kein Lieferant ausgewählt", type: "breaking"})
|
if(!i.vendor) errors.push({message: "Es ist kein Lieferant ausgewählt", type: "breaking"})
|
||||||
if(!i.reference) errors.push({message: "Es ist keine Referenz angegeben", type: "breaking"})
|
if(!i.reference || !String(i.reference).trim()) errors.push({message: "Es ist keine Referenz angegeben", type: "breaking"})
|
||||||
if(!i.date) errors.push({message: "Es ist kein Datum ausgewählt", type: "breaking"})
|
if(!i.date) errors.push({message: "Es ist kein Datum ausgewählt", type: "breaking"})
|
||||||
|
if(!i.accounts || i.accounts.length === 0) errors.push({message: "Es ist keine Position vorhanden", type: "breaking"})
|
||||||
|
|
||||||
i.accounts.forEach((account, idx) => {
|
i.accounts.forEach((account, idx) => {
|
||||||
if(!account.account) errors.push({message: `Pos ${idx+1}: Keine Kategorie`, type: "breaking"})
|
if(!account.account) errors.push({message: `Pos ${idx+1}: Keine Kategorie`, type: "breaking"})
|
||||||
if(account.amountNet === null) errors.push({message: `Pos ${idx+1}: Kein Betrag`, type: "breaking"})
|
if(!hasValidNumber(account.amountNet) && !hasValidNumber(account.amountGross)) {
|
||||||
|
errors.push({message: `Pos ${idx+1}: Kein gültiger Betrag`, type: "breaking"})
|
||||||
|
}
|
||||||
|
if(!account.taxType) errors.push({message: `Pos ${idx+1}: Kein Steuerschlüssel`, type: "breaking"})
|
||||||
|
if(hasValidNumber(account.amountNet) && !hasValidNumber(account.amountTax)) {
|
||||||
|
errors.push({message: `Pos ${idx+1}: Steuerbetrag fehlt, bitte Steuer neu berechnen`, type: "warning"})
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
return errors.sort((a,b) => (a.type === "breaking") ? -1 : 1)
|
const order = { breaking: 0, warning: 1 }
|
||||||
|
return errors.sort((a,b) => order[a.type] - order[b.type])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const blockingIncomingInvoiceErrors = computed(() => findIncomingInvoiceErrors.value.filter(i => i.type === "breaking"))
|
||||||
|
const warningIncomingInvoiceErrors = computed(() => findIncomingInvoiceErrors.value.filter(i => i.type === "warning"))
|
||||||
|
const hasBlockingIncomingInvoiceErrors = computed(() => blockingIncomingInvoiceErrors.value.length > 0)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -194,7 +231,7 @@ const findIncomingInvoiceErrors = computed(() => {
|
|||||||
<UButton
|
<UButton
|
||||||
v-if="mode !== 'show'"
|
v-if="mode !== 'show'"
|
||||||
@click="updateIncomingInvoice(true)"
|
@click="updateIncomingInvoice(true)"
|
||||||
:disabled="findIncomingInvoiceErrors.filter(i => i.type === 'breaking').length > 0"
|
:disabled="hasBlockingIncomingInvoiceErrors"
|
||||||
>
|
>
|
||||||
Speichern & Buchen
|
Speichern & Buchen
|
||||||
</UButton>
|
</UButton>
|
||||||
@@ -249,14 +286,35 @@ const findIncomingInvoiceErrors = computed(() => {
|
|||||||
<UAlert
|
<UAlert
|
||||||
v-if="findIncomingInvoiceErrors.length > 0"
|
v-if="findIncomingInvoiceErrors.length > 0"
|
||||||
title="Prüfung erforderlich"
|
title="Prüfung erforderlich"
|
||||||
:color="findIncomingInvoiceErrors.some(i => i.type === 'breaking') ? 'rose' : 'orange'"
|
:color="hasBlockingIncomingInvoiceErrors ? 'rose' : 'orange'"
|
||||||
variant="soft"
|
variant="soft"
|
||||||
icon="i-heroicons-exclamation-triangle"
|
icon="i-heroicons-exclamation-triangle"
|
||||||
>
|
>
|
||||||
<template #description>
|
<template #description>
|
||||||
<ul class="list-disc list-inside text-sm mt-1">
|
<div class="space-y-3 text-sm mt-1">
|
||||||
<li v-for="(err, idx) in findIncomingInvoiceErrors" :key="idx">{{ err.message }}</li>
|
<div v-if="blockingIncomingInvoiceErrors.length > 0">
|
||||||
</ul>
|
<p class="font-semibold text-rose-700 dark:text-rose-300">Pflichtfehler</p>
|
||||||
|
<ul class="list-disc list-inside mt-1">
|
||||||
|
<li
|
||||||
|
v-for="(err, idx) in blockingIncomingInvoiceErrors"
|
||||||
|
:key="`blocking-${idx}-${err.message}`"
|
||||||
|
>
|
||||||
|
{{ err.message }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div v-if="warningIncomingInvoiceErrors.length > 0">
|
||||||
|
<p class="font-semibold text-orange-700 dark:text-orange-300">Hinweise</p>
|
||||||
|
<ul class="list-disc list-inside mt-1">
|
||||||
|
<li
|
||||||
|
v-for="(err, idx) in warningIncomingInvoiceErrors"
|
||||||
|
:key="`warning-${idx}-${err.message}`"
|
||||||
|
>
|
||||||
|
{{ err.message }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</UAlert>
|
</UAlert>
|
||||||
|
|
||||||
@@ -401,24 +459,35 @@ const findIncomingInvoiceErrors = computed(() => {
|
|||||||
</UFormGroup>
|
</UFormGroup>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="col-span-12 md:col-span-4">
|
<div class="col-span-12 md:col-span-3">
|
||||||
<UFormGroup :label="useNetMode ? 'Betrag (Netto)' : 'Betrag (Brutto)'">
|
<UFormGroup label="Betrag (Netto)">
|
||||||
<UInput
|
<UInput
|
||||||
type="number"
|
type="number"
|
||||||
step="0.01"
|
step="0.01"
|
||||||
:disabled="mode === 'show'"
|
:disabled="mode === 'show' || !useNetMode"
|
||||||
:model-value="useNetMode ? item.amountNet : item.amountGross"
|
:model-value="item.amountNet"
|
||||||
@update:model-value="(val) => {
|
@update:model-value="(val) => { item.amountNet = Number(val); recalculateItem(item, 'net') }"
|
||||||
if(useNetMode) { item.amountNet = Number(val); recalculateItem(item, 'net') }
|
|
||||||
else { item.amountGross = Number(val); recalculateItem(item, 'gross') }
|
|
||||||
}"
|
|
||||||
>
|
>
|
||||||
<template #trailing>€</template>
|
<template #trailing>€</template>
|
||||||
</UInput>
|
</UInput>
|
||||||
</UFormGroup>
|
</UFormGroup>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="col-span-6 md:col-span-4">
|
<div class="col-span-12 md:col-span-3">
|
||||||
|
<UFormGroup label="Betrag (Brutto)">
|
||||||
|
<UInput
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
:disabled="mode === 'show' || useNetMode"
|
||||||
|
:model-value="item.amountGross"
|
||||||
|
@update:model-value="(val) => { item.amountGross = Number(val); recalculateItem(item, 'gross') }"
|
||||||
|
>
|
||||||
|
<template #trailing>€</template>
|
||||||
|
</UInput>
|
||||||
|
</UFormGroup>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-span-6 md:col-span-3">
|
||||||
<UFormGroup label="Steuerschlüssel">
|
<UFormGroup label="Steuerschlüssel">
|
||||||
<USelectMenu
|
<USelectMenu
|
||||||
v-model="item.taxType"
|
v-model="item.taxType"
|
||||||
@@ -431,7 +500,7 @@ const findIncomingInvoiceErrors = computed(() => {
|
|||||||
</UFormGroup>
|
</UFormGroup>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="col-span-6 md:col-span-4">
|
<div class="col-span-6 md:col-span-3">
|
||||||
<UFormGroup label="Steuerbetrag" help="Automatisch berechnet">
|
<UFormGroup label="Steuerbetrag" help="Automatisch berechnet">
|
||||||
<UInput :model-value="item.amountTax" disabled color="gray" >
|
<UInput :model-value="item.amountTax" disabled color="gray" >
|
||||||
<template #trailing>€</template>
|
<template #trailing>€</template>
|
||||||
@@ -439,6 +508,27 @@ const findIncomingInvoiceErrors = computed(() => {
|
|||||||
</UFormGroup>
|
</UFormGroup>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="col-span-12 flex justify-end gap-2">
|
||||||
|
<UButton
|
||||||
|
size="xs"
|
||||||
|
variant="outline"
|
||||||
|
icon="i-heroicons-calculator"
|
||||||
|
:disabled="mode === 'show'"
|
||||||
|
@click="recalculateItem(item, 'manual')"
|
||||||
|
>
|
||||||
|
Steuer berechnen
|
||||||
|
</UButton>
|
||||||
|
<UButton
|
||||||
|
size="xs"
|
||||||
|
variant="soft"
|
||||||
|
icon="i-heroicons-arrow-right"
|
||||||
|
:disabled="mode === 'show' || !hasAmount(item.amountGross)"
|
||||||
|
@click="moveGrossToNet(item)"
|
||||||
|
>
|
||||||
|
Brutto als Netto
|
||||||
|
</UButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="col-span-12">
|
<div class="col-span-12">
|
||||||
<UInput v-model="item.description" :disabled="mode === 'show'" placeholder="Positionstext (optional)" icon="i-heroicons-bars-3-bottom-left" variant="none" class="border-b border-gray-100 dark:border-gray-800" />
|
<UInput v-model="item.description" :disabled="mode === 'show'" placeholder="Positionstext (optional)" icon="i-heroicons-bars-3-bottom-left" variant="none" class="border-b border-gray-100 dark:border-gray-800" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ const profileStore = useProfileStore()
|
|||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const url = useRequestURL()
|
const url = useRequestURL()
|
||||||
const supabase = useSupabaseClient()
|
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
|
||||||
const showAddBankRequisition = ref(false)
|
const showAddBankRequisition = ref(false)
|
||||||
@@ -49,36 +48,45 @@ const generateLink = async (bankId) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const addAccount = async (account) => {
|
const addAccount = async (account) => {
|
||||||
let accountData = {
|
let accountData = {
|
||||||
accountId: account.id,
|
accountId: account.id,
|
||||||
ownerName: account.owner_name,
|
ownerName: account.owner_name,
|
||||||
iban: account.iban,
|
iban: account.iban,
|
||||||
tenant: profileStore.currentTenant,
|
tenant: profileStore.currentTenant,
|
||||||
bankId: account.institution_id
|
bankId: account.institution_id
|
||||||
}
|
}
|
||||||
|
|
||||||
const {data,error} = await supabase.from("bankaccounts").insert(accountData).select()
|
try {
|
||||||
if(error) {
|
// Nutzung von useEntities statt direktem DB-Call
|
||||||
toast.add({title: "Es gab einen Fehler bei hinzufügen des Accounts", color:"rose"})
|
// true als 2. Parameter verhindert den Redirect, da wir im Modal sind
|
||||||
} else if(data) {
|
const res = await useEntities("bankaccounts").create(accountData, true)
|
||||||
toast.add({title: "Account erfolgreich hinzugefügt"})
|
|
||||||
|
if(res) {
|
||||||
|
// useEntities feuert bereits einen Success-Toast ("X hinzugefügt")
|
||||||
|
// Wir laden die Seite neu, um die Buttons im Modal zu aktualisieren (Hinzufügen -> Aktualisieren)
|
||||||
|
await setupPage()
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error)
|
||||||
|
toast.add({title: "Es gab einen Fehler beim Hinzufügen des Accounts", color:"rose"})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateAccount = async (account) => {
|
const updateAccount = async (account) => {
|
||||||
|
|
||||||
let bankaccountId = bankaccounts.value.find(i => i.iban === account.iban).id
|
let bankaccountId = bankaccounts.value.find(i => i.iban === account.iban).id
|
||||||
|
|
||||||
const res = await useEntities("bankaccounts").update(bankaccountId, {accountId: account.id, expired: false})
|
// Fehlerbehandlung analog zu addAccount verbessert
|
||||||
|
try {
|
||||||
|
const res = await useEntities("bankaccounts").update(bankaccountId, {accountId: account.id, expired: false}, true)
|
||||||
|
|
||||||
if(!res) {
|
// useEntities feuert bereits einen Success-Toast
|
||||||
console.log(error)
|
// reqData.value = null // Das würde das Modal leeren, ggf. gewünscht? Im Original war es drin.
|
||||||
toast.add({title: "Es gab einen Fehler bei aktualisieren des Accounts", color:"rose"})
|
setupPage()
|
||||||
} else {
|
} catch (error) {
|
||||||
toast.add({title: "Account erfolgreich aktualisiert"})
|
console.log(error)
|
||||||
reqData.value = null
|
toast.add({title: "Es gab einen Fehler beim Aktualisieren des Accounts", color:"rose"})
|
||||||
setupPage()
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setupPage()
|
setupPage()
|
||||||
@@ -88,23 +96,23 @@ setupPage()
|
|||||||
<UDashboardNavbar title="Bankkonten">
|
<UDashboardNavbar title="Bankkonten">
|
||||||
<template #right>
|
<template #right>
|
||||||
<UButton
|
<UButton
|
||||||
@click="showAddBankRequisition = true"
|
@click="showAddBankRequisition = true"
|
||||||
>
|
>
|
||||||
+ Bankverbindung
|
+ Bankverbindung
|
||||||
</UButton>
|
</UButton>
|
||||||
<USlideover
|
<USlideover
|
||||||
v-model="showAddBankRequisition"
|
v-model="showAddBankRequisition"
|
||||||
>
|
>
|
||||||
<UCard
|
<UCard
|
||||||
class="h-full"
|
class="h-full"
|
||||||
>
|
>
|
||||||
<template #header>
|
<template #header>
|
||||||
<p>Bankverbindung hinzufügen</p>
|
<p>Bankverbindung hinzufügen</p>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<UFormGroup
|
<UFormGroup
|
||||||
label="BIC:"
|
label="BIC:"
|
||||||
class="flex-auto"
|
class="flex-auto"
|
||||||
>
|
>
|
||||||
<InputGroup class="w-full">
|
<InputGroup class="w-full">
|
||||||
<UInput
|
<UInput
|
||||||
@@ -113,7 +121,7 @@ setupPage()
|
|||||||
@keydown.enter="checkBIC"
|
@keydown.enter="checkBIC"
|
||||||
/>
|
/>
|
||||||
<UButton
|
<UButton
|
||||||
@click="checkBIC"
|
@click="checkBIC"
|
||||||
>
|
>
|
||||||
Check
|
Check
|
||||||
</UButton>
|
</UButton>
|
||||||
@@ -121,21 +129,21 @@ setupPage()
|
|||||||
|
|
||||||
</UFormGroup>
|
</UFormGroup>
|
||||||
<UAlert
|
<UAlert
|
||||||
v-if="showAlert && bankData.id && bankData.countries.includes('DE')"
|
v-if="showAlert && bankData.id && bankData.countries.includes('DE')"
|
||||||
title="Bank gefunden"
|
title="Bank gefunden"
|
||||||
icon="i-heroicons-check-circle"
|
icon="i-heroicons-check-circle"
|
||||||
color="primary"
|
color="primary"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
class="mt-3"
|
class="mt-3"
|
||||||
:actions="[{ variant: 'solid', color: 'primary', label: 'Verbinden',click: generateLink }]"
|
:actions="[{ variant: 'solid', color: 'primary', label: 'Verbinden',click: generateLink }]"
|
||||||
/>
|
/>
|
||||||
<UAlert
|
<UAlert
|
||||||
v-else-if="showAlert && !bankData.id"
|
v-else-if="showAlert && !bankData.id"
|
||||||
title="Bank nicht gefunden"
|
title="Bank nicht gefunden"
|
||||||
icon="i-heroicons-x-circle"
|
icon="i-heroicons-x-circle"
|
||||||
color="rose"
|
color="rose"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
class="mt-3"
|
class="mt-3"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
</UCard>
|
</UCard>
|
||||||
@@ -150,6 +158,7 @@ setupPage()
|
|||||||
</template>
|
</template>
|
||||||
<div
|
<div
|
||||||
v-for="account in reqData.accounts"
|
v-for="account in reqData.accounts"
|
||||||
|
:key="account.id"
|
||||||
class="p-2 m-3 flex justify-between"
|
class="p-2 m-3 flex justify-between"
|
||||||
>
|
>
|
||||||
{{account.iban}} - {{account.owner_name}}
|
{{account.iban}} - {{account.owner_name}}
|
||||||
@@ -170,16 +179,9 @@ setupPage()
|
|||||||
</UCard>
|
</UCard>
|
||||||
</UModal>
|
</UModal>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<!-- <UButton @click="setupPage">Setup</UButton>
|
|
||||||
<div v-if="route.query.reqId">
|
|
||||||
{{reqData}}
|
|
||||||
</div>-->
|
|
||||||
|
|
||||||
<UTable
|
<UTable
|
||||||
:rows="bankaccounts"
|
:rows="bankaccounts"
|
||||||
:columns="[
|
:columns="[
|
||||||
{
|
{
|
||||||
key: 'expired',
|
key: 'expired',
|
||||||
label: 'Aktiv'
|
label: 'Aktiv'
|
||||||
@@ -202,10 +204,10 @@ setupPage()
|
|||||||
<span v-if="row.expired" class="text-rose-600">Ausgelaufen</span>
|
<span v-if="row.expired" class="text-rose-600">Ausgelaufen</span>
|
||||||
<span v-else class="text-primary">Aktiv</span>
|
<span v-else class="text-primary">Aktiv</span>
|
||||||
<UButton
|
<UButton
|
||||||
v-if="row.expired"
|
v-if="row.expired"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
class="ml-2"
|
class="ml-2"
|
||||||
@click="generateLink(row.bankId)"
|
@click="generateLink(row.bankId)"
|
||||||
>Aktualisieren</UButton>
|
>Aktualisieren</UButton>
|
||||||
</template>
|
</template>
|
||||||
<template #balance-data="{row}">
|
<template #balance-data="{row}">
|
||||||
|
|||||||
@@ -109,8 +109,11 @@ function recalculateWeeklyHours() {
|
|||||||
|
|
||||||
const checkZip = async () => {
|
const checkZip = async () => {
|
||||||
const zipData = await useFunctions().useZipCheck(profile.value.address_zip)
|
const zipData = await useFunctions().useZipCheck(profile.value.address_zip)
|
||||||
profile.value.address_city = zipData.short
|
if (zipData) {
|
||||||
profile.value.state_code = zipData.state_code
|
profile.value.address_zip = zipData.zip || profile.value.address_zip
|
||||||
|
profile.value.address_city = zipData.short
|
||||||
|
profile.value.state_code = zipData.state_code
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(fetchProfile)
|
onMounted(fetchProfile)
|
||||||
@@ -314,5 +317,3 @@ onMounted(fetchProfile)
|
|||||||
<USkeleton v-if="pending" height="300px" />
|
<USkeleton v-if="pending" height="300px" />
|
||||||
</UDashboardPanelContent>
|
</UDashboardPanelContent>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -12,13 +12,129 @@ export const useAuthStore = defineStore("auth", {
|
|||||||
activeTenantData: null as any,
|
activeTenantData: null as any,
|
||||||
loading: true as boolean,
|
loading: true as boolean,
|
||||||
notLoggedIn: true,
|
notLoggedIn: true,
|
||||||
|
sessionWarningVisible: false,
|
||||||
|
sessionWarningRemainingSeconds: 0,
|
||||||
|
sessionWarningLeadMs: 5 * 60 * 1000,
|
||||||
|
sessionWarningTimer: null as ReturnType<typeof setTimeout> | null,
|
||||||
|
sessionLogoutTimer: null as ReturnType<typeof setTimeout> | null,
|
||||||
|
sessionCountdownTimer: null as ReturnType<typeof setInterval> | null,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
actions: {
|
actions: {
|
||||||
async persist(token) {
|
decodeTokenExpiryMs(token: string) {
|
||||||
|
try {
|
||||||
|
const parts = token.split(".")
|
||||||
|
if (parts.length < 2) return null
|
||||||
|
|
||||||
|
const payload = JSON.parse(atob(parts[1].replace(/-/g, "+").replace(/_/g, "/")))
|
||||||
|
if (!payload?.exp) return null
|
||||||
|
|
||||||
|
return Number(payload.exp) * 1000
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Could not decode token expiry", err)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
clearSessionTimers() {
|
||||||
|
if (!process.client) return
|
||||||
|
|
||||||
|
if (this.sessionWarningTimer) {
|
||||||
|
clearTimeout(this.sessionWarningTimer)
|
||||||
|
this.sessionWarningTimer = null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.sessionLogoutTimer) {
|
||||||
|
clearTimeout(this.sessionLogoutTimer)
|
||||||
|
this.sessionLogoutTimer = null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.sessionCountdownTimer) {
|
||||||
|
clearInterval(this.sessionCountdownTimer)
|
||||||
|
this.sessionCountdownTimer = null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
startSessionCountdown(expiresAtMs: number) {
|
||||||
|
if (!process.client) return
|
||||||
|
|
||||||
|
if (this.sessionCountdownTimer) {
|
||||||
|
clearInterval(this.sessionCountdownTimer)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sessionCountdownTimer = setInterval(() => {
|
||||||
|
const remaining = Math.max(0, Math.ceil((expiresAtMs - Date.now()) / 1000))
|
||||||
|
this.sessionWarningRemainingSeconds = remaining
|
||||||
|
|
||||||
|
if (remaining <= 0 && this.sessionCountdownTimer) {
|
||||||
|
clearInterval(this.sessionCountdownTimer)
|
||||||
|
this.sessionCountdownTimer = null
|
||||||
|
}
|
||||||
|
}, 1000)
|
||||||
|
},
|
||||||
|
|
||||||
|
openSessionWarning(expiresAtMs: number) {
|
||||||
|
this.sessionWarningVisible = true
|
||||||
|
this.sessionWarningRemainingSeconds = Math.max(0, Math.ceil((expiresAtMs - Date.now()) / 1000))
|
||||||
|
this.startSessionCountdown(expiresAtMs)
|
||||||
|
},
|
||||||
|
|
||||||
|
scheduleSessionTimers(token?: string | null) {
|
||||||
|
if (!process.client) return
|
||||||
|
|
||||||
|
const tokenToUse = token || useCookie("token").value
|
||||||
|
|
||||||
|
this.clearSessionTimers()
|
||||||
|
this.sessionWarningVisible = false
|
||||||
|
this.sessionWarningRemainingSeconds = 0
|
||||||
|
|
||||||
|
if (!tokenToUse) return
|
||||||
|
|
||||||
|
const expiresAtMs = this.decodeTokenExpiryMs(tokenToUse)
|
||||||
|
if (!expiresAtMs) return
|
||||||
|
|
||||||
|
const now = Date.now()
|
||||||
|
const msUntilLogout = expiresAtMs - now
|
||||||
|
|
||||||
|
if (msUntilLogout <= 0) {
|
||||||
|
void this.logout()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sessionLogoutTimer = setTimeout(() => {
|
||||||
|
this.sessionWarningVisible = false
|
||||||
|
void this.logout()
|
||||||
|
}, msUntilLogout)
|
||||||
|
|
||||||
|
const msUntilWarning = msUntilLogout - this.sessionWarningLeadMs
|
||||||
|
|
||||||
|
if (msUntilWarning <= 0) {
|
||||||
|
this.openSessionWarning(expiresAtMs)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sessionWarningTimer = setTimeout(() => {
|
||||||
|
this.openSessionWarning(expiresAtMs)
|
||||||
|
}, msUntilWarning)
|
||||||
|
},
|
||||||
|
|
||||||
|
setToken(token: string | null) {
|
||||||
|
useCookie("token").value = token
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
this.clearSessionTimers()
|
||||||
|
this.sessionWarningVisible = false
|
||||||
|
this.sessionWarningRemainingSeconds = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.scheduleSessionTimers(token)
|
||||||
|
},
|
||||||
|
|
||||||
|
async persist(token: string | null) {
|
||||||
|
|
||||||
console.log("On Web")
|
console.log("On Web")
|
||||||
useCookie("token").value = token // persistieren
|
this.setToken(token)
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -74,8 +190,7 @@ export const useAuthStore = defineStore("auth", {
|
|||||||
console.log("Token: " + token)
|
console.log("Token: " + token)
|
||||||
|
|
||||||
// 1. WICHTIG: Token sofort ins Cookie schreiben, damit es persistiert wird
|
// 1. WICHTIG: Token sofort ins Cookie schreiben, damit es persistiert wird
|
||||||
const tokenCookie = useCookie("token")
|
this.setToken(token)
|
||||||
tokenCookie.value = token
|
|
||||||
|
|
||||||
// 2. User Daten laden
|
// 2. User Daten laden
|
||||||
await this.fetchMe(token)
|
await this.fetchMe(token)
|
||||||
@@ -112,19 +227,22 @@ export const useAuthStore = defineStore("auth", {
|
|||||||
this.resetState()
|
this.resetState()
|
||||||
|
|
||||||
// Token löschen
|
// Token löschen
|
||||||
useCookie("token").value = null
|
this.setToken(null)
|
||||||
|
|
||||||
// Nur beim expliziten Logout navigieren wir
|
// Nur beim expliziten Logout navigieren wir
|
||||||
navigateTo("/login")
|
navigateTo("/login")
|
||||||
},
|
},
|
||||||
|
|
||||||
resetState() {
|
resetState() {
|
||||||
|
this.clearSessionTimers()
|
||||||
this.user = null
|
this.user = null
|
||||||
this.permissions = []
|
this.permissions = []
|
||||||
this.profile = null
|
this.profile = null
|
||||||
this.activeTenant = null
|
this.activeTenant = null
|
||||||
this.tenants = []
|
this.tenants = []
|
||||||
this.activeTenantData = null
|
this.activeTenantData = null
|
||||||
|
this.sessionWarningVisible = false
|
||||||
|
this.sessionWarningRemainingSeconds = 0
|
||||||
},
|
},
|
||||||
|
|
||||||
async fetchMe(jwt= null) {
|
async fetchMe(jwt= null) {
|
||||||
@@ -162,6 +280,8 @@ export const useAuthStore = defineStore("auth", {
|
|||||||
this.activeTenantData = me.tenants.find(i => i.id === me.activeTenant)
|
this.activeTenantData = me.tenants.find(i => i.id === me.activeTenant)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.scheduleSessionTimers(tokenToUse)
|
||||||
|
|
||||||
console.log(this)
|
console.log(this)
|
||||||
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -170,12 +290,27 @@ export const useAuthStore = defineStore("auth", {
|
|||||||
|
|
||||||
// Stattdessen nur den State sauber machen und Token löschen
|
// Stattdessen nur den State sauber machen und Token löschen
|
||||||
this.resetState()
|
this.resetState()
|
||||||
useCookie("token").value = null
|
this.setToken(null)
|
||||||
|
|
||||||
// Wir werfen den Fehler nicht weiter, damit initStore normal durchläuft
|
// Wir werfen den Fehler nicht weiter, damit initStore normal durchläuft
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async refreshSession() {
|
||||||
|
try {
|
||||||
|
const { token } = await useNuxtApp().$api("/api/auth/refresh", {
|
||||||
|
method: "POST",
|
||||||
|
})
|
||||||
|
|
||||||
|
this.setToken(token)
|
||||||
|
await this.fetchMe(token)
|
||||||
|
this.sessionWarningVisible = false
|
||||||
|
} catch (err) {
|
||||||
|
console.error("JWT refresh failed", err)
|
||||||
|
await this.logout()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
async switchTenant(tenant_id: string) {
|
async switchTenant(tenant_id: string) {
|
||||||
console.log("Auth switchTenant")
|
console.log("Auth switchTenant")
|
||||||
this.loading = true
|
this.loading = true
|
||||||
@@ -188,7 +323,7 @@ export const useAuthStore = defineStore("auth", {
|
|||||||
const {token} = res
|
const {token} = res
|
||||||
|
|
||||||
|
|
||||||
useCookie("token").value = token // persistieren
|
this.setToken(token)
|
||||||
|
|
||||||
|
|
||||||
await this.init(token)
|
await this.init(token)
|
||||||
|
|||||||
@@ -333,10 +333,14 @@ export const useDataStore = defineStore('data', () => {
|
|||||||
{
|
{
|
||||||
key: "infoData.zip",
|
key: "infoData.zip",
|
||||||
label: "Postleitzahl",
|
label: "Postleitzahl",
|
||||||
inputType: "number",
|
inputType: "text",
|
||||||
inputChangeFunction: async function (row) {
|
inputChangeFunction: async function (row) {
|
||||||
if(row.infoData.zip) {
|
const zip = String(row.infoData.zip || "").replace(/\D/g, "")
|
||||||
row.infoData.city = (await useFunctions().useZipCheck(row.infoData.zip)).short
|
row.infoData.zip = zip
|
||||||
|
if ([4, 5].includes(zip.length)) {
|
||||||
|
const zipData = await useFunctions().useZipCheck(zip)
|
||||||
|
row.infoData.zip = zipData?.zip || row.infoData.zip
|
||||||
|
row.infoData.city = zipData?.short || row.infoData.city
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
disabledInTable: true,
|
disabledInTable: true,
|
||||||
@@ -1291,11 +1295,15 @@ export const useDataStore = defineStore('data', () => {
|
|||||||
{
|
{
|
||||||
key: "infoData.zip",
|
key: "infoData.zip",
|
||||||
label: "Postleitzahl",
|
label: "Postleitzahl",
|
||||||
inputType: "number",
|
inputType: "text",
|
||||||
disabledInTable: true,
|
disabledInTable: true,
|
||||||
inputChangeFunction: async function (row) {
|
inputChangeFunction: async function (row) {
|
||||||
if(row.infoData.zip) {
|
const zip = String(row.infoData.zip || "").replace(/\D/g, "")
|
||||||
row.infoData.city = (await useFunctions().useZipCheck(row.infoData.zip)).short
|
row.infoData.zip = zip
|
||||||
|
if ([4, 5].includes(zip.length)) {
|
||||||
|
const zipData = await useFunctions().useZipCheck(zip)
|
||||||
|
row.infoData.zip = zipData?.zip || row.infoData.zip
|
||||||
|
row.infoData.city = zipData?.short || row.infoData.city
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1474,12 +1482,16 @@ export const useDataStore = defineStore('data', () => {
|
|||||||
{
|
{
|
||||||
key: "info_data.zip",
|
key: "info_data.zip",
|
||||||
label: "Postleitzahl",
|
label: "Postleitzahl",
|
||||||
inputType: "number",
|
inputType: "text",
|
||||||
disabledInTable: true,
|
disabledInTable: true,
|
||||||
inputColumn: "Ort",
|
inputColumn: "Ort",
|
||||||
inputChangeFunction: async function (row) {
|
inputChangeFunction: async function (row) {
|
||||||
if(row.infoData.zip) {
|
const zip = String(row.info_data.zip || "").replace(/\D/g, "")
|
||||||
row.infoData.city = (await useFunctions().useZipCheck(row.infoData.zip)).short
|
row.info_data.zip = zip
|
||||||
|
if ([4, 5].includes(zip.length)) {
|
||||||
|
const zipData = await useFunctions().useZipCheck(zip)
|
||||||
|
row.info_data.zip = zipData?.zip || row.info_data.zip
|
||||||
|
row.info_data.city = zipData?.short || row.info_data.city
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user