@innertia-solutions/innertia-nuxt 0.1.92 → 0.1.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ <script setup lang="ts">
2
+ import { IconDownload, IconCoin } from '@tabler/icons-vue'
3
+ import { formatMoney, formatDate, movementLabel, AGING_BUCKETS, errorMessage } from '../../composables/useBilling/internal/billing'
4
+
5
+ /*
6
+ * Billing.AccountStatement — estado de cuenta: charges, credits and running balance (opening balance with
7
+ * "desde"), credit in favor, aging of the open debt (not due, 0–30, 31–60, 61–90, 90+) and open invoices.
8
+ * platform: <Billing.AccountStatement :client-id="client.id" /> (whole client; xlsx export,
9
+ * "Aplicar saldo a favor"; space-key narrows to one space)
10
+ * backoffice: <Billing.AccountStatement mode="space" /> (active space, read-only)
11
+ * Backend: GET {endpoint}/clients/{id}/account(/export) · POST …/apply-credit — backoffice GET {endpoint}/account.
12
+ */
13
+ const props = withDefaults(defineProps<{
14
+ endpoint?: string
15
+ mode?: 'client' | 'space'
16
+ clientId?: string | null
17
+ spaceKey?: string | null
18
+ canEdit?: boolean
19
+ }>(), { endpoint: undefined, mode: 'client', clientId: null, spaceKey: null, canEdit: true })
20
+
21
+ const toast = useToast()
22
+ const range = reactive({ from: '', to: '' })
23
+ const params = computed(() => ({ from: range.from, to: range.to, tenant_key: props.spaceKey }))
24
+ const isSpace = props.mode === 'space'
25
+ const platform = isSpace ? null : useBillingPlatform({ base: props.endpoint ?? 'platform/billing' })
26
+ const space = isSpace ? useBillingSpace({ base: props.endpoint ?? 'billing' }) : null
27
+ const query = isSpace
28
+ ? space!.account(computed(() => ({ from: range.from, to: range.to })))
29
+ : platform!.account(computed(() => props.clientId ?? ''), params)
30
+ const data = computed<any>(() => query.data.value)
31
+ const download = useBillingDownload()
32
+
33
+ async function exportXlsx() {
34
+ if (!platform || !props.clientId) return
35
+ try {
36
+ await download(`${platform.base}/clients/${props.clientId}/account/export`, `estado-de-cuenta.xlsx`, params.value)
37
+ } catch {
38
+ toast.error('No se pudo descargar el estado de cuenta.')
39
+ }
40
+ }
41
+
42
+ async function applyCredit() {
43
+ if (!platform || !props.clientId) return
44
+ try {
45
+ const res = await platform.applyCredit.mutateAsync({ clientId: props.clientId })
46
+ toast.success(res.applied > 0 ? `Saldo a favor aplicado: ${formatMoney(res.applied)}.` : 'No hay facturas abiertas para aplicar el saldo.')
47
+ query.refetch()
48
+ } catch (e: any) {
49
+ toast.error(errorMessage(e, 'No se pudo aplicar el saldo a favor.'))
50
+ }
51
+ }
52
+
53
+ const inputClass = 'h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
54
+ </script>
55
+
56
+ <template>
57
+ <div class="space-y-4">
58
+ <div class="flex flex-wrap items-end gap-3 text-sm">
59
+ <label class="space-y-1"><span class="block text-xs text-muted-foreground">Desde</span><input v-model="range.from" type="date" :class="inputClass" /></label>
60
+ <label class="space-y-1"><span class="block text-xs text-muted-foreground">Hasta</span><input v-model="range.to" type="date" :class="inputClass" /></label>
61
+ <span class="flex-1" />
62
+ <App.Button v-if="!isSpace && canEdit && (data?.credit_available ?? 0) > 0" text="Aplicar saldo a favor" size="sm" :icon="IconCoin" :loading="platform?.applyCredit.isPending.value" @click="applyCredit" />
63
+ <App.Button v-if="!isSpace" text="Excel" size="sm" outline :icon="IconDownload" @click="exportXlsx" />
64
+ </div>
65
+
66
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
67
+ <div v-else-if="query.isError.value || !data" class="p-8 text-center text-sm text-muted-foreground">
68
+ No se pudo cargar el estado de cuenta.
69
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
70
+ </div>
71
+ <div v-else-if="data.testing" class="rounded-card border border-info/40 bg-info/5 p-4 text-sm">Espacio de pruebas: no tiene facturación.</div>
72
+
73
+ <template v-else>
74
+ <div class="grid gap-3 sm:grid-cols-3">
75
+ <App.StatCard label="Saldo" :value="formatMoney(data.closing_balance, data.currency)" :value-class="data.closing_balance > 0 ? 'text-foreground' : 'text-success'"
76
+ :hint="data.closing_balance < 0 ? 'A favor del cliente' : 'Cargos menos abonos'" />
77
+ <App.StatCard label="Deuda abierta" :value="formatMoney(data.open_balance, data.currency)" :value-class="data.aging.total - data.aging.current > 0 ? 'text-danger' : 'text-foreground'"
78
+ :hint="`${formatMoney(data.aging.total - data.aging.current, data.currency)} vencido`" />
79
+ <App.StatCard v-if="data.credit_available !== null" label="Saldo a favor disponible" :value="formatMoney(data.credit_available, data.currency)" hint="Se aplica a la próxima factura emitida" />
80
+ </div>
81
+
82
+ <div class="bg-card border border-card-line rounded-card p-4">
83
+ <p class="text-sm font-medium text-foreground mb-2">Antigüedad de la deuda</p>
84
+ <div class="grid gap-2 grid-cols-2 sm:grid-cols-5 text-sm">
85
+ <div v-for="b in AGING_BUCKETS" :key="b.key">
86
+ <p class="text-xs text-muted-foreground">{{ b.label }}</p>
87
+ <p :class="b.key !== 'current' && data.aging[b.key] > 0 ? 'text-danger font-medium' : ''">{{ formatMoney(data.aging[b.key], data.currency) }}</p>
88
+ </div>
89
+ </div>
90
+ </div>
91
+
92
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
93
+ <table class="w-full text-sm">
94
+ <thead class="text-xs uppercase text-muted-foreground">
95
+ <tr class="border-b border-card-line">
96
+ <th class="text-left font-medium px-4 py-2">Fecha</th>
97
+ <th class="text-left font-medium px-4 py-2">Detalle</th>
98
+ <th class="text-right font-medium px-4 py-2">Cargo</th>
99
+ <th class="text-right font-medium px-4 py-2">Abono</th>
100
+ <th class="text-right font-medium px-4 py-2">Saldo</th>
101
+ </tr>
102
+ </thead>
103
+ <tbody class="divide-y divide-card-line">
104
+ <tr v-if="range.from" class="text-muted-foreground">
105
+ <td class="px-4 py-2">{{ formatDate(range.from) }}</td><td class="px-4 py-2">Saldo inicial</td><td /><td />
106
+ <td class="px-4 py-2 text-right">{{ formatMoney(data.opening_balance, data.currency) }}</td>
107
+ </tr>
108
+ <tr v-if="!data.movements.length"><td colspan="5" class="p-6 text-center text-muted-foreground">Sin movimientos en el rango.</td></tr>
109
+ <tr v-for="(m, idx) in data.movements" :key="idx">
110
+ <td class="px-4 py-2 whitespace-nowrap text-muted-foreground">{{ formatDate(m.date) }}</td>
111
+ <td class="px-4 py-2"><span class="text-xs text-muted-foreground mr-1">{{ movementLabel(m.type) }}</span>{{ m.description }}</td>
112
+ <td class="px-4 py-2 text-right">{{ m.charge ? formatMoney(m.charge, data.currency) : '' }}</td>
113
+ <td class="px-4 py-2 text-right text-success">{{ m.credit ? formatMoney(m.credit, data.currency) : '' }}</td>
114
+ <td class="px-4 py-2 text-right font-medium">{{ formatMoney(m.balance, data.currency) }}</td>
115
+ </tr>
116
+ </tbody>
117
+ </table>
118
+ </div>
119
+ </template>
120
+ </div>
121
+ </template>
@@ -0,0 +1,44 @@
1
+ <script setup lang="ts">
2
+ import { formatDateTime, activityLabel, formatMoney } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.ActivityLog — collections audit log of a client (who did what: adjustments, credit notes,
6
+ * voids and reissues, terms, reconciliations, waivers), newest first.
7
+ * Backend: GET {endpoint}/activity?client_id=.
8
+ *
9
+ * <Billing.ActivityLog :client-id="client.id" :users="{ [id]: name }" />
10
+ */
11
+ const props = withDefaults(defineProps<{ endpoint?: string; clientId?: string | null; users?: Record<string, string> }>(), { endpoint: 'platform/billing', clientId: null, users: () => ({}) })
12
+
13
+ const billing = useBillingPlatform({ base: props.endpoint })
14
+ const page = ref(1)
15
+ const query = billing.activity(computed(() => ({ client_id: props.clientId, page: page.value })))
16
+ const rows = computed<any[]>(() => (query.data.value as any)?.data ?? [])
17
+ const meta = computed(() => (query.data.value as any)?.meta ?? { page: 1, last_page: 1 })
18
+
19
+ function detail(a: any): string {
20
+ const d = a.data ?? {}
21
+ const parts = [d.number, d.invoice, d.reason]
22
+ if (typeof d.amount === 'number') parts.push(formatMoney(d.amount))
23
+ return parts.filter(Boolean).join(' · ')
24
+ }
25
+ const who = (a: any) => !a.user_id ? 'Sistema' : (props.users[a.user_id] ?? `Usuario ${a.user_id}`)
26
+ </script>
27
+
28
+ <template>
29
+ <div class="bg-card border border-card-line rounded-card">
30
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
31
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin actividad de cobranza.</div>
32
+ <ul v-else class="divide-y divide-card-line text-sm">
33
+ <li v-for="a in rows" :key="a.id" class="px-4 py-2">
34
+ <p class="text-foreground">{{ activityLabel(a.subject_type, a.action) }}<span v-if="detail(a)" class="text-muted-foreground"> · {{ detail(a) }}</span></p>
35
+ <p class="text-xs text-muted-foreground">{{ formatDateTime(a.created_at) }} · {{ who(a) }}</p>
36
+ </li>
37
+ </ul>
38
+ <div v-if="meta.last_page > 1" class="flex items-center justify-end gap-2 p-3 text-sm">
39
+ <App.Button text="Anterior" size="xs" :disabled="page <= 1" @click="page--" />
40
+ <span class="text-muted-foreground">Página {{ meta.page }} de {{ meta.last_page }}</span>
41
+ <App.Button text="Siguiente" size="xs" :disabled="page >= meta.last_page" @click="page++" />
42
+ </div>
43
+ </div>
44
+ </template>
@@ -0,0 +1,169 @@
1
+ <script setup lang="ts">
2
+ import { IconPlus, IconReceiptRefund, IconX } from '@tabler/icons-vue'
3
+ import {
4
+ ADJUSTMENT_TYPES, adjustmentTypeLabel, adjustmentValue, adjustmentStatus, adjustmentPayload, formatDate, formatDateTime,
5
+ errorMessage, type Adjustment, type AdjustmentForm,
6
+ } from '../../composables/useBilling/internal/billing'
7
+
8
+ /*
9
+ * Billing.Adjustments — discounts, surcharges, one-off charges and credits of a client's spaces (or of the
10
+ * whole client: percent discounts/surcharges applied to every space), plus its credit notes. Every
11
+ * adjustment carries reason and author; pending ones can be canceled. They enter the next closes.
12
+ * Backend: GET|POST {endpoint}/adjustments, POST {endpoint}/adjustments/{id}/cancel, POST {endpoint}/credit-notes.
13
+ *
14
+ * <Billing.Adjustments :client-id="client.id" :spaces="[{ value: 'rancagua', label: 'Rancagua' }]" />
15
+ * <Billing.Adjustments :client-id="client.id" space-key="rancagua" /> (inside a space detail)
16
+ */
17
+ const props = withDefaults(defineProps<{
18
+ endpoint?: string
19
+ clientId: string
20
+ spaceKey?: string | null
21
+ spaces?: { value: string; label: string }[]
22
+ canEdit?: boolean
23
+ }>(), { endpoint: 'platform/billing', spaceKey: null, spaces: () => [], canEdit: true })
24
+
25
+ const toast = useToast()
26
+ const { prompt } = useModal()
27
+ const billing = useBillingPlatform({ base: props.endpoint })
28
+
29
+ const status = ref<'' | 'pending' | 'applied' | 'canceled'>('')
30
+ const filters = computed(() => ({ client_id: props.spaceKey ? null : props.clientId, tenant_key: props.spaceKey, status: status.value }))
31
+ const query = billing.adjustments(filters)
32
+ const rows = computed<Adjustment[]>(() => (query.data.value as Adjustment[] | undefined) ?? [])
33
+ const spaceName = (a: Adjustment) => a.scope === 'client' ? 'Todo el cliente' : (props.spaces.find(s => s.value === a.tenant_id)?.label ?? props.spaceKey ?? 'Espacio')
34
+
35
+ const empty = (): AdjustmentForm => ({
36
+ scope: 'space', tenant_key: props.spaceKey ?? props.spaces[0]?.value ?? '', type: 'discount', mode: 'amount', value: '',
37
+ recurring: false, starts_at: '', ends_at: '', reason: '',
38
+ })
39
+ const form = reactive({ open: false, data: empty() })
40
+ const once = computed(() => form.data.type === 'one_off' || form.data.type === 'credit')
41
+
42
+ async function submit() {
43
+ const { payload, error } = adjustmentPayload(form.data, props.clientId)
44
+ if (error) { toast.error(error); return }
45
+ try {
46
+ await billing.createAdjustment.mutateAsync(payload)
47
+ form.open = false
48
+ toast.success('Ajuste creado. Se aplica en el próximo cierre.')
49
+ } catch (e: any) {
50
+ toast.error(errorMessage(e, 'No se pudo crear el ajuste.'))
51
+ }
52
+ }
53
+
54
+ async function cancel(a: Adjustment) {
55
+ const reason = await prompt({ title: 'Anular ajuste', message: `${adjustmentTypeLabel(a.type)} "${a.reason}". Indica el motivo.`, required: true, confirmText: 'Anular' })
56
+ if (!reason) return
57
+ try {
58
+ await billing.cancelAdjustment.mutateAsync({ id: a.id, reason })
59
+ toast.success('Ajuste anulado.')
60
+ } catch (e: any) {
61
+ toast.error(errorMessage(e, 'No se pudo anular.'))
62
+ }
63
+ }
64
+
65
+ const creditNoteOpen = ref(false)
66
+ const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
67
+ </script>
68
+
69
+ <template>
70
+ <div class="space-y-4">
71
+ <div class="flex flex-wrap items-end gap-3">
72
+ <label class="space-y-1">
73
+ <span class="text-xs text-muted-foreground">Estado</span>
74
+ <select v-model="status" :class="inputClass">
75
+ <option value="">Todos</option>
76
+ <option value="pending">Pendientes</option>
77
+ <option value="applied">Aplicados</option>
78
+ <option value="canceled">Anulados</option>
79
+ </select>
80
+ </label>
81
+ <span class="flex-1" />
82
+ <App.Button v-if="canEdit" text="Nota de crédito" size="sm" :icon="IconReceiptRefund" @click="creditNoteOpen = true" />
83
+ <App.Button v-if="canEdit" text="Nuevo ajuste" size="sm" severity="primary" :icon="IconPlus" @click="form.data = empty(); form.open = true" />
84
+ </div>
85
+
86
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
87
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
88
+ <div v-else-if="query.isError.value" class="p-8 text-center text-sm text-muted-foreground">
89
+ No se pudieron cargar los ajustes.
90
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
91
+ </div>
92
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin ajustes ni notas de crédito.</div>
93
+ <table v-else class="w-full text-sm">
94
+ <thead class="text-xs uppercase text-muted-foreground">
95
+ <tr class="border-b border-card-line">
96
+ <th class="text-left font-medium px-4 py-2">Ajuste</th>
97
+ <th class="text-left font-medium px-4 py-2">Alcance</th>
98
+ <th class="text-right font-medium px-4 py-2">Valor</th>
99
+ <th class="text-left font-medium px-4 py-2">Vigencia</th>
100
+ <th class="text-left font-medium px-4 py-2">Motivo</th>
101
+ <th class="px-4 py-2" />
102
+ </tr>
103
+ </thead>
104
+ <tbody class="divide-y divide-card-line">
105
+ <tr v-for="a in rows" :key="a.id">
106
+ <td class="px-4 py-2">
107
+ <p class="font-medium text-foreground">{{ a.credit_note ? `Nota de crédito ${a.display_number}` : adjustmentTypeLabel(a.type) }}</p>
108
+ <App.Tag :text="adjustmentStatus(a.status).label" :severity="adjustmentStatus(a.status).severity" size="xs" />
109
+ </td>
110
+ <td class="px-4 py-2 text-muted-foreground">{{ spaceName(a) }}</td>
111
+ <td class="px-4 py-2 text-right whitespace-nowrap">{{ adjustmentValue(a) }}</td>
112
+ <td class="px-4 py-2 text-muted-foreground">
113
+ <template v-if="a.credit_note">{{ a.target === 'invoice' ? 'A factura' : a.target === 'balance' ? 'Saldo a favor' : 'Próximo cobro' }}</template>
114
+ <template v-else-if="a.recurring">Recurrente {{ a.starts_at ? `desde ${formatDate(a.starts_at)}` : '' }} {{ a.ends_at ? `hasta ${formatDate(a.ends_at)}` : '(sin término)' }}</template>
115
+ <template v-else>Una vez</template>
116
+ </td>
117
+ <td class="px-4 py-2">
118
+ <p>{{ a.reason }}</p>
119
+ <p class="text-xs text-muted-foreground">{{ formatDateTime(a.created_at) }}<template v-if="a.cancel_reason"> · anulado: {{ a.cancel_reason }}</template></p>
120
+ </td>
121
+ <td class="px-4 py-2 text-right">
122
+ <App.Button v-if="canEdit && a.status === 'pending'" text="Anular" size="xs" outline :icon="IconX" @click="cancel(a)" />
123
+ </td>
124
+ </tr>
125
+ </tbody>
126
+ </table>
127
+ </div>
128
+
129
+ <Modal v-model="form.open" title="Nuevo ajuste" size="md" show-footer>
130
+ <div class="space-y-3 text-sm">
131
+ <div v-if="!spaceKey" class="flex gap-4">
132
+ <label class="flex items-center gap-2"><input v-model="form.data.scope" type="radio" value="space" /> Un espacio</label>
133
+ <label class="flex items-center gap-2"><input v-model="form.data.scope" type="radio" value="client" /> Todo el cliente (porcentaje)</label>
134
+ </div>
135
+ <label v-if="form.data.scope === 'space' && !spaceKey" class="block space-y-1"><span class="font-medium">Espacio</span>
136
+ <select v-model="form.data.tenant_key" :class="inputClass"><option v-for="s in spaces" :key="s.value" :value="s.value">{{ s.label }}</option></select>
137
+ </label>
138
+ <div class="grid grid-cols-2 gap-3">
139
+ <label class="block space-y-1"><span class="font-medium">Tipo</span>
140
+ <select v-model="form.data.type" :class="inputClass">
141
+ <option v-for="t in ADJUSTMENT_TYPES" :key="t.value" :value="t.value" :disabled="form.data.scope === 'client' && !['discount', 'surcharge'].includes(t.value)">{{ t.label }}</option>
142
+ </select>
143
+ </label>
144
+ <label class="block space-y-1"><span class="font-medium">Cálculo</span>
145
+ <select v-model="form.data.mode" :class="inputClass">
146
+ <option value="amount" :disabled="form.data.scope === 'client'">Monto neto ($)</option>
147
+ <option value="percent">Porcentaje (%)</option>
148
+ </select>
149
+ </label>
150
+ </div>
151
+ <label class="block space-y-1"><span class="font-medium">{{ form.data.mode === 'percent' ? 'Porcentaje' : 'Monto (antes de IVA)' }}</span>
152
+ <input v-model="form.data.value" inputmode="decimal" :class="inputClass" />
153
+ </label>
154
+ <label v-if="!once" class="flex items-center gap-2"><input v-model="form.data.recurring" type="checkbox" class="rounded" /> Recurrente (se aplica en cada cierre dentro de la vigencia)</label>
155
+ <div class="grid grid-cols-2 gap-3">
156
+ <label class="block space-y-1"><span class="font-medium">Desde</span><input v-model="form.data.starts_at" type="date" :class="inputClass" /></label>
157
+ <label v-if="!once" class="block space-y-1"><span class="font-medium">Hasta</span><input v-model="form.data.ends_at" type="date" :class="inputClass" /></label>
158
+ </div>
159
+ <label class="block space-y-1"><span class="font-medium">Motivo</span><input v-model="form.data.reason" :class="inputClass" maxlength="250" placeholder="Aparece como línea del cobro" /></label>
160
+ </div>
161
+ <template #footer>
162
+ <App.Button text="Cancelar" size="sm" @click="form.open = false" />
163
+ <App.Button text="Crear ajuste" severity="primary" size="sm" :loading="billing.createAdjustment.isPending.value" @click="submit" />
164
+ </template>
165
+ </Modal>
166
+
167
+ <Billing.CreditNoteForm v-model="creditNoteOpen" :endpoint="endpoint" :client-id="clientId" :spaces="spaceKey ? [{ value: spaceKey, label: spaceKey }] : spaces" />
168
+ </div>
169
+ </template>
@@ -0,0 +1,70 @@
1
+ <script setup lang="ts">
2
+ import { errorMessage } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.ClientTerms — collection terms of a client: late fee interest (percent, per month or per day,
6
+ * cap over the invoice total, exemption) and whether payment reminders are sent. Changes are audited.
7
+ * Backend: GET|PUT {endpoint}/clients/{clientId}/terms.
8
+ *
9
+ * <Billing.ClientTerms :client-id="client.id" :can-edit="isOwner" />
10
+ */
11
+ const props = withDefaults(defineProps<{ endpoint?: string; clientId: string; canEdit?: boolean }>(), { endpoint: 'platform/billing', canEdit: true })
12
+
13
+ const toast = useToast()
14
+ const billing = useBillingPlatform({ base: props.endpoint })
15
+ const query = billing.terms(computed(() => props.clientId))
16
+ const form = reactive({ late_fee_percent: '' as string | number, late_fee_basis: 'monthly', late_fee_cap_percent: '' as string | number, late_fee_exempt: false, reminders_enabled: true })
17
+
18
+ watch(() => query.data.value, (t: any) => {
19
+ if (t) Object.assign(form, { late_fee_percent: t.late_fee_percent ?? 0, late_fee_basis: t.late_fee_basis, late_fee_cap_percent: t.late_fee_cap_percent ?? '', late_fee_exempt: t.late_fee_exempt, reminders_enabled: t.reminders_enabled })
20
+ }, { immediate: true })
21
+
22
+ const example = computed(() => {
23
+ const p = Number(form.late_fee_percent) || 0
24
+ if (p <= 0 || form.late_fee_exempt) return 'Sin interés por mora.'
25
+ const daily = form.late_fee_basis === 'daily' ? p : p / 30
26
+ return `Una deuda vencida de $ 100.000 genera $ ${Math.round(100000 * daily / 100 * 30).toLocaleString('es-CL')} en 30 días (se cobra en el cierre siguiente).`
27
+ })
28
+
29
+ async function save() {
30
+ try {
31
+ await billing.saveTerms.mutateAsync({
32
+ clientId: props.clientId,
33
+ body: {
34
+ late_fee_percent: Number(form.late_fee_percent) || 0,
35
+ late_fee_basis: form.late_fee_basis,
36
+ late_fee_cap_percent: form.late_fee_cap_percent === '' ? null : Number(form.late_fee_cap_percent),
37
+ late_fee_exempt: form.late_fee_exempt,
38
+ reminders_enabled: form.reminders_enabled,
39
+ },
40
+ })
41
+ toast.success('Condiciones guardadas.')
42
+ } catch (e: any) {
43
+ toast.error(errorMessage(e, 'No se pudieron guardar las condiciones.'))
44
+ }
45
+ }
46
+
47
+ const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
48
+ </script>
49
+
50
+ <template>
51
+ <form class="bg-card border border-card-line rounded-card p-4 grid gap-3 sm:grid-cols-2 text-sm" @submit.prevent="save">
52
+ <p class="sm:col-span-2 font-medium text-foreground">Interés por mora</p>
53
+ <label class="block space-y-1"><span class="font-medium">Tasa (%)</span>
54
+ <input v-model="form.late_fee_percent" type="number" min="0" max="50" step="0.01" :class="inputClass" :disabled="!canEdit" />
55
+ </label>
56
+ <label class="block space-y-1"><span class="font-medium">Base</span>
57
+ <select v-model="form.late_fee_basis" :class="inputClass" :disabled="!canEdit"><option value="monthly">Mensual</option><option value="daily">Diaria</option></select>
58
+ </label>
59
+ <label class="block space-y-1"><span class="font-medium">Tope (% del total de la factura)</span>
60
+ <input v-model="form.late_fee_cap_percent" type="number" min="0" step="0.01" :class="inputClass" :disabled="!canEdit" placeholder="Sin tope" />
61
+ </label>
62
+ <label class="flex items-center gap-2 self-end h-9"><input v-model="form.late_fee_exempt" type="checkbox" class="rounded" :disabled="!canEdit" /> Cliente exento de interés</label>
63
+ <p class="sm:col-span-2 text-xs text-muted-foreground">{{ example }}</p>
64
+ <p class="sm:col-span-2 font-medium text-foreground pt-2">Recordatorios</p>
65
+ <label class="sm:col-span-2 flex items-center gap-2"><input v-model="form.reminders_enabled" type="checkbox" class="rounded" :disabled="!canEdit" /> Enviar recordatorios de pago por correo a este cliente</label>
66
+ <div v-if="canEdit" class="sm:col-span-2 flex justify-end">
67
+ <App.Button text="Guardar" severity="primary" size="sm" :loading="billing.saveTerms.isPending.value" @click="save" />
68
+ </div>
69
+ </form>
70
+ </template>
@@ -0,0 +1,82 @@
1
+ <script setup lang="ts">
2
+ import { CREDIT_NOTE_TARGETS, creditNotePayload, formatMoney, errorMessage, type CreditNoteForm, type Invoice } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.CreditNoteForm — modal to create a credit note (NC-000001) with reason: to an open invoice
6
+ * (amount with VAT), to the client balance (credit for the next invoice) or to the next charge of a
7
+ * space (net amount). With `invoice` it opens fixed on that invoice.
8
+ * Backend: POST {endpoint}/credit-notes; open invoices from GET {endpoint}/reconciliation/open-invoices.
9
+ *
10
+ * <Billing.CreditNoteForm v-model="open" :client-id="client.id" :spaces="spaces" />
11
+ * <Billing.CreditNoteForm v-model="open" :client-id="invoice.client_id" :invoice="invoice" @created="reload" />
12
+ */
13
+ const props = withDefaults(defineProps<{
14
+ endpoint?: string
15
+ clientId: string
16
+ invoice?: Invoice | null
17
+ spaces?: { value: string; label: string }[]
18
+ }>(), { endpoint: 'platform/billing', invoice: null, spaces: () => [] })
19
+ const emit = defineEmits<{ created: [note: any] }>()
20
+ const open = defineModel<boolean>({ default: false })
21
+
22
+ const toast = useToast()
23
+ const billing = useBillingPlatform({ base: props.endpoint })
24
+ const form = reactive<CreditNoteForm>({ target: 'invoice', amount: '', reason: '', invoice_id: '', tenant_key: '' })
25
+ const candidates = ref<Invoice[]>([])
26
+
27
+ watch(open, async (v) => {
28
+ if (!v) return
29
+ Object.assign(form, { target: 'invoice', amount: '', reason: '', invoice_id: props.invoice?.id ?? '', tenant_key: props.spaces[0]?.value ?? '' })
30
+ if (props.invoice) { candidates.value = [props.invoice]; return }
31
+ try {
32
+ candidates.value = await billing.openInvoices({ client_id: props.clientId })
33
+ form.invoice_id = candidates.value[0]?.id ?? ''
34
+ } catch {
35
+ candidates.value = []
36
+ }
37
+ })
38
+
39
+ const targets = computed(() => props.invoice ? CREDIT_NOTE_TARGETS.filter(t => t.value === 'invoice') : CREDIT_NOTE_TARGETS)
40
+ const hint = computed(() => CREDIT_NOTE_TARGETS.find(t => t.value === form.target)?.hint)
41
+
42
+ async function submit() {
43
+ const { payload, error } = creditNotePayload(form, props.clientId)
44
+ if (error) { toast.error(error); return }
45
+ try {
46
+ const note = await billing.createCreditNote.mutateAsync(payload)
47
+ open.value = false
48
+ toast.success(`Nota de crédito ${note?.display_number ?? ''} creada.`)
49
+ emit('created', note)
50
+ } catch (e: any) {
51
+ toast.error(errorMessage(e, 'No se pudo crear la nota de crédito.'))
52
+ }
53
+ }
54
+
55
+ const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
56
+ </script>
57
+
58
+ <template>
59
+ <Modal v-model="open" title="Nota de crédito" size="md" show-footer>
60
+ <div class="space-y-3 text-sm">
61
+ <label class="block space-y-1"><span class="font-medium">Se aplica a</span>
62
+ <select v-model="form.target" :class="inputClass"><option v-for="t in targets" :key="t.value" :value="t.value">{{ t.label }}</option></select>
63
+ <span class="text-xs text-muted-foreground">{{ hint }}</span>
64
+ </label>
65
+ <label v-if="form.target === 'invoice'" class="block space-y-1"><span class="font-medium">Factura</span>
66
+ <select v-model="form.invoice_id" :class="inputClass" :disabled="!!invoice">
67
+ <option v-if="!candidates.length" value="">No hay facturas abiertas</option>
68
+ <option v-for="i in candidates" :key="i.id" :value="i.id">{{ i.display_number }} · saldo {{ formatMoney(i.balance, i.currency) }}</option>
69
+ </select>
70
+ </label>
71
+ <label v-if="form.target === 'next_period'" class="block space-y-1"><span class="font-medium">Espacio</span>
72
+ <select v-model="form.tenant_key" :class="inputClass"><option v-for="s in spaces" :key="s.value" :value="s.value">{{ s.label }}</option></select>
73
+ </label>
74
+ <label class="block space-y-1"><span class="font-medium">Monto ($)</span><input v-model="form.amount" inputmode="numeric" :class="inputClass" /></label>
75
+ <label class="block space-y-1"><span class="font-medium">Motivo</span><input v-model="form.reason" :class="inputClass" maxlength="250" /></label>
76
+ </div>
77
+ <template #footer>
78
+ <App.Button text="Cancelar" size="sm" @click="open = false" />
79
+ <App.Button text="Crear nota de crédito" severity="primary" size="sm" :loading="billing.createCreditNote.isPending.value" @click="submit" />
80
+ </template>
81
+ </Modal>
82
+ </template>