feat(libra): wire up income submission flow

Adds the frontend pair to libra's new POST /entries/income endpoint:
SUBMIT_INCOME in PermissionType, IncomeEntry/IncomeEntryRequest types,
ExpensesAPI.submitIncome wrapping the new endpoint, and the AddIncome
view collecting description / amount / revenue account / payment-method
account / currency / reference. Mirrors the existing expense flow so
non-admin users can log income on behalf of the organization for
super-user review.
This commit is contained in:
Padreug 2026-05-16 23:16:42 +02:00
commit 31cefac183
3 changed files with 423 additions and 31 deletions

View file

@ -1,31 +1,44 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { Button } from '@/components/ui/button'
import { TrendingUp, Info } from 'lucide-vue-next'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
interface Emits {
(e: 'close'): void
}
const emit = defineEmits<Emits>()
const { t } = useI18n()
function handleClose() {
emit('close')
}
</script>
<template> <template>
<Dialog :open="true" @update:open="(open) => !open && handleClose()"> <Dialog :open="true" @update:open="(open) => !open && handleDialogClose()">
<DialogContent class="max-w-md"> <DialogContent class="max-w-2xl max-h-[85vh] overflow-hidden flex flex-col p-0 gap-0 top-[5%] translate-y-0 sm:top-[5%] sm:translate-y-0">
<DialogHeader> <!-- Success State -->
<div v-if="showSuccessDialog" class="flex flex-col items-center justify-center p-8 space-y-6">
<div class="rounded-full bg-green-100 dark:bg-green-900/20 p-4">
<CheckCircle2 class="h-12 w-12 text-green-600 dark:text-green-400" />
</div>
<div class="text-center space-y-3">
<h2 class="text-2xl font-bold">Income Submitted Successfully!</h2>
<div class="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-orange-100 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800">
<Clock class="h-4 w-4 text-orange-600 dark:text-orange-400" />
<span class="text-sm font-medium text-orange-700 dark:text-orange-300">
Pending Admin Approval
</span>
</div>
<p class="text-muted-foreground">
Your income entry has been submitted successfully. An administrator will review and approve it shortly.
</p>
<p class="text-sm text-muted-foreground">
You can track the approval status in your transactions page.
</p>
</div>
<div class="flex flex-col sm:flex-row gap-3 w-full max-w-sm">
<Button variant="outline" @click="closeSuccessDialog" class="flex-1">
Close
</Button>
<Button @click="goToTransactions" class="flex-1">
<Receipt class="h-4 w-4 mr-2" />
View My Transactions
</Button>
</div>
</div>
<!-- Form State -->
<template v-else>
<DialogHeader class="px-6 pt-6 pb-4 border-b shrink-0">
<DialogTitle class="flex items-center gap-2"> <DialogTitle class="flex items-center gap-2">
<TrendingUp class="h-5 w-5 text-green-600 dark:text-green-400" /> <TrendingUp class="h-5 w-5 text-green-600 dark:text-green-400" />
<span>{{ t('libra.income.title') }}</span> <span>{{ t('libra.income.title') }}</span>
@ -35,18 +48,337 @@ function handleClose() {
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<!-- Placeholder content --> <div class="flex-1 overflow-y-auto px-6 py-4 space-y-4 min-h-0">
<div class="flex flex-col items-center py-8 space-y-4"> <!-- Step indicator -->
<div class="rounded-full bg-muted p-4"> <div class="flex items-center justify-center gap-2 mb-4">
<Info class="h-8 w-8 text-muted-foreground" /> <div
:class="[
'flex items-center justify-center w-8 h-8 rounded-full font-medium text-sm transition-colors',
currentStep === 1
? 'bg-primary text-primary-foreground'
: selectedRevenueAccount
? 'bg-primary/20 text-primary'
: 'bg-muted text-muted-foreground'
]"
>
1
</div> </div>
<p class="text-sm text-muted-foreground text-center max-w-xs"> <div class="w-12 h-px bg-border" />
{{ t('libra.income.notAvailable') }} <div
:class="[
'flex items-center justify-center w-8 h-8 rounded-full font-medium text-sm transition-colors',
currentStep === 2
? 'bg-primary text-primary-foreground'
: 'bg-muted text-muted-foreground'
]"
>
2
</div>
</div>
<!-- Step 1: Revenue Account Selection -->
<div v-if="currentStep === 1">
<p class="text-sm text-muted-foreground mb-4">
{{ t('libra.income.selectAccount') }}
</p> </p>
<Button variant="outline" @click="handleClose"> <AccountSelector
Close v-model="selectedRevenueAccount"
root-account="Income"
@account-selected="handleRevenueAccountSelected"
/>
</div>
<!-- Step 2: Income Details -->
<div v-if="currentStep === 2">
<form @submit="onSubmit" class="space-y-4">
<FormField v-slot="{ componentField }" name="description">
<FormItem>
<FormLabel>Description *</FormLabel>
<FormControl>
<Textarea
placeholder="e.g., Workshop fee, Donation, Service revenue"
v-bind="componentField"
rows="3"
/>
</FormControl>
<FormDescription>Describe the source of this income</FormDescription>
<FormMessage />
</FormItem>
</FormField>
<FormField v-slot="{ componentField }" name="amount">
<FormItem>
<FormLabel>Amount *</FormLabel>
<FormControl>
<Input
type="number"
placeholder="0.00"
v-bind="componentField"
min="0.01"
step="0.01"
/>
</FormControl>
<FormDescription>Amount in selected currency</FormDescription>
<FormMessage />
</FormItem>
</FormField>
<FormField v-slot="{ componentField }" name="currency">
<FormItem>
<FormLabel>Currency *</FormLabel>
<Select v-bind="componentField">
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select currency" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem v-for="currency in availableCurrencies" :key="currency" :value="currency">
{{ currency }}
</SelectItem>
</SelectContent>
</Select>
<FormDescription>Currency for this income</FormDescription>
<FormMessage />
</FormItem>
</FormField>
<FormField v-slot="{ componentField }" name="paymentMethodAccount">
<FormItem>
<FormLabel>Received into *</FormLabel>
<Select v-bind="componentField">
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select asset account" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem
v-for="acc in assetAccounts"
:key="acc.id"
:value="acc.name"
>
{{ acc.name }}
</SelectItem>
</SelectContent>
</Select>
<FormDescription>Where the funds were received (Cash, Bank, Lightning, etc.)</FormDescription>
<FormMessage />
</FormItem>
</FormField>
<FormField v-slot="{ componentField }" name="reference">
<FormItem>
<FormLabel>Reference</FormLabel>
<FormControl>
<Input placeholder="e.g., Invoice #123, Receipt #456" v-bind="componentField" />
</FormControl>
<FormDescription>Optional reference number or note</FormDescription>
<FormMessage />
</FormItem>
</FormField>
<div class="p-3 rounded-lg bg-muted/50">
<div class="flex items-center gap-2 mb-1">
<span class="text-sm text-muted-foreground">Revenue account:</span>
<Badge variant="secondary" class="font-mono">{{ selectedRevenueAccount?.name }}</Badge>
</div>
<p v-if="selectedRevenueAccount?.description" class="text-xs text-muted-foreground">
{{ selectedRevenueAccount.description }}
</p>
</div>
<div class="flex items-center gap-2 pt-2 pb-6">
<Button
type="button"
variant="outline"
@click="currentStep = 1"
:disabled="isSubmitting"
class="flex-1"
>
<ChevronLeft class="h-4 w-4 mr-1" />
Back
</Button>
<Button type="submit" :disabled="isSubmitting || !isFormValid" class="flex-1">
<Loader2 v-if="isSubmitting" class="h-4 w-4 mr-2 animate-spin" />
<span>{{ isSubmitting ? 'Submitting...' : t('libra.income.submitIncome') }}</span>
</Button> </Button>
</div> </div>
</form>
</div>
</div>
</template>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</template> </template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import * as z from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import {
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { TrendingUp, ChevronLeft, Loader2, CheckCircle2, Receipt, Clock } from 'lucide-vue-next'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import { useAuth } from '@/composables/useAuthService'
import { useToast } from '@/core/composables/useToast'
import type { ExpensesAPI } from '@/modules/expenses/services/ExpensesAPI'
import type { Account } from '@/modules/expenses/types'
import AccountSelector from '@/modules/expenses/components/AccountSelector.vue'
interface Emits {
(e: 'close'): void
}
const emit = defineEmits<Emits>()
const expensesAPI = injectService<ExpensesAPI>(SERVICE_TOKENS.EXPENSES_API)
const { user } = useAuth()
const toast = useToast()
const router = useRouter()
const { t } = useI18n()
const currentStep = ref(1)
const selectedRevenueAccount = ref<Account | null>(null)
const isSubmitting = ref(false)
const availableCurrencies = ref<string[]>([])
const assetAccounts = ref<Account[]>([])
const showSuccessDialog = ref(false)
const formSchema = toTypedSchema(
z.object({
description: z.string().min(1, 'Description is required').max(500, 'Description too long'),
amount: z.coerce.number().min(0.01, 'Amount must be at least 0.01'),
currency: z.string().min(1, 'Currency is required'),
paymentMethodAccount: z.string().min(1, 'Payment method is required'),
reference: z.string().max(100, 'Reference too long').optional(),
})
)
const form = useForm({
validationSchema: formSchema,
initialValues: {
description: '',
amount: 0,
currency: '',
paymentMethodAccount: '',
reference: '',
}
})
const { resetForm, meta } = form
const isFormValid = computed(() => meta.value.valid)
onMounted(async () => {
try {
const wallet = user.value?.wallets?.[0]
if (!wallet || !wallet.inkey) {
console.warn('[AddIncome] No wallet available for loading data')
return
}
const currencies = await expensesAPI.getCurrencies()
availableCurrencies.value = currencies
const defaultCurrency = await expensesAPI.getDefaultCurrency()
const initialCurrency = defaultCurrency || currencies[0] || 'EUR'
form.setFieldValue('currency', initialCurrency)
const allAccounts = await expensesAPI.getAccounts(wallet.inkey, false, true)
assetAccounts.value = allAccounts.filter(
(a) => a.name === 'Assets' || a.name.startsWith('Assets:')
)
} catch (error) {
console.error('[AddIncome] Failed to load data:', error)
toast.error('Failed to load form data', { description: 'Please check your connection and try again' })
}
})
function handleRevenueAccountSelected(account: Account) {
selectedRevenueAccount.value = account
currentStep.value = 2
}
const onSubmit = form.handleSubmit(async (values) => {
if (!selectedRevenueAccount.value) {
toast.error('No account selected', { description: 'Please select a revenue account first' })
return
}
const wallet = user.value?.wallets?.[0]
if (!wallet || !wallet.inkey) {
toast.error('No wallet available', { description: 'Please log in to submit income' })
return
}
isSubmitting.value = true
try {
await expensesAPI.submitIncome(wallet.inkey, {
description: values.description,
amount: values.amount,
revenue_account: selectedRevenueAccount.value.name,
payment_method_account: values.paymentMethodAccount,
currency: values.currency,
reference: values.reference,
})
showSuccessDialog.value = true
resetForm()
selectedRevenueAccount.value = null
currentStep.value = 1
} catch (error) {
console.error('[AddIncome] Error submitting income:', error)
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
toast.error('Submission failed', { description: errorMessage })
} finally {
isSubmitting.value = false
}
})
function goToTransactions() {
showSuccessDialog.value = false
emit('close')
router.push('/expenses/transactions')
}
function closeSuccessDialog() {
showSuccessDialog.value = false
emit('close')
}
function handleDialogClose() {
if (showSuccessDialog.value) {
closeSuccessDialog()
} else {
emit('close')
}
}
</script>

View file

@ -7,6 +7,8 @@ import type {
Account, Account,
ExpenseEntryRequest, ExpenseEntryRequest,
ExpenseEntry, ExpenseEntry,
IncomeEntryRequest,
IncomeEntry,
AccountNode, AccountNode,
UserInfo, UserInfo,
AccountPermission, AccountPermission,
@ -188,6 +190,33 @@ export class ExpensesAPI extends BaseService {
} }
} }
/**
* Submit income entry to libra
*/
async submitIncome(walletKey: string, request: IncomeEntryRequest): Promise<IncomeEntry> {
try {
const response = await fetch(`${this.baseUrl}/libra/api/v1/entries/income`, {
method: 'POST',
headers: this.getHeaders(walletKey),
body: JSON.stringify(request),
signal: AbortSignal.timeout(this.config?.apiConfig?.timeout || 30000)
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
const errorMessage =
errorData.detail || `Failed to submit income: ${response.statusText}`
throw new Error(errorMessage)
}
const entry = await response.json()
return entry as IncomeEntry
} catch (error) {
console.error('[ExpensesAPI] Error submitting income:', error)
throw error
}
}
/** /**
* Get user's expense entries * Get user's expense entries
*/ */

View file

@ -43,6 +43,7 @@ export interface AccountWithPermissions extends Account {
export enum PermissionType { export enum PermissionType {
READ = 'read', READ = 'read',
SUBMIT_EXPENSE = 'submit_expense', SUBMIT_EXPENSE = 'submit_expense',
SUBMIT_INCOME = 'submit_income',
MANAGE = 'manage' MANAGE = 'manage'
} }
@ -78,6 +79,36 @@ export interface ExpenseEntry {
status: 'pending' | 'approved' | 'rejected' | 'void' status: 'pending' | 'approved' | 'rejected' | 'void'
} }
/**
* Income entry request payload
*/
export interface IncomeEntryRequest {
description: string
amount: number
revenue_account: string
payment_method_account: string
currency: string
reference?: string
entry_date?: string
}
/**
* Income entry response from libra API
*/
export interface IncomeEntry {
id: string
journal_id: string
description: string
amount: number
revenue_account: string
payment_method_account: string
currency: string
reference?: string
entry_date: string
created_at: string
status: 'pending' | 'approved' | 'rejected' | 'void'
}
/** /**
* Hierarchical account tree node for UI rendering * Hierarchical account tree node for UI rendering
*/ */