Finalize Typescript restructure

This commit is contained in:
Darko Gjorgjijoski
2026-04-06 17:59:15 +02:00
parent cab785172e
commit 74b4b2df4e
209 changed files with 12419 additions and 1745 deletions

View File

@@ -0,0 +1,270 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { required, helpers } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import { useModalStore } from '@v2/stores/modal.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import {
backupService,
type CreateBackupPayload,
} from '@v2/api/services/backup.service'
import { diskService, type Disk } from '@v2/api/services/disk.service'
import {
getErrorTranslationKey,
handleApiError,
} from '@v2/utils/error-handling'
type BackupOption = CreateBackupPayload['option']
interface DiskOption extends Disk {
display_name: string
}
interface BackupTypeOption {
id: BackupOption
label: string
}
interface BackupModalData {
disks?: DiskOption[]
selectedDiskId?: number | null
}
interface BackupForm {
option: BackupOption | ''
selectedDiskId: number | null
}
const modalStore = useModalStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const isSaving = ref(false)
const isFetchingInitialData = ref(false)
const disks = ref<DiskOption[]>([])
const form = reactive<BackupForm>({
option: 'full',
selectedDiskId: null,
})
const backupTypeOptions: BackupTypeOption[] = [
{
id: 'full',
label: 'full',
},
{
id: 'only-db',
label: 'only-db',
},
{
id: 'only-files',
label: 'only-files',
},
]
const modalActive = computed<boolean>(() => {
return modalStore.active && modalStore.componentName === 'AdminBackupModal'
})
const rules = computed(() => ({
option: {
required: helpers.withMessage(t('validation.required'), required),
},
selectedDiskId: {
required: helpers.withMessage(t('validation.required'), required),
},
}))
const v$ = useVuelidate(rules, form)
async function setInitialData(): Promise<void> {
resetForm()
isFetchingInitialData.value = true
try {
const modalData = isBackupModalData(modalStore.data) ? modalStore.data : null
if (modalData?.disks?.length) {
disks.value = modalData.disks
form.selectedDiskId =
modalData.selectedDiskId ??
modalData.disks.find((disk) => disk.set_as_default)?.id ??
modalData.disks[0]?.id ??
null
return
}
const response = await diskService.list({ limit: 'all' })
disks.value = response.data.map((disk) => ({
...disk,
display_name: `${disk.name} - [${disk.driver}]`,
}))
const selectedDiskId =
modalStore.data &&
typeof modalStore.data === 'object' &&
'id' in (modalStore.data as Record<string, unknown>)
? Number((modalStore.data as Record<string, unknown>).id)
: null
form.selectedDiskId =
disks.value.find((disk) => disk.id === selectedDiskId)?.id ??
disks.value.find((disk) => disk.set_as_default)?.id ??
disks.value[0]?.id ??
null
} catch (error: unknown) {
showApiError(error)
} finally {
isFetchingInitialData.value = false
}
}
async function createBackup(): Promise<void> {
v$.value.$touch()
if (v$.value.$invalid || !form.selectedDiskId) {
return
}
isSaving.value = true
try {
const response = await backupService.create({
option: form.option as BackupOption,
file_disk_id: form.selectedDiskId,
})
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: t('settings.backup.created_message'),
})
modalStore.refreshData?.()
closeModal()
}
} catch (error: unknown) {
showApiError(error)
} finally {
isSaving.value = false
}
}
function showApiError(error: unknown): void {
const normalizedError = handleApiError(error)
const translationKey = getErrorTranslationKey(normalizedError.message)
notificationStore.showNotification({
type: 'error',
message: translationKey ? t(translationKey) : normalizedError.message,
})
}
function resetForm(): void {
form.option = 'full'
form.selectedDiskId = null
v$.value.$reset()
}
function closeModal(): void {
modalStore.closeModal()
setTimeout(() => {
resetForm()
disks.value = []
}, 300)
}
function isBackupModalData(value: unknown): value is BackupModalData {
return Boolean(value && typeof value === 'object')
}
</script>
<template>
<BaseModal :show="modalActive" @close="closeModal" @open="setInitialData">
<template #header>
<div class="flex justify-between w-full">
{{ modalStore.title }}
<BaseIcon
name="XMarkIcon"
class="w-6 h-6 text-muted cursor-pointer"
@click="closeModal"
/>
</div>
</template>
<form @submit.prevent="createBackup">
<div class="p-4 md:p-6">
<BaseInputGrid layout="one-column">
<BaseInputGroup
:label="$t('settings.backup.select_backup_type')"
:error="v$.option.$error && v$.option.$errors[0]?.$message"
required
>
<BaseSelectInput
v-model="form.option"
:options="backupTypeOptions"
:placeholder="$t('settings.backup.select_backup_type')"
value-prop="id"
@update:model-value="v$.option.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.disk.select_disk')"
:error="
v$.selectedDiskId.$error && v$.selectedDiskId.$errors[0]?.$message
"
required
>
<BaseMultiselect
v-model="form.selectedDiskId"
:options="disks"
:content-loading="isFetchingInitialData"
:can-deselect="false"
:invalid="v$.selectedDiskId.$error"
label="display_name"
track-by="id"
value-prop="id"
searchable
:placeholder="$t('settings.disk.select_disk')"
@update:model-value="v$.selectedDiskId.$touch()"
/>
</BaseInputGroup>
</BaseInputGrid>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
type="button"
variant="primary-outline"
class="mr-3"
@click="closeModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
>
<template #left="slotProps">
<BaseIcon
v-if="!isSaving"
name="ArrowDownOnSquareIcon"
:class="slotProps.class"
/>
</template>
{{ $t('general.create') }}
</BaseButton>
</div>
</form>
</BaseModal>
</template>

View File

@@ -0,0 +1,565 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { required, helpers } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import { useModalStore } from '@v2/stores/modal.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import {
diskService,
type CreateDiskPayload,
type Disk,
type DiskDriverValue,
} from '@v2/api/services/disk.service'
import {
getErrorTranslationKey,
handleApiError,
} from '@v2/utils/error-handling'
interface DiskField {
key: string
labelKey: string
placeholder?: string
}
interface DiskDriverOption {
name: string
value: DiskDriverValue
}
interface DiskForm {
name: string
driver: DiskDriverValue
set_as_default: boolean
credentials: Record<string, string>
}
const DRIVER_FIELDS: Record<DiskDriverValue, DiskField[]> = {
local: [
{
key: 'root',
labelKey: 'settings.disk.local_root',
placeholder: 'Ex. /user/root/',
},
],
s3: [
{
key: 'root',
labelKey: 'settings.disk.aws_root',
placeholder: 'Ex. /user/root/',
},
{
key: 'key',
labelKey: 'settings.disk.aws_key',
placeholder: 'Ex. KEIS4S39SERSDS',
},
{
key: 'secret',
labelKey: 'settings.disk.aws_secret',
placeholder: 'Ex. ********',
},
{
key: 'region',
labelKey: 'settings.disk.aws_region',
placeholder: 'Ex. us-west',
},
{
key: 'bucket',
labelKey: 'settings.disk.aws_bucket',
placeholder: 'Ex. AppName',
},
],
s3compat: [
{
key: 'endpoint',
labelKey: 'settings.disk.s3_endpoint',
placeholder: 'Ex. https://s3.example.com',
},
{
key: 'key',
labelKey: 'settings.disk.s3_key',
placeholder: 'Ex. KEIS4S39SERSDS',
},
{
key: 'secret',
labelKey: 'settings.disk.s3_secret',
placeholder: 'Ex. ********',
},
{
key: 'region',
labelKey: 'settings.disk.s3_region',
placeholder: 'Ex. us-west',
},
{
key: 'bucket',
labelKey: 'settings.disk.s3_bucket',
placeholder: 'Ex. AppName',
},
{
key: 'root',
labelKey: 'settings.disk.s3_root',
placeholder: 'Ex. /user/root/',
},
],
doSpaces: [
{
key: 'key',
labelKey: 'settings.disk.do_spaces_key',
placeholder: 'Ex. KEIS4S39SERSDS',
},
{
key: 'secret',
labelKey: 'settings.disk.do_spaces_secret',
placeholder: 'Ex. ********',
},
{
key: 'region',
labelKey: 'settings.disk.do_spaces_region',
placeholder: 'Ex. nyc3',
},
{
key: 'bucket',
labelKey: 'settings.disk.do_spaces_bucket',
placeholder: 'Ex. AppName',
},
{
key: 'endpoint',
labelKey: 'settings.disk.do_spaces_endpoint',
placeholder: 'Ex. https://nyc3.digitaloceanspaces.com',
},
{
key: 'root',
labelKey: 'settings.disk.do_spaces_root',
placeholder: 'Ex. /user/root/',
},
],
dropbox: [
{
key: 'token',
labelKey: 'settings.disk.dropbox_token',
},
{
key: 'key',
labelKey: 'settings.disk.dropbox_key',
placeholder: 'Ex. KEIS4S39SERSDS',
},
{
key: 'secret',
labelKey: 'settings.disk.dropbox_secret',
placeholder: 'Ex. ********',
},
{
key: 'app',
labelKey: 'settings.disk.dropbox_app',
},
{
key: 'root',
labelKey: 'settings.disk.dropbox_root',
placeholder: 'Ex. /user/root/',
},
],
}
const modalStore = useModalStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const isSaving = ref(false)
const isFetchingInitialData = ref(false)
const driverOptions = ref<DiskDriverOption[]>([])
const currentDisk = ref<Disk | null>(null)
const form = reactive<DiskForm>({
name: '',
driver: 'local',
set_as_default: false,
credentials: {},
})
const modalActive = computed<boolean>(() => {
return modalStore.active && modalStore.componentName === 'AdminFileDiskModal'
})
const currentFields = computed<DiskField[]>(() => {
return DRIVER_FIELDS[form.driver] ?? []
})
const defaultSwitchDisabled = computed<boolean>(() => {
return Boolean(currentDisk.value?.set_as_default)
})
const rules = computed(() => {
const credentialRules = currentFields.value.reduce<
Record<string, { required: ReturnType<typeof helpers.withMessage> }>
>((ruleSet, field) => {
ruleSet[field.key] = {
required: helpers.withMessage(t('validation.required'), required),
}
return ruleSet
}, {})
return {
name: {
required: helpers.withMessage(t('validation.required'), required),
},
driver: {
required: helpers.withMessage(t('validation.required'), required),
},
credentials: credentialRules,
}
})
const v$ = useVuelidate(rules, form)
async function setInitialData(): Promise<void> {
resetForm()
isFetchingInitialData.value = true
try {
const response = await diskService.getDrivers()
driverOptions.value = response.drivers
if (isDisk(modalStore.data)) {
currentDisk.value = modalStore.data
form.name = currentDisk.value.name
form.driver = currentDisk.value.driver
form.set_as_default = currentDisk.value.set_as_default
form.credentials = normalizeDiskCredentials(
currentDisk.value.credentials,
currentDisk.value.driver
)
} else {
currentDisk.value = null
form.driver = resolveInitialDriver(response.drivers, response.default)
form.credentials = await loadDriverCredentials(form.driver)
}
} catch (error: unknown) {
showApiError(error)
} finally {
isFetchingInitialData.value = false
}
}
async function handleDriverChange(value: DiskDriverValue): Promise<void> {
v$.value.driver.$touch()
form.driver = value
const existingName = form.name
const existingDefaultState = form.set_as_default
form.credentials = await loadDriverCredentials(value)
form.name = existingName
form.set_as_default = existingDefaultState
}
async function saveDisk(): Promise<void> {
v$.value.$touch()
if (v$.value.$invalid) {
return
}
isSaving.value = true
try {
const payload: CreateDiskPayload = {
name: form.name.trim(),
driver: form.driver,
credentials: { ...form.credentials },
set_as_default: form.set_as_default,
}
if (currentDisk.value) {
await diskService.update(currentDisk.value.id, payload)
notificationStore.showNotification({
type: 'success',
message: t('settings.disk.success_update'),
})
} else {
await diskService.create(payload)
notificationStore.showNotification({
type: 'success',
message: t('settings.disk.success_create'),
})
}
modalStore.refreshData?.()
closeModal()
} catch (error: unknown) {
showApiError(error)
} finally {
isSaving.value = false
}
}
async function loadDriverCredentials(
driver: DiskDriverValue
): Promise<Record<string, string>> {
if (currentDisk.value && currentDisk.value.driver === driver) {
return normalizeDiskCredentials(currentDisk.value.credentials, driver)
}
const defaults = await diskService.get(driver)
return normalizeDiskCredentials(defaults, driver)
}
function resolveInitialDriver(
drivers: DiskDriverOption[],
defaultDriver: string
): DiskDriverValue {
const matchedDriver = drivers.find((driver) => driver.value === defaultDriver)
return matchedDriver?.value ?? drivers[0]?.value ?? 'local'
}
function normalizeDiskCredentials(
credentials: Disk['credentials'] | Record<string, string>,
driver: DiskDriverValue
): Record<string, string> {
const emptyCredentials = createEmptyCredentials(driver)
if (!credentials) {
return emptyCredentials
}
if (typeof credentials === 'string') {
try {
const parsedCredentials = JSON.parse(credentials) as unknown
if (typeof parsedCredentials === 'string') {
return {
...emptyCredentials,
root: parsedCredentials,
}
}
if (parsedCredentials && typeof parsedCredentials === 'object') {
return {
...emptyCredentials,
...stringifyRecord(parsedCredentials as Record<string, unknown>),
}
}
} catch {
return {
...emptyCredentials,
root: credentials,
}
}
}
return {
...emptyCredentials,
...stringifyRecord(credentials as Record<string, unknown>),
}
}
function createEmptyCredentials(driver: DiskDriverValue): Record<string, string> {
return currentFieldsFor(driver).reduce<Record<string, string>>(
(credentialSet, field) => {
credentialSet[field.key] = ''
return credentialSet
},
{}
)
}
function currentFieldsFor(driver: DiskDriverValue): DiskField[] {
return DRIVER_FIELDS[driver] ?? []
}
function stringifyRecord(
value: Record<string, unknown>
): Record<string, string> {
return Object.entries(value).reduce<Record<string, string>>(
(record, [key, entry]) => {
record[key] = entry == null ? '' : String(entry)
return record
},
{}
)
}
function touchCredential(key: string): void {
const credentialField = (
v$.value.credentials as Record<
string,
{ $touch: () => void }
>
)[key]
credentialField?.$touch()
}
function credentialError(key: string): string {
const credentialField = (
v$.value.credentials as Record<
string,
{ $error: boolean; $errors: Array<{ $message: string }> }
>
)[key]
if (!credentialField?.$error) {
return ''
}
return credentialField.$errors[0]?.$message ?? ''
}
function isCredentialInvalid(key: string): boolean {
const credentialField = (
v$.value.credentials as Record<string, { $error: boolean }>
)[key]
return Boolean(credentialField?.$error)
}
function showApiError(error: unknown): void {
const normalizedError = handleApiError(error)
const translationKey = getErrorTranslationKey(normalizedError.message)
notificationStore.showNotification({
type: 'error',
message: translationKey ? t(translationKey) : normalizedError.message,
})
}
function resetForm(): void {
form.name = ''
form.driver = 'local'
form.set_as_default = false
form.credentials = {}
currentDisk.value = null
v$.value.$reset()
}
function closeModal(): void {
modalStore.closeModal()
setTimeout(() => {
resetForm()
driverOptions.value = []
}, 300)
}
function isDisk(value: unknown): value is Disk {
return Boolean(
value &&
typeof value === 'object' &&
'id' in value &&
'driver' in value &&
'name' in value
)
}
</script>
<template>
<BaseModal :show="modalActive" @close="closeModal" @open="setInitialData">
<template #header>
<div class="flex justify-between w-full">
{{ modalStore.title }}
<BaseIcon
name="XMarkIcon"
class="w-6 h-6 text-muted cursor-pointer"
@click="closeModal"
/>
</div>
</template>
<form @submit.prevent="saveDisk">
<div class="p-4 md:p-6">
<BaseInputGrid>
<BaseInputGroup
:label="$t('settings.disk.name')"
:error="v$.name.$error && v$.name.$errors[0]?.$message"
required
>
<BaseInput
v-model.trim="form.name"
:invalid="v$.name.$error"
@input="v$.name.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.disk.driver')"
:error="v$.driver.$error && v$.driver.$errors[0]?.$message"
required
>
<BaseMultiselect
v-model="form.driver"
:options="driverOptions"
:content-loading="isFetchingInitialData"
:can-deselect="false"
:invalid="v$.driver.$error"
label="name"
track-by="value"
value-prop="value"
searchable
@update:model-value="handleDriverChange"
/>
</BaseInputGroup>
<BaseInputGroup
v-for="field in currentFields"
:key="field.key"
:label="$t(field.labelKey)"
:error="credentialError(field.key)"
required
>
<BaseInput
v-model.trim="form.credentials[field.key]"
:invalid="isCredentialInvalid(field.key)"
:placeholder="field.placeholder"
@input="touchCredential(field.key)"
/>
</BaseInputGroup>
</BaseInputGrid>
<div class="mt-6 flex items-center">
<div class="relative flex items-center w-12">
<BaseSwitch
v-model="form.set_as_default"
:disabled="defaultSwitchDisabled"
class="flex"
/>
</div>
<div class="ml-4">
<p class="mb-1 text-base leading-snug text-heading">
{{ $t('settings.disk.is_default') }}
</p>
</div>
</div>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
type="button"
variant="primary-outline"
class="mr-3"
@click="closeModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
>
<template #left="slotProps">
<BaseIcon
v-if="!isSaving"
name="ArrowDownOnSquareIcon"
:class="slotProps.class"
/>
</template>
{{ currentDisk ? $t('general.update') : $t('general.save') }}
</BaseButton>
</div>
</form>
</BaseModal>
</template>

View File

@@ -0,0 +1,105 @@
<script setup lang="ts">
import { computed, onMounted, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { required, helpers } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import type { PdfDriver } from '@v2/api/services/pdf.service'
interface DomPdfForm {
pdf_driver: string
}
const props = withDefaults(
defineProps<{
configData?: Record<string, unknown>
isSaving?: boolean
isFetchingInitialData?: boolean
drivers?: PdfDriver[]
}>(),
{
configData: () => ({}),
isSaving: false,
isFetchingInitialData: false,
drivers: () => [],
}
)
const emit = defineEmits<{
'submit-data': [config: DomPdfForm]
'on-change-driver': [driver: string]
}>()
const { t } = useI18n()
const form = reactive<DomPdfForm>({
pdf_driver: 'dompdf',
})
const rules = computed(() => ({
pdf_driver: {
required: helpers.withMessage(t('validation.required'), required),
},
}))
const v$ = useVuelidate(rules, form)
onMounted(() => {
if (typeof props.configData.pdf_driver === 'string') {
form.pdf_driver = props.configData.pdf_driver
}
})
function onChangeDriver(): void {
v$.value.pdf_driver.$touch()
emit('on-change-driver', form.pdf_driver)
}
function saveConfig(): void {
v$.value.$touch()
if (v$.value.$invalid) {
return
}
emit('submit-data', { ...form })
}
</script>
<template>
<form @submit.prevent="saveConfig">
<BaseInputGrid>
<BaseInputGroup
:label="$t('settings.pdf.driver')"
:error="v$.pdf_driver.$error && v$.pdf_driver.$errors[0]?.$message"
required
>
<BaseMultiselect
v-model="form.pdf_driver"
:content-loading="isFetchingInitialData"
:options="drivers"
:can-deselect="false"
:invalid="v$.pdf_driver.$error"
@update:model-value="onChangeDriver"
/>
</BaseInputGroup>
</BaseInputGrid>
<div class="flex my-10">
<BaseButton
:disabled="isSaving"
:content-loading="isFetchingInitialData"
:loading="isSaving"
type="submit"
variant="primary"
>
<template #left="slotProps">
<BaseIcon
v-if="!isSaving"
name="ArrowDownOnSquareIcon"
:class="slotProps.class"
/>
</template>
{{ $t('general.save') }}
</BaseButton>
</div>
</form>
</template>

View File

@@ -0,0 +1,180 @@
<script setup lang="ts">
import { computed, onMounted, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { required, helpers } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import type { PdfDriver } from '@v2/api/services/pdf.service'
interface GotenbergForm {
pdf_driver: string
gotenberg_host: string
gotenberg_papersize: string
}
const props = withDefaults(
defineProps<{
configData?: Record<string, unknown>
isSaving?: boolean
isFetchingInitialData?: boolean
drivers?: PdfDriver[]
}>(),
{
configData: () => ({}),
isSaving: false,
isFetchingInitialData: false,
drivers: () => [],
}
)
const emit = defineEmits<{
'submit-data': [config: GotenbergForm]
'on-change-driver': [driver: string]
}>()
const { t } = useI18n()
const form = reactive<GotenbergForm>({
pdf_driver: 'gotenberg',
gotenberg_host: '',
gotenberg_papersize: '210mm 297mm',
})
function isValidServiceUrl(value: string): boolean {
if (!helpers.req(value)) {
return true
}
try {
const parsedUrl = new URL(value)
return (
(parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') &&
parsedUrl.hostname.length > 0
)
} catch {
return false
}
}
const rules = computed(() => ({
pdf_driver: {
required: helpers.withMessage(t('validation.required'), required),
},
gotenberg_host: {
required: helpers.withMessage(t('validation.required'), required),
validServiceUrl: helpers.withMessage(
t('validation.invalid_url'),
isValidServiceUrl
),
},
gotenberg_papersize: {
required: helpers.withMessage(t('validation.required'), required),
},
}))
const v$ = useVuelidate(rules, form)
onMounted(() => {
if (typeof props.configData.pdf_driver === 'string') {
form.pdf_driver = props.configData.pdf_driver
}
if (typeof props.configData.gotenberg_host === 'string') {
form.gotenberg_host = props.configData.gotenberg_host
}
if (typeof props.configData.gotenberg_papersize === 'string') {
form.gotenberg_papersize = props.configData.gotenberg_papersize
}
})
function onChangeDriver(): void {
v$.value.pdf_driver.$touch()
emit('on-change-driver', form.pdf_driver)
}
function saveConfig(): void {
v$.value.$touch()
if (v$.value.$invalid) {
return
}
emit('submit-data', { ...form })
}
</script>
<template>
<form @submit.prevent="saveConfig">
<BaseInputGrid>
<BaseInputGroup
:label="$t('settings.pdf.driver')"
:error="v$.pdf_driver.$error && v$.pdf_driver.$errors[0]?.$message"
required
>
<BaseMultiselect
v-model="form.pdf_driver"
:content-loading="isFetchingInitialData"
:options="drivers"
:can-deselect="false"
:invalid="v$.pdf_driver.$error"
@update:model-value="onChangeDriver"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.pdf.gotenberg_host')"
:error="
v$.gotenberg_host.$error && v$.gotenberg_host.$errors[0]?.$message
"
required
>
<BaseInput
v-model.trim="form.gotenberg_host"
:content-loading="isFetchingInitialData"
:invalid="v$.gotenberg_host.$error"
type="text"
name="gotenberg_host"
@input="v$.gotenberg_host.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.pdf.papersize')"
:help-text="$t('settings.pdf.papersize_hint')"
:error="
v$.gotenberg_papersize.$error &&
v$.gotenberg_papersize.$errors[0]?.$message
"
required
>
<BaseInput
v-model.trim="form.gotenberg_papersize"
:content-loading="isFetchingInitialData"
:invalid="v$.gotenberg_papersize.$error"
type="text"
name="gotenberg_papersize"
@input="v$.gotenberg_papersize.$touch()"
/>
</BaseInputGroup>
</BaseInputGrid>
<div class="flex my-10">
<BaseButton
:disabled="isSaving"
:content-loading="isFetchingInitialData"
:loading="isSaving"
type="submit"
variant="primary"
>
<template #left="slotProps">
<BaseIcon
v-if="!isSaving"
name="ArrowDownOnSquareIcon"
:class="slotProps.class"
/>
</template>
{{ $t('general.save') }}
</BaseButton>
</div>
</form>
</template>

View File

@@ -7,6 +7,11 @@ const AdminCompanyEditView = () => import('./views/AdminCompanyEditView.vue')
const AdminUsersView = () => import('./views/AdminUsersView.vue')
const AdminUserEditView = () => import('./views/AdminUserEditView.vue')
const AdminSettingsView = () => import('./views/AdminSettingsView.vue')
const AdminMailConfigView = () => import('./views/settings/AdminMailConfigView.vue')
const AdminPdfGenerationView = () => import('./views/settings/AdminPdfGenerationView.vue')
const AdminBackupView = () => import('./views/settings/AdminBackupView.vue')
const AdminFileDiskView = () => import('./views/settings/AdminFileDiskView.vue')
const AdminUpdateAppView = () => import('./views/settings/AdminUpdateAppView.vue')
export const adminRoutes: RouteRecordRaw[] = [
{
@@ -15,6 +20,7 @@ export const adminRoutes: RouteRecordRaw[] = [
meta: {
requiresAuth: true,
isSuperAdmin: true,
usesAdminBootstrap: true,
},
children: [
{
@@ -65,14 +71,17 @@ export const adminRoutes: RouteRecordRaw[] = [
isSuperAdmin: true,
},
children: [
{
path: '',
redirect: 'mail-configuration',
},
{
path: 'mail-configuration',
name: 'admin.settings.mail',
meta: {
isSuperAdmin: true,
},
// Loaded by settings sub-routes
component: { template: '<router-view />' },
component: AdminMailConfigView,
},
{
path: 'pdf-generation',
@@ -80,7 +89,7 @@ export const adminRoutes: RouteRecordRaw[] = [
meta: {
isSuperAdmin: true,
},
component: { template: '<router-view />' },
component: AdminPdfGenerationView,
},
{
path: 'backup',
@@ -88,7 +97,7 @@ export const adminRoutes: RouteRecordRaw[] = [
meta: {
isSuperAdmin: true,
},
component: { template: '<router-view />' },
component: AdminBackupView,
},
{
path: 'file-disk',
@@ -96,7 +105,7 @@ export const adminRoutes: RouteRecordRaw[] = [
meta: {
isSuperAdmin: true,
},
component: { template: '<router-view />' },
component: AdminFileDiskView,
},
{
path: 'update-app',
@@ -104,7 +113,7 @@ export const adminRoutes: RouteRecordRaw[] = [
meta: {
isSuperAdmin: true,
},
component: { template: '<router-view />' },
component: AdminUpdateAppView,
},
],
},

View File

@@ -0,0 +1,328 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useModalStore } from '@v2/stores/modal.store'
import { useDialogStore } from '@v2/stores/dialog.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { backupService, type Backup } from '@v2/api/services/backup.service'
import { diskService, type Disk } from '@v2/api/services/disk.service'
import {
getErrorTranslationKey,
handleApiError,
} from '@v2/utils/error-handling'
import AdminBackupModal from '@v2/features/admin/components/settings/AdminBackupModal.vue'
interface TableColumn {
key: string
label?: string
thClass?: string
tdClass?: string
sortable?: boolean
}
interface DiskOption extends Disk {
display_name: string
}
interface FetchParams {
page: number
filter: Record<string, unknown>
sort: { fieldName: string; order: string }
}
interface FetchResult {
data: Backup[]
pagination: {
totalPages: number
currentPage: number
totalCount: number
limit: number
}
}
const modalStore = useModalStore()
const dialogStore = useDialogStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const table = ref<{ refresh: () => void } | null>(null)
const disks = ref<DiskOption[]>([])
const selectedDisk = ref<DiskOption | null>(null)
const isFetchingInitialData = ref(false)
const backupError = ref('')
const backupColumns = computed<TableColumn[]>(() => [
{
key: 'path',
label: t('settings.backup.path'),
thClass: 'extra',
tdClass: 'font-medium text-heading',
},
{
key: 'created_at',
label: t('settings.backup.created_at'),
tdClass: 'font-medium text-heading',
},
{
key: 'size',
label: t('settings.backup.size'),
tdClass: 'font-medium text-heading',
},
{
key: 'actions',
label: '',
tdClass: 'text-right text-sm font-medium',
sortable: false,
},
])
watch(
selectedDisk,
(newDisk, oldDisk) => {
if (newDisk?.id && oldDisk?.id && newDisk.id !== oldDisk.id) {
refreshTable()
}
}
)
loadDisks()
async function loadDisks(): Promise<void> {
isFetchingInitialData.value = true
try {
const response = await diskService.list({ limit: 'all' })
disks.value = response.data.map((disk) => ({
...disk,
display_name: `${disk.name} - [${disk.driver}]`,
}))
selectedDisk.value =
disks.value.find((disk) => disk.set_as_default) ?? disks.value[0] ?? null
} catch (error: unknown) {
showApiError(error)
} finally {
isFetchingInitialData.value = false
}
}
async function fetchData({ page }: FetchParams): Promise<FetchResult> {
if (!selectedDisk.value) {
return emptyResult(page)
}
backupError.value = ''
try {
const response = await backupService.list({
disk: selectedDisk.value.driver,
file_disk_id: selectedDisk.value.id,
})
if (response.error) {
backupError.value = t('settings.backup.invalid_disk_credentials')
return emptyResult(page)
}
return {
data: response.backups,
pagination: {
totalPages: 1,
currentPage: 1,
totalCount: response.backups.length,
limit: response.backups.length || 1,
},
}
} catch (error: unknown) {
showApiError(error)
return emptyResult(page)
}
}
async function removeBackup(backup: Backup): Promise<void> {
if (!selectedDisk.value) {
return
}
const confirmed = await dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('settings.backup.backup_confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
if (!confirmed) {
return
}
try {
const response = await backupService.delete({
disk: selectedDisk.value.driver,
file_disk_id: selectedDisk.value.id,
path: backup.path,
})
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: t('settings.backup.deleted_message'),
})
refreshTable()
}
} catch (error: unknown) {
showApiError(error)
}
}
async function downloadBackup(backup: Backup): Promise<void> {
if (!selectedDisk.value) {
return
}
isFetchingInitialData.value = true
let objectUrl = ''
try {
const blob = await backupService.download({
disk: selectedDisk.value.driver,
file_disk_id: selectedDisk.value.id,
path: backup.path,
})
objectUrl = window.URL.createObjectURL(blob)
const downloadLink = document.createElement('a')
downloadLink.href = objectUrl
downloadLink.setAttribute(
'download',
backup.path.split('/').pop() ?? 'backup.zip'
)
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
} catch (error: unknown) {
showApiError(error)
} finally {
if (objectUrl) {
window.URL.revokeObjectURL(objectUrl)
}
isFetchingInitialData.value = false
}
}
function openCreateBackupModal(): void {
modalStore.openModal({
title: t('settings.backup.create_backup'),
componentName: 'AdminBackupModal',
size: 'sm',
data: {
disks: disks.value,
selectedDiskId: selectedDisk.value?.id ?? null,
},
refreshData: table.value?.refresh,
})
}
function refreshTable(): void {
table.value?.refresh()
}
function emptyResult(page: number): FetchResult {
return {
data: [],
pagination: {
totalPages: 1,
currentPage: page,
totalCount: 0,
limit: 1,
},
}
}
function showApiError(error: unknown): void {
const normalizedError = handleApiError(error)
const translationKey = getErrorTranslationKey(normalizedError.message)
notificationStore.showNotification({
type: 'error',
message: translationKey ? t(translationKey) : normalizedError.message,
})
}
</script>
<template>
<AdminBackupModal />
<BaseSettingCard
:title="$t('settings.backup.title', 1)"
:description="$t('settings.backup.description')"
>
<template #action>
<BaseButton variant="primary-outline" @click="openCreateBackupModal">
<template #left="slotProps">
<BaseIcon :class="slotProps.class" name="PlusIcon" />
</template>
{{ $t('settings.backup.new_backup') }}
</BaseButton>
</template>
<div class="grid my-14 md:grid-cols-3">
<BaseInputGroup
:label="$t('settings.disk.select_disk')"
:content-loading="isFetchingInitialData"
>
<BaseMultiselect
v-model="selectedDisk"
:content-loading="isFetchingInitialData"
:options="disks"
track-by="id"
value-prop="id"
label="display_name"
:placeholder="$t('settings.disk.select_disk')"
object
searchable
class="w-full"
/>
</BaseInputGroup>
</div>
<BaseErrorAlert
v-if="backupError"
class="mt-6"
:errors="[backupError]"
/>
<BaseTable
ref="table"
class="mt-10"
:show-filter="false"
:data="fetchData"
:columns="backupColumns"
>
<template #cell-actions="{ row }">
<BaseDropdown>
<template #activator>
<div class="inline-block">
<BaseIcon name="EllipsisHorizontalIcon" class="text-muted" />
</div>
</template>
<BaseDropdownItem @click="downloadBackup(row.data)">
<BaseIcon name="CloudArrowDownIcon" class="mr-3 text-body" />
{{ $t('general.download') }}
</BaseDropdownItem>
<BaseDropdownItem @click="removeBackup(row.data)">
<BaseIcon name="TrashIcon" class="mr-3 text-body" />
{{ $t('general.delete') }}
</BaseDropdownItem>
</BaseDropdown>
</template>
</BaseTable>
</BaseSettingCard>
</template>

View File

@@ -0,0 +1,295 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useModalStore } from '@v2/stores/modal.store'
import { useDialogStore } from '@v2/stores/dialog.store'
import { useGlobalStore } from '@v2/stores/global.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { diskService, type Disk } from '@v2/api/services/disk.service'
import {
getErrorTranslationKey,
handleApiError,
} from '@v2/utils/error-handling'
import AdminFileDiskModal from '@v2/features/admin/components/settings/AdminFileDiskModal.vue'
interface TableColumn {
key: string
label?: string
thClass?: string
tdClass?: string
sortable?: boolean
}
interface FetchParams {
page: number
filter: Record<string, unknown>
sort: { fieldName: string; order: string }
}
interface FetchResult {
data: Disk[]
pagination: {
totalPages: number
currentPage: number
totalCount: number
limit: number
}
}
const modalStore = useModalStore()
const dialogStore = useDialogStore()
const globalStore = useGlobalStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const table = ref<{ refresh: () => void } | null>(null)
const savePdfToDisk = ref(
(globalStore.globalSettings?.save_pdf_to_disk ?? 'NO') === 'YES'
)
const fileDiskColumns = computed<TableColumn[]>(() => [
{
key: 'name',
label: t('settings.disk.disk_name'),
thClass: 'extra',
tdClass: 'font-medium text-heading',
},
{
key: 'driver',
label: t('settings.disk.filesystem_driver'),
thClass: 'extra',
tdClass: 'font-medium text-heading',
},
{
key: 'type',
label: t('settings.disk.disk_type'),
thClass: 'extra',
tdClass: 'font-medium text-heading',
},
{
key: 'set_as_default',
label: t('settings.disk.is_default'),
thClass: 'extra',
tdClass: 'font-medium text-heading',
},
{
key: 'actions',
label: '',
tdClass: 'text-right text-sm font-medium',
sortable: false,
},
])
const savePdfToDiskField = computed<boolean>({
get: () => savePdfToDisk.value,
set: async (enabled) => {
savePdfToDisk.value = enabled
await globalStore.updateGlobalSettings({
data: {
settings: {
save_pdf_to_disk: enabled ? 'YES' : 'NO',
},
},
message: t('general.setting_updated'),
})
},
})
async function fetchData({ page, sort }: FetchParams): Promise<FetchResult> {
const response = await diskService.list({
orderByField: sort.fieldName || 'created_at',
orderBy: sort.order || 'desc',
page,
})
return {
data: response.data,
pagination: {
totalPages: response.meta.last_page,
currentPage: page,
totalCount: response.meta.total,
limit: Number(response.meta.per_page) || 5,
},
}
}
async function setDefaultDisk(id: number): Promise<void> {
const confirmed = await dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('settings.disk.set_default_disk_confirm'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
})
if (!confirmed) {
return
}
try {
await diskService.update(id, { set_as_default: true })
notificationStore.showNotification({
type: 'success',
message: t('settings.disk.success_set_default_disk'),
})
refreshTable()
} catch (error: unknown) {
showApiError(error)
}
}
async function removeDisk(id: number): Promise<void> {
const confirmed = await dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('settings.disk.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
if (!confirmed) {
return
}
try {
const response = await diskService.delete(id)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: t('settings.disk.deleted_message'),
})
refreshTable()
}
} catch (error: unknown) {
showApiError(error)
}
}
function openCreateDiskModal(): void {
modalStore.openModal({
title: t('settings.disk.new_disk'),
componentName: 'AdminFileDiskModal',
size: 'lg',
refreshData: table.value?.refresh,
})
}
function openEditDiskModal(disk: Disk): void {
modalStore.openModal({
title: t('settings.disk.edit_file_disk'),
componentName: 'AdminFileDiskModal',
id: disk.id,
data: disk,
size: 'lg',
refreshData: table.value?.refresh,
})
}
function canShowActions(disk: Disk): boolean {
return !disk.set_as_default || disk.type !== 'SYSTEM'
}
function refreshTable(): void {
table.value?.refresh()
}
function showApiError(error: unknown): void {
const normalizedError = handleApiError(error)
const translationKey = getErrorTranslationKey(normalizedError.message)
notificationStore.showNotification({
type: 'error',
message: translationKey ? t(translationKey) : normalizedError.message,
})
}
</script>
<template>
<AdminFileDiskModal />
<BaseSettingCard
:title="$t('settings.disk.title', 1)"
:description="$t('settings.disk.description')"
>
<template #action>
<BaseButton variant="primary-outline" @click="openCreateDiskModal">
<template #left="slotProps">
<BaseIcon :class="slotProps.class" name="PlusIcon" />
</template>
{{ $t('settings.disk.new_disk') }}
</BaseButton>
</template>
<BaseTable
ref="table"
class="mt-16"
:data="fetchData"
:columns="fileDiskColumns"
>
<template #cell-set_as_default="{ row }">
<span
:class="
row.data.set_as_default
? 'bg-success text-status-green'
: 'bg-surface-muted text-muted'
"
class="inline-flex rounded-full px-2 py-1 text-xs font-medium uppercase"
>
{{
row.data.set_as_default ? $t('general.yes') : $t('general.no')
}}
</span>
</template>
<template #cell-actions="{ row }">
<BaseDropdown v-if="canShowActions(row.data)">
<template #activator>
<div class="inline-block">
<BaseIcon name="EllipsisHorizontalIcon" class="text-muted" />
</div>
</template>
<BaseDropdownItem
v-if="!row.data.set_as_default"
@click="setDefaultDisk(row.data.id)"
>
<BaseIcon class="mr-3 text-body" name="CheckCircleIcon" />
{{ $t('settings.disk.set_default_disk') }}
</BaseDropdownItem>
<BaseDropdownItem
v-if="row.data.type !== 'SYSTEM'"
@click="openEditDiskModal(row.data)"
>
<BaseIcon name="PencilIcon" class="mr-3 text-body" />
{{ $t('general.edit') }}
</BaseDropdownItem>
<BaseDropdownItem
v-if="row.data.type !== 'SYSTEM' && !row.data.set_as_default"
@click="removeDisk(row.data.id)"
>
<BaseIcon name="TrashIcon" class="mr-3 text-body" />
{{ $t('general.delete') }}
</BaseDropdownItem>
</BaseDropdown>
</template>
</BaseTable>
<BaseDivider class="mt-8 mb-2" />
<BaseSwitchSection
v-model="savePdfToDiskField"
:title="$t('settings.disk.save_pdf_to_disk')"
:description="$t('settings.disk.disk_setting_description')"
/>
</BaseSettingCard>
</template>

View File

@@ -0,0 +1,127 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useModalStore } from '@v2/stores/modal.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { mailService } from '@v2/api/services/mail.service'
import type { MailConfig, MailDriver } from '@v2/api/services/mail.service'
import SmtpMailDriver from '@v2/features/company/settings/components/SmtpMailDriver.vue'
import MailgunMailDriver from '@v2/features/company/settings/components/MailgunMailDriver.vue'
import SesMailDriver from '@v2/features/company/settings/components/SesMailDriver.vue'
import BasicMailDriver from '@v2/features/company/settings/components/BasicMailDriver.vue'
import MailTestModal from '@v2/features/company/settings/components/MailTestModal.vue'
const { t } = useI18n()
const modalStore = useModalStore()
const notificationStore = useNotificationStore()
const isSaving = ref(false)
const isFetchingInitialData = ref(false)
const mailConfigData = ref<Record<string, unknown> | null>(null)
const mailDrivers = ref<MailDriver[]>([])
const currentMailDriver = ref('smtp')
loadData()
async function loadData(): Promise<void> {
isFetchingInitialData.value = true
try {
const [driversResponse, configResponse] = await Promise.all([
mailService.getDrivers(),
mailService.getConfig(),
])
mailDrivers.value = driversResponse
mailConfigData.value = configResponse
currentMailDriver.value = configResponse.mail_driver ?? 'smtp'
} finally {
isFetchingInitialData.value = false
}
}
const mailDriver = computed(() => {
switch (currentMailDriver.value) {
case 'mailgun':
return MailgunMailDriver
case 'ses':
return SesMailDriver
case 'sendmail':
case 'mail':
return BasicMailDriver
default:
return SmtpMailDriver
}
})
function changeDriver(value: string): void {
currentMailDriver.value = value
if (mailConfigData.value) {
mailConfigData.value.mail_driver = value
}
}
async function saveEmailConfig(value: MailConfig): Promise<void> {
isSaving.value = true
try {
const response = await mailService.saveConfig(value)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: t(`settings.success.${response.success}`),
})
if (mailConfigData.value) {
mailConfigData.value = {
...mailConfigData.value,
...value,
}
}
}
} finally {
isSaving.value = false
}
}
function openMailTestModal(): void {
modalStore.openModal({
title: t('general.test_mail_conf'),
componentName: 'MailTestModal',
size: 'sm',
})
}
</script>
<template>
<MailTestModal store-type="global" />
<BaseSettingCard
:title="$t('settings.mail.mail_config')"
:description="$t('settings.mail.mail_config_desc')"
>
<div v-if="mailConfigData" class="mt-14">
<component
:is="mailDriver"
:config-data="mailConfigData"
:is-saving="isSaving"
:mail-drivers="mailDrivers"
:is-fetching-initial-data="isFetchingInitialData"
@on-change-driver="changeDriver"
@submit-data="saveEmailConfig"
>
<BaseButton
variant="primary-outline"
type="button"
class="ml-2"
:content-loading="isFetchingInitialData"
@click="openMailTestModal"
>
{{ $t('general.test_mail_conf') }}
</BaseButton>
</component>
</div>
</BaseSettingCard>
</template>

View File

@@ -0,0 +1,96 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useNotificationStore } from '@v2/stores/notification.store'
import { pdfService } from '@v2/api/services/pdf.service'
import type { PdfConfig, PdfDriver } from '@v2/api/services/pdf.service'
import AdminPdfDomDriver from '@v2/features/admin/components/settings/AdminPdfDomDriver.vue'
import AdminPdfGotenbergDriver from '@v2/features/admin/components/settings/AdminPdfGotenbergDriver.vue'
const { t } = useI18n()
const notificationStore = useNotificationStore()
const isSaving = ref(false)
const isFetchingInitialData = ref(false)
const configData = ref<Record<string, unknown> | null>(null)
const drivers = ref<PdfDriver[]>([])
const currentDriver = ref('dompdf')
loadData()
async function loadData(): Promise<void> {
isFetchingInitialData.value = true
try {
const [driversResponse, configResponse] = await Promise.all([
pdfService.getDrivers(),
pdfService.getConfig(),
])
drivers.value = driversResponse
configData.value = configResponse
currentDriver.value = configResponse.pdf_driver ?? 'dompdf'
} finally {
isFetchingInitialData.value = false
}
}
const pdfDriver = computed(() => {
if (currentDriver.value === 'gotenberg') {
return AdminPdfGotenbergDriver
}
return AdminPdfDomDriver
})
function changeDriver(value: string): void {
currentDriver.value = value
if (configData.value) {
configData.value.pdf_driver = value
}
}
async function saveConfig(value: PdfConfig): Promise<void> {
isSaving.value = true
try {
const response = await pdfService.saveConfig(value)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: t(`settings.pdf.${response.success}`),
})
if (configData.value) {
configData.value = {
...configData.value,
...value,
}
}
}
} finally {
isSaving.value = false
}
}
</script>
<template>
<BaseSettingCard
:title="$t('settings.pdf.pdf_configuration')"
:description="$t('settings.pdf.section_description')"
>
<div v-if="configData" class="mt-14">
<component
:is="pdfDriver"
:config-data="configData"
:is-saving="isSaving"
:drivers="drivers"
:is-fetching-initial-data="isFetchingInitialData"
@on-change-driver="changeDriver"
@submit-data="saveConfig"
/>
</div>
</BaseSettingCard>
</template>

View File

@@ -0,0 +1,481 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDialogStore } from '@v2/stores/dialog.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { settingService } from '@v2/api/services/setting.service'
import { updateService, type UpdateRelease } from '@v2/api/services/update.service'
import {
getErrorTranslationKey,
handleApiError,
} from '@v2/utils/error-handling'
type UpdateStepKey =
| 'download'
| 'unzip'
| 'copy'
| 'delete'
| 'migrate'
| 'finish'
type UpdateStepStatus = 'pending' | 'running' | 'finished' | 'error'
interface UpdateStep {
key: UpdateStepKey
translationKey: string
status: UpdateStepStatus
time: string | null
}
const dialogStore = useDialogStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const isCheckingForUpdate = ref(false)
const isUpdating = ref(false)
const insiderChannel = ref(false)
const currentVersion = ref('')
const updateRelease = ref<UpdateRelease | null>(null)
const isMinorUpdate = ref(false)
const updateSteps = ref<UpdateStep[]>([
{
key: 'download',
translationKey: 'settings.update_app.download_zip_file',
status: 'pending',
time: null,
},
{
key: 'unzip',
translationKey: 'settings.update_app.unzipping_package',
status: 'pending',
time: null,
},
{
key: 'copy',
translationKey: 'settings.update_app.copying_files',
status: 'pending',
time: null,
},
{
key: 'delete',
translationKey: 'settings.update_app.deleting_files',
status: 'pending',
time: null,
},
{
key: 'migrate',
translationKey: 'settings.update_app.running_migrations',
status: 'pending',
time: null,
},
{
key: 'finish',
translationKey: 'settings.update_app.finishing_update',
status: 'pending',
time: null,
},
])
const isUpdateAvailable = computed<boolean>(() => {
return Boolean(updateRelease.value)
})
const requirementEntries = computed(() => {
return Object.entries(updateRelease.value?.extensions ?? {})
})
const allowToUpdate = computed<boolean>(() => {
return requirementEntries.value.every(([, isAvailable]) => isAvailable)
})
onMounted(async () => {
window.addEventListener('beforeunload', preventUnloadDuringUpdate)
await loadCurrentVersion()
})
onBeforeUnmount(() => {
window.removeEventListener('beforeunload', preventUnloadDuringUpdate)
})
async function loadCurrentVersion(): Promise<void> {
try {
const response = await settingService.getAppVersion()
currentVersion.value = response.version
insiderChannel.value = response.channel === 'insider'
} catch (error: unknown) {
showApiError(error)
}
}
async function checkUpdate(): Promise<void> {
isCheckingForUpdate.value = true
try {
const response = await updateService.check(
insiderChannel.value ? 'insider' : 'stable'
)
if (!response.release) {
updateRelease.value = null
notificationStore.showNotification({
type: 'info',
message: t('settings.update_app.latest_message'),
})
return
}
updateRelease.value = response.release
isMinorUpdate.value = Boolean(response.is_minor)
resetUpdateProgress()
} catch (error: unknown) {
updateRelease.value = null
showApiError(error)
} finally {
isCheckingForUpdate.value = false
}
}
async function startUpdate(): Promise<void> {
if (!updateRelease.value) {
return
}
const confirmed = await dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('settings.update_app.update_warning'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
if (!confirmed) {
return
}
if (!allowToUpdate.value) {
notificationStore.showNotification({
type: 'error',
message: t('settings.update_app.requirements_not_met'),
})
return
}
resetUpdateProgress()
isUpdating.value = true
let updatePath: string | null = null
try {
for (const step of updateSteps.value) {
step.status = 'running'
switch (step.key) {
case 'download': {
const response = await updateService.download({
version: updateRelease.value.version,
})
updatePath = extractPath(response.path)
break
}
case 'unzip': {
if (!updatePath) {
throw new Error('Missing update package path.')
}
const response = await updateService.unzip({ path: updatePath })
updatePath = extractPath(response.path) ?? updatePath
break
}
case 'copy': {
if (!updatePath) {
throw new Error('Missing extracted update path.')
}
const response = await updateService.copy({ path: updatePath })
updatePath = extractPath(response.path) ?? updatePath
break
}
case 'delete':
await updateService.delete({
deleted_files: updateRelease.value.deleted_files ?? null,
})
break
case 'migrate':
await updateService.migrate()
break
case 'finish':
await updateService.finish({
installed: currentVersion.value,
version: updateRelease.value.version,
})
break
}
step.status = 'finished'
step.time = new Date().toLocaleTimeString()
}
notificationStore.showNotification({
type: 'success',
message: t('settings.update_app.update_success'),
})
setTimeout(() => {
window.location.reload()
}, 3000)
} catch (error: unknown) {
const currentStep = updateSteps.value.find((step) => step.status === 'running')
if (currentStep) {
currentStep.status = 'error'
currentStep.time = new Date().toLocaleTimeString()
}
showApiError(error)
} finally {
isUpdating.value = false
}
}
function resetUpdateProgress(): void {
updateSteps.value = updateSteps.value.map((step) => ({
...step,
status: 'pending',
time: null,
}))
}
function statusClass(step: UpdateStep): string {
if (step.status === 'finished') {
return 'text-status-green bg-success'
}
if (step.status === 'running') {
return 'text-primary-700 bg-primary-100'
}
if (step.status === 'error') {
return 'text-danger bg-red-200'
}
return 'text-muted bg-surface-muted'
}
function preventUnloadDuringUpdate(event: BeforeUnloadEvent): void {
if (!isUpdating.value) {
return
}
event.preventDefault()
event.returnValue = 'Update is in progress!'
}
function extractPath(value: unknown): string | null {
if (typeof value === 'string') {
return value
}
return null
}
function showApiError(error: unknown): void {
const normalizedError = handleApiError(error)
const translationKey = getErrorTranslationKey(normalizedError.message)
notificationStore.showNotification({
type: 'error',
message: translationKey ? t(translationKey) : normalizedError.message,
})
}
</script>
<template>
<BaseSettingCard
:title="$t('settings.update_app.title')"
:description="$t('settings.update_app.description')"
>
<div class="pb-8">
<label class="text-sm font-medium input-label">
{{ $t('settings.update_app.current_version') }}
</label>
<div class="w-full border-b-2 border-line-light border-solid pb-4">
<div
class="my-2 inline-block rounded-md border border-line-default bg-surface-muted p-3 text-sm text-body"
>
{{ currentVersion }}
</div>
</div>
<div class="pt-4">
<BaseCheckbox
v-model="insiderChannel"
:label="$t('settings.update_app.insider_consent')"
/>
</div>
<BaseButton
:loading="isCheckingForUpdate"
:disabled="isCheckingForUpdate || isUpdating"
variant="primary-outline"
class="mt-6"
@click="checkUpdate"
>
{{ $t('settings.update_app.check_update') }}
</BaseButton>
<BaseDivider v-if="isUpdateAvailable" class="mt-6 mb-4" />
<div v-if="isUpdateAvailable && updateRelease && !isUpdating" class="mt-4">
<BaseHeading type="heading-title" class="mb-2">
{{ $t('settings.update_app.avail_update') }}
</BaseHeading>
<div class="mb-3 rounded-md bg-primary-50 p-4">
<div class="flex">
<div class="shrink-0">
<BaseIcon
name="InformationCircleIcon"
class="h-5 w-5 text-primary-400"
/>
</div>
<div class="ml-3">
<h3 class="text-sm font-medium text-primary-800">
{{ $t('general.note') }}
</h3>
<div class="mt-2 text-sm text-primary-700">
<p>{{ $t('settings.update_app.update_warning') }}</p>
</div>
</div>
</div>
</div>
<label class="text-sm font-medium input-label">
{{ $t('settings.update_app.next_version') }}
</label>
<br />
<div
class="my-2 inline-block rounded-md border border-line-default bg-surface-muted p-3 text-sm text-body"
>
{{ updateRelease.version }}
<span v-if="isMinorUpdate" class="ml-2 text-xs text-muted">
(minor)
</span>
</div>
<div
v-if="updateRelease.description"
class="update-rich-text mt-4 max-w-[680px] text-sm leading-snug text-muted"
v-html="updateRelease.description"
/>
<div
v-if="updateRelease.changelog"
class="update-rich-text mt-4 max-w-[680px] text-sm leading-snug text-muted"
v-html="updateRelease.changelog"
/>
<div v-if="requirementEntries.length" class="mt-6">
<label class="text-sm font-medium input-label">
{{ $t('settings.update_app.requirements') }}
</label>
<table class="mt-2 w-full max-w-xl border border-line-default">
<tbody>
<tr
v-for="([extension, available], index) in requirementEntries"
:key="extension"
:class="index === requirementEntries.length - 1 ? '' : 'border-b border-line-default'"
>
<td class="p-3 text-sm">
{{ extension }}
</td>
<td class="p-3 text-right text-sm">
<span
:class="available ? 'bg-success' : 'bg-red-500'"
class="inline-block h-4 w-4 rounded-full"
/>
</td>
</tr>
</tbody>
</table>
</div>
<div
v-if="!allowToUpdate"
class="mt-6 rounded-md bg-red-50 p-4 text-sm text-red-700"
>
{{ $t('settings.update_app.requirements_not_met') }}
</div>
<BaseButton
class="mt-10"
variant="primary"
:disabled="!allowToUpdate"
@click="startUpdate"
>
{{ $t('settings.update_app.update') }}
</BaseButton>
</div>
<div v-if="isUpdating" class="mt-4">
<div class="mb-6 flex items-start justify-between">
<div>
<BaseHeading type="heading-title" class="mb-2">
{{ $t('settings.update_app.update_progress') }}
</BaseHeading>
<p class="max-w-[480px] text-sm leading-snug text-muted">
{{ $t('settings.update_app.progress_text') }}
</p>
</div>
<BaseIcon
name="ArrowPathIcon"
class="h-6 w-6 animate-spin text-primary-400"
/>
</div>
<ul class="w-full list-none p-0">
<li
v-for="step in updateSteps"
:key="step.key"
class="flex w-full justify-between border-b border-line-default py-3 last:border-b-0"
>
<p class="m-0 text-sm leading-8">{{ $t(step.translationKey) }}</p>
<div class="flex items-center">
<span v-if="step.time" class="mr-3 text-xs text-muted">
{{ step.time }}
</span>
<span
:class="statusClass(step)"
class="block rounded-full px-3 py-1 text-sm uppercase"
>
{{ step.status }}
</span>
</div>
</li>
</ul>
</div>
</div>
</BaseSettingCard>
</template>
<style scoped>
.update-rich-text :deep(ul) {
list-style: disc;
margin-left: 1.5rem;
}
.update-rich-text :deep(li) {
margin-bottom: 0.25rem;
}
</style>

View File

@@ -38,15 +38,15 @@ export const authRoutes: RouteRecordRaw[] = [
title: 'Reset Password',
},
},
{
path: '/register',
name: 'register-with-invitation',
component: RegisterWithInvitationView,
meta: {
requiresAuth: false,
title: 'Register',
},
},
],
},
{
path: '/register',
name: 'register-with-invitation',
component: RegisterWithInvitationView,
meta: {
requiresAuth: false,
title: 'Register',
},
},
]

View File

@@ -93,7 +93,11 @@ async function onSubmit(): Promise<void> {
isSent.value = true
} catch (err: unknown) {
handleApiError(err)
const normalized = handleApiError(err)
notificationStore.showNotification({
type: 'error',
message: normalized.message,
})
} finally {
isLoading.value = false
}

View File

@@ -115,7 +115,13 @@ async function onSubmit(): Promise<void> {
type: 'success',
message: 'Logged in successfully.',
})
} catch {
} catch (err: unknown) {
const { handleApiError } = await import('../../../utils/error-handling')
const normalized = handleApiError(err)
notificationStore.showNotification({
type: 'error',
message: normalized.message,
})
isLoading.value = false
}
}

View File

@@ -1,123 +1,128 @@
<template>
<div class="flex items-center justify-center min-h-screen bg-surface-secondary">
<div class="w-full max-w-md p-8">
<!-- Logo -->
<div class="mb-8 text-center">
<MainLogo
v-if="!loginPageLogo"
class="inline-block w-48 h-auto text-primary-500"
/>
<img
v-else
:src="loginPageLogo"
class="inline-block w-48 h-auto"
/>
</div>
<!-- Loading -->
<div v-if="isLoading" class="mt-12 text-center">
<BaseSpinner class="w-8 h-8 text-primary-400 mx-auto" />
<p class="text-muted mt-4 text-sm">Loading invitation details...</p>
</div>
<!-- Loading -->
<div v-if="isLoading" class="text-center">
<p class="text-muted">Loading invitation details...</p>
</div>
<!-- Invalid/Expired -->
<div v-else-if="error" class="mt-12 text-center">
<BaseIcon
name="ExclamationCircleIcon"
class="w-12 h-12 mx-auto text-red-400 mb-4"
/>
<h2 class="text-lg font-semibold text-heading mb-2">
Invalid Invitation
</h2>
<p class="text-sm text-muted mb-4">{{ error }}</p>
<router-link
to="/login"
class="text-sm text-primary-400 hover:text-primary-500"
>
Go to Login
</router-link>
</div>
<!-- Invalid/Expired -->
<div v-else-if="error" class="text-center">
<BaseIcon
name="ExclamationCircleIcon"
class="w-16 h-16 mx-auto text-red-400 mb-4"
<!-- Registration Form -->
<div v-else class="mt-12">
<div class="mb-8">
<h1 class="text-2xl font-semibold text-heading">
Create Your Account
</h1>
<p class="text-sm text-muted mt-2">
You've been invited to join
<strong class="text-heading">{{ invitationDetails.company_name }}</strong>
as <strong class="text-heading">{{ invitationDetails.role_name }}</strong>
</p>
</div>
<form @submit.prevent="submitRegistration">
<BaseInputGroup
label="Name"
:error="v$.name.$error && v$.name.$errors[0].$message"
class="mb-4"
required
>
<BaseInput
v-model="form.name"
:invalid="v$.name.$error"
focus
@input="v$.name.$touch()"
/>
<h1 class="text-xl font-semibold text-heading mb-2">
Invalid Invitation
</h1>
<p class="text-muted">{{ error }}</p>
<router-link to="/login" class="text-primary-500 mt-4 inline-block">
Go to Login
</BaseInputGroup>
<BaseInputGroup label="Email" class="mb-4">
<BaseInput
v-model="form.email"
type="email"
disabled
/>
</BaseInputGroup>
<BaseInputGroup
label="Password"
:error="v$.password.$error && v$.password.$errors[0].$message"
class="mb-4"
required
>
<BaseInput
v-model="form.password"
:type="isShowPassword ? 'text' : 'password'"
:invalid="v$.password.$error"
@input="v$.password.$touch()"
>
<template #right>
<BaseIcon
:name="isShowPassword ? 'EyeIcon' : 'EyeSlashIcon'"
class="mr-1 text-muted cursor-pointer"
@click="isShowPassword = !isShowPassword"
/>
</template>
</BaseInput>
</BaseInputGroup>
<BaseInputGroup
label="Confirm Password"
:error="
v$.password_confirmation.$error &&
v$.password_confirmation.$errors[0].$message
"
class="mb-4"
required
>
<BaseInput
v-model="form.password_confirmation"
:type="isShowConfirmPassword ? 'text' : 'password'"
:invalid="v$.password_confirmation.$error"
@input="v$.password_confirmation.$touch()"
>
<template #right>
<BaseIcon
:name="isShowConfirmPassword ? 'EyeIcon' : 'EyeSlashIcon'"
class="mr-1 text-muted cursor-pointer"
@click="isShowConfirmPassword = !isShowConfirmPassword"
/>
</template>
</BaseInput>
</BaseInputGroup>
<div class="mt-5 mb-8">
<router-link
to="/login"
class="text-sm text-primary-400 hover:text-body"
>
Already have an account? Log in
</router-link>
</div>
<!-- Registration Form -->
<div v-else>
<div class="text-center mb-6">
<h1 class="text-2xl font-semibold text-heading">
Create Your Account
</h1>
<p class="text-muted mt-2">
You've been invited to join
<strong>{{ invitationDetails.company_name }}</strong> as
<strong>{{ invitationDetails.role_name }}</strong>
</p>
</div>
<BaseCard class="p-6">
<form @submit.prevent="submitRegistration">
<div class="space-y-4">
<BaseInputGroup
label="Name"
:error="v$.name.$error && v$.name.$errors[0].$message"
required
>
<BaseInput
v-model="form.name"
:invalid="v$.name.$error"
@input="v$.name.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup label="Email">
<BaseInput
v-model="form.email"
type="email"
disabled
/>
</BaseInputGroup>
<BaseInputGroup
label="Password"
:error="v$.password.$error && v$.password.$errors[0].$message"
required
>
<BaseInput
v-model="form.password"
type="password"
:invalid="v$.password.$error"
@input="v$.password.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
label="Confirm Password"
:error="
v$.password_confirmation.$error &&
v$.password_confirmation.$errors[0].$message
"
required
>
<BaseInput
v-model="form.password_confirmation"
type="password"
:invalid="v$.password_confirmation.$error"
@input="v$.password_confirmation.$touch()"
/>
</BaseInputGroup>
</div>
<BaseButton
:loading="isSubmitting"
:disabled="isSubmitting"
class="w-full mt-6"
type="submit"
>
Create Account & Join
</BaseButton>
</form>
</BaseCard>
<div class="text-center mt-4">
<router-link to="/login" class="text-sm text-muted hover:text-primary-500">
Already have an account? Log in
</router-link>
</div>
</div>
</div>
<BaseButton
:loading="isSubmitting"
:disabled="isSubmitting"
type="submit"
>
Create Account & Join
</BaseButton>
</form>
</div>
</template>
@@ -127,8 +132,6 @@ import { useRoute, useRouter } from 'vue-router'
import { helpers, required, minLength, sameAs } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { authService } from '../../../api/services/auth.service'
import * as ls from '../../../utils/local-storage'
import MainLogo from '../../../components/icons/MainLogo.vue'
interface InvitationDetailsData {
email: string
@@ -146,12 +149,10 @@ interface RegistrationForm {
const route = useRoute()
const router = useRouter()
const loginPageLogo = computed<string | false>(() => {
return (window as Record<string, unknown>).login_page_logo as string || false
})
const isLoading = ref<boolean>(true)
const isSubmitting = ref<boolean>(false)
const isShowPassword = ref<boolean>(false)
const isShowConfirmPassword = ref<boolean>(false)
const error = ref<string | null>(null)
const invitationDetails = ref<InvitationDetailsData>({
email: '',
@@ -182,7 +183,7 @@ const rules = computed(() => ({
const v$ = useVuelidate(
rules,
computed(() => form)
computed(() => form),
)
const token = computed<string>(() => route.query.invitation as string)
@@ -195,12 +196,11 @@ onMounted(async () => {
}
try {
const response = await authService.getInvitationDetails(token.value)
const details = response.data
const details = await authService.getInvitationDetails(token.value) as unknown as InvitationDetailsData
invitationDetails.value = {
email: details.email,
company_name: details.company_name,
role_name: details.invited_by,
role_name: details.role_name,
}
form.email = details.email
} catch {
@@ -217,17 +217,27 @@ async function submitRegistration(): Promise<void> {
isSubmitting.value = true
try {
await authService.registerWithInvitation({
const response = await authService.registerWithInvitation({
name: form.name,
email: form.email,
password: form.password,
password_confirmation: form.password_confirmation,
token: token.value,
invitation_token: token.value,
})
// Save the auth token before navigating (matching old version's pattern)
localStorage.setItem('auth.token', `Bearer ${response.token}`)
router.push('/admin/dashboard')
} catch {
// Validation errors handled by http interceptor
} catch (err: unknown) {
const { handleApiError } = await import('../../../utils/error-handling')
const { useNotificationStore } = await import('../../../stores/notification.store')
const normalized = handleApiError(err)
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'error',
message: normalized.message,
})
} finally {
isSubmitting.value = false
}

View File

@@ -157,7 +157,11 @@ async function onSubmit(): Promise<void> {
router.push('/login')
} catch (err: unknown) {
handleApiError(err)
const normalized = handleApiError(err)
notificationStore.showNotification({
type: 'error',
message: normalized.message,
})
} finally {
isLoading.value = false
}

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { computed, watch } from 'vue'
import lodash from 'lodash'
import moment from 'moment'
import { customFieldService } from '@v2/api/services/custom-field.service'
@@ -51,16 +51,32 @@ const props = withDefaults(
}
)
const customFields = ref<CustomFieldItem[]>([])
const storeData = computed(() => {
const data = props.store[props.storeProp]
if (!data) {
return null
}
if (!Array.isArray(data.customFields)) {
data.customFields = []
}
if (!Array.isArray(data.fields)) {
data.fields = []
}
return data
})
getInitialCustomFields()
function mergeExistingValues(): void {
if (props.isEdit && props.store[props.storeProp]) {
props.store[props.storeProp].fields.forEach((field) => {
const existingIndex = props.store[
props.storeProp
].customFields.findIndex((f) => f.id === field.custom_field_id)
if (props.isEdit && storeData.value) {
storeData.value.fields.forEach((field) => {
const existingIndex = storeData.value?.customFields.findIndex(
(f) => f.id === field.custom_field_id
) ?? -1
if (existingIndex > -1) {
let value: string | boolean | number | null = field.default_answer
@@ -72,7 +88,7 @@ function mergeExistingValues(): void {
).format('YYYY-MM-DD HH:mm')
}
props.store[props.storeProp].customFields[existingIndex] = {
storeData.value.customFields[existingIndex] = {
...field,
id: field.custom_field_id ?? field.id,
value,
@@ -89,6 +105,10 @@ function mergeExistingValues(): void {
}
async function getInitialCustomFields(): Promise<void> {
if (!storeData.value) {
return
}
const res = await customFieldService.list({
type: props.type ?? undefined,
limit: 'all',
@@ -99,7 +119,7 @@ async function getInitialCustomFields(): Promise<void> {
d.value = d.default_answer
})
props.store[props.storeProp].customFields = lodash.sortBy(
storeData.value.customFields = lodash.sortBy(
data,
(_cf: CustomFieldItem) => _cf.order
)
@@ -108,7 +128,7 @@ async function getInitialCustomFields(): Promise<void> {
}
watch(
() => props.store[props.storeProp]?.fields,
() => storeData.value?.fields,
() => {
mergeExistingValues()
}
@@ -118,14 +138,14 @@ watch(
<template>
<div
v-if="
store[storeProp] &&
store[storeProp].customFields.length > 0 &&
storeData &&
storeData.customFields.length > 0 &&
!isLoading
"
>
<BaseInputGrid :layout="gridLayout">
<SingleField
v-for="(field, index) in store[storeProp].customFields"
v-for="(field, index) in storeData.customFields"
:key="field.id"
:custom-field-scope="customFieldScope"
:store="store"

View File

@@ -4,22 +4,10 @@ import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useCustomerStore } from '../store'
import { useCompanyStore } from '@v2/stores/company.store'
import { customerService } from '@v2/api/services/customer.service'
import LineChart from '@v2/components/charts/LineChart.vue'
import ChartPlaceholder from './CustomerChartPlaceholder.vue'
import CustomerInfo from './CustomerInfo.vue'
interface ChartData {
salesTotal: number
totalReceipts: number
totalExpenses: number
netProfit: number
expenseTotals: number[]
netProfits: number[]
months: string[]
receiptTotals: number[]
invoiceTotals: number[]
}
import type { CustomerStatsChartData } from '@v2/api/services/customer.service'
interface YearOption {
label: string
@@ -32,7 +20,7 @@ const { t } = useI18n()
const route = useRoute()
const isLoading = ref<boolean>(false)
const chartData = reactive<Partial<ChartData>>({})
const chartData = reactive<Partial<CustomerStatsChartData>>({})
const years = reactive<YearOption[]>([
{ label: t('dateRange.this_year'), value: 'This year' },
{ label: t('dateRange.previous_year'), value: 'Previous year' },
@@ -58,21 +46,24 @@ watch(
async function loadCustomer(): Promise<void> {
isLoading.value = false
const response = await customerService.getStats(Number(route.params.id))
const response = await customerStore.fetchViewCustomer({
id: Number(route.params.id),
})
if (response.data) {
const meta = (response as Record<string, unknown>).meta as Record<string, unknown> | undefined
if (meta?.chartData) {
Object.assign(chartData, meta.chartData)
}
if (response.meta.chartData) {
Object.assign(chartData, response.meta.chartData)
}
isLoading.value = true
}
async function onChangeYear(data: string): Promise<boolean> {
const params: Record<string, unknown> = {
id: route.params.id,
const params: {
id: number
previous_year?: boolean
this_year?: boolean
} = {
id: Number(route.params.id),
}
if (data === 'Previous year') {
@@ -81,14 +72,10 @@ async function onChangeYear(data: string): Promise<boolean> {
params.this_year = true
}
const response = await customerService.getStats(
Number(route.params.id),
params
)
const response = await customerStore.fetchViewCustomer(params)
const meta = (response as Record<string, unknown>).meta as Record<string, unknown> | undefined
if (meta?.chartData) {
Object.assign(chartData, meta.chartData)
if (response.meta.chartData) {
Object.assign(chartData, response.meta.chartData)
}
return true

View File

@@ -1,12 +1,13 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { useCustomerStore } from '../store'
import { useDialogStore } from '../../../../stores/dialog.store'
import { useUserStore } from '../../../../stores/user.store'
interface RowData {
id: number
id?: number | string | null
[key: string]: unknown
}
@@ -40,7 +41,33 @@ const userStore = useUserStore()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const isDetailView = computed<boolean>(() => route.name === 'customers.view')
const customerId = computed<number | null>(() => {
const rowId = normalizeCustomerId(props.row?.id)
if (rowId !== null) {
return rowId
}
if (isDetailView.value) {
return normalizeCustomerId(route.params.id)
}
return null
})
function normalizeCustomerId(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) {
return value
}
if (typeof value === 'string' && value.trim() !== '') {
const parsedValue = Number(value)
return Number.isFinite(parsedValue) ? parsedValue : null
}
return null
}
function removeCustomer(id: number): void {
dialogStore
@@ -63,12 +90,20 @@ function removeCustomer(id: number): void {
}
})
}
function onRemoveCustomer(): void {
if (customerId.value === null) {
return
}
removeCustomer(customerId.value)
}
</script>
<template>
<BaseDropdown :content-loading="customerStore.isFetchingViewData">
<template #activator>
<BaseButton v-if="route.name === 'customers.view'" variant="primary">
<BaseButton v-if="isDetailView" variant="primary">
<BaseIcon name="EllipsisHorizontalIcon" class="h-5 text-white" />
</BaseButton>
<BaseIcon v-else name="EllipsisHorizontalIcon" class="h-5 text-muted" />
@@ -76,8 +111,11 @@ function removeCustomer(id: number): void {
<!-- Edit Customer -->
<router-link
v-if="userStore.hasAbilities(ABILITIES.EDIT_CUSTOMER) && row"
:to="`/admin/customers/${row.id}/edit`"
v-if="
userStore.hasAbilities(ABILITIES.EDIT_CUSTOMER) &&
customerId !== null
"
:to="`/admin/customers/${customerId}/edit`"
>
<BaseDropdownItem>
<BaseIcon
@@ -91,11 +129,11 @@ function removeCustomer(id: number): void {
<!-- View Customer -->
<router-link
v-if="
route.name !== 'customers.view' &&
!isDetailView &&
userStore.hasAbilities(ABILITIES.VIEW_CUSTOMER) &&
row
customerId !== null
"
:to="`customers/${row.id}/view`"
:to="`/admin/customers/${customerId}/view`"
>
<BaseDropdownItem>
<BaseIcon
@@ -108,8 +146,11 @@ function removeCustomer(id: number): void {
<!-- Delete Customer -->
<BaseDropdownItem
v-if="userStore.hasAbilities(ABILITIES.DELETE_CUSTOMER) && row"
@click="removeCustomer(row.id)"
v-if="
userStore.hasAbilities(ABILITIES.DELETE_CUSTOMER) &&
customerId !== null
"
@click="onRemoveCustomer"
>
<BaseIcon
name="TrashIcon"

View File

@@ -137,6 +137,11 @@ function copyAddress(): void {
}
async function setInitialData(): Promise<void> {
await Promise.all([
globalStore.fetchCurrencies(),
globalStore.fetchCountries(),
])
if (!customerStore.isEdit) {
customerStore.currentCustomer.currency_id =
companyStore.selectedCompanyCurrency?.id ?? null
@@ -217,9 +222,9 @@ function closeCustomerModal(): void {
</div>
</template>
<form action="" @submit.prevent="submitCustomerData">
<div class="px-6 pb-3">
<div class="px-6 pb-3 max-h-[calc(80vh-8rem)] overflow-y-auto">
<BaseTabGroup>
<BaseTab :title="$t('customers.basic_info')" class="!mt-2">
<BaseTab :title="$t('customers.basic_info')">
<BaseInputGrid layout="one-column">
<BaseInputGroup
:label="$t('customers.display_name')"
@@ -403,7 +408,7 @@ function closeCustomerModal(): void {
</BaseInputGrid>
</BaseTab>
<BaseTab :title="$t('customers.billing_address')" class="!mt-2">
<BaseTab :title="$t('customers.billing_address')">
<BaseInputGrid layout="one-column">
<BaseInputGroup :label="$t('customers.name')">
<BaseInput
@@ -505,7 +510,7 @@ function closeCustomerModal(): void {
</BaseInputGrid>
</BaseTab>
<BaseTab :title="$t('customers.shipping_address')" class="!mt-2">
<BaseTab :title="$t('customers.shipping_address')">
<div class="grid md:grid-cols-12">
<div class="flex justify-end col-span-12">
<BaseButton

View File

@@ -0,0 +1,15 @@
<template>
<BaseDatePicker v-model="date" enable-time />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | null): void }>()
const date = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseDatePicker v-model="date" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | Date | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | Date | null): void }>()
const date = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,29 @@
<template>
<BaseMultiselect
v-model="inputValue"
:options="options"
label="name"
value-prop="name"
/>
</template>
<script setup lang="ts">
import { computed } from 'vue'
interface Props {
modelValue?: string | Record<string, unknown> | number | null
options?: Array<{ name: string }> | string[]
}
const props = withDefaults(defineProps<Props>(), {
modelValue: null,
options: () => [],
})
const emit = defineEmits<{ (e: 'update:modelValue', value: unknown): void }>()
const inputValue = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseInput v-model="inputValue" type="text" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | null): void }>()
const inputValue = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseInput v-model="inputValue" type="number" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | number | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | number | null): void }>()
const inputValue = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseInput v-model="inputValue" type="tel" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | null): void }>()
const inputValue = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseSwitch v-model="inputValue" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | number | boolean | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: number): void }>()
const inputValue = computed({
get: () => props.modelValue === 1,
set: (value: boolean) => emit('update:modelValue', value ? 1 : 0),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseTextarea v-model="inputValue" rows="2" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | null): void }>()
const inputValue = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseTimePicker v-model="date" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | Date | Record<string, string> | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | Date | Record<string, string> | null): void }>()
const date = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -0,0 +1,15 @@
<template>
<BaseInput v-model="inputValue" type="url" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ modelValue?: string | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', value: string | null): void }>()
const inputValue = computed({
get: () => props.modelValue ?? null,
set: (value) => emit('update:modelValue', value),
})
</script>

View File

@@ -6,6 +6,7 @@ const customerRoutes: RouteRecordRaw[] = [
name: 'customers.index',
component: () => import('./views/CustomerIndexView.vue'),
meta: {
requiresAuth: true,
ability: 'view-customer',
},
},
@@ -14,6 +15,7 @@ const customerRoutes: RouteRecordRaw[] = [
name: 'customers.create',
component: () => import('./views/CustomerCreateView.vue'),
meta: {
requiresAuth: true,
ability: 'create-customer',
},
},
@@ -22,6 +24,7 @@ const customerRoutes: RouteRecordRaw[] = [
name: 'customers.edit',
component: () => import('./views/CustomerCreateView.vue'),
meta: {
requiresAuth: true,
ability: 'edit-customer',
},
},
@@ -30,6 +33,7 @@ const customerRoutes: RouteRecordRaw[] = [
name: 'customers.view',
component: () => import('./views/CustomerDetailView.vue'),
meta: {
requiresAuth: true,
ability: 'view-customer',
},
},

View File

@@ -5,7 +5,8 @@ import { customerService } from '../../../api/services/customer.service'
import type {
CustomerListParams,
CustomerListResponse,
CustomerStatsData,
CustomerStatsParams,
CustomerStatsResponse,
} from '../../../api/services/customer.service'
import { useNotificationStore } from '../../../stores/notification.store'
import { useGlobalStore } from '../../../stores/global.store'
@@ -47,10 +48,7 @@ export interface CustomerForm {
password_added?: boolean
}
export interface CustomerViewData {
customer?: Customer
[key: string]: unknown
}
export type CustomerViewData = Partial<Customer>
function createAddressStub(): CustomerFormAddress {
return {
@@ -153,13 +151,15 @@ export const useCustomerStore = defineStore('customer', () => {
}
}
async function fetchViewCustomer(params: { id: number }): Promise<ApiResponse<CustomerStatsData>> {
async function fetchViewCustomer(
params: { id: number } & CustomerStatsParams
): Promise<CustomerStatsResponse> {
isFetchingViewData.value = true
try {
const response = await customerService.getStats(params.id, params as Record<string, unknown>)
const { id, ...queryParams } = params
const response = await customerService.getStats(id, queryParams)
selectedViewCustomer.value = {}
Object.assign(selectedViewCustomer.value, response.data)
setAddressStub(response.data as unknown as Record<string, unknown>)
isFetchingViewData.value = false
return response
} catch (err: unknown) {

View File

@@ -19,11 +19,7 @@ import { useCompanyStore } from '../../../../stores/company.store'
import CustomerCustomFields from '@v2/features/company/customers/components/CreateCustomFields.vue'
import CopyInputField from '@v2/features/company/customers/components/CopyInputField.vue'
// Custom field store - imported from original location
import { customFieldService } from '@v2/api/services/custom-field.service'
const customerStore = useCustomerStore()
// Custom fields fetched via service
const globalStore = useGlobalStore()
const companyStore = useCompanyStore()
@@ -49,6 +45,10 @@ const pageTitle = computed<string>(() =>
isEdit.value ? t('customers.edit_customer') : t('customers.new_customer')
)
const hasCustomFields = computed<boolean>(() => {
return customerStore.currentCustomer.customFields.length > 0
})
const rules = computed(() => ({
currentCustomer: {
name: {
@@ -709,14 +709,14 @@ async function submitCustomerData(): Promise<void> {
</div>
<BaseDivider
v-if="customFieldStore.customFields.length > 0"
v-if="hasCustomFields"
class="mb-5 md:mb-8"
/>
<!-- Customer Custom Fields -->
<div class="grid grid-cols-5 gap-2 mb-8">
<h6
v-if="customFieldStore.customFields.length > 0"
v-if="hasCustomFields"
class="col-span-5 text-lg font-semibold text-left lg:col-span-1"
>
{{ $t('settings.custom_fields.title') }}

View File

@@ -1,7 +1,6 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useCustomerStore } from '../store'
import { useUserStore } from '../../../../stores/user.store'
import CustomerDropdown from '../components/CustomerDropdown.vue'
@@ -19,15 +18,12 @@ const ABILITIES = {
const customerStore = useCustomerStore()
const userStore = useUserStore()
const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const pageTitle = computed<string>(() => {
return customerStore.selectedViewCustomer.customer
? (customerStore.selectedViewCustomer.customer as { name: string }).name
: ''
return customerStore.selectedViewCustomer.name ?? ''
})
const isLoading = computed<boolean>(() => customerStore.isFetchingViewData)

View File

@@ -16,12 +16,15 @@ interface TableColumn {
const ABILITIES = {
VIEW_INVOICE: 'view-invoice',
VIEW_ESTIMATE: 'view-estimate',
DELETE_INVOICE: 'delete-invoice',
CREATE_INVOICE: 'create-invoice',
EDIT_INVOICE: 'edit-invoice',
DELETE_INVOICE: 'delete-invoice',
SEND_INVOICE: 'send-invoice',
CREATE_PAYMENT: 'create-payment',
VIEW_ESTIMATE: 'view-estimate',
CREATE_ESTIMATE: 'create-estimate',
EDIT_ESTIMATE: 'edit-estimate',
DELETE_ESTIMATE: 'delete-estimate',
SEND_ESTIMATE: 'send-estimate',
} as const
@@ -91,6 +94,22 @@ function hasAtleastOneEstimateAbility(): boolean {
ABILITIES.SEND_ESTIMATE,
])
}
// Invoice ability props
const canViewInvoice = computed(() => userStore.hasAbilities(ABILITIES.VIEW_INVOICE))
const canCreateInvoice = computed(() => userStore.hasAbilities(ABILITIES.CREATE_INVOICE))
const canEditInvoice = computed(() => userStore.hasAbilities(ABILITIES.EDIT_INVOICE))
const canDeleteInvoice = computed(() => userStore.hasAbilities(ABILITIES.DELETE_INVOICE))
const canSendInvoice = computed(() => userStore.hasAbilities(ABILITIES.SEND_INVOICE))
const canCreatePayment = computed(() => userStore.hasAbilities(ABILITIES.CREATE_PAYMENT))
// Estimate ability props
const canViewEstimate = computed(() => userStore.hasAbilities(ABILITIES.VIEW_ESTIMATE))
const canCreateEstimate = computed(() => userStore.hasAbilities(ABILITIES.CREATE_ESTIMATE))
const canEditEstimate = computed(() => userStore.hasAbilities(ABILITIES.EDIT_ESTIMATE))
const canDeleteEstimate = computed(() => userStore.hasAbilities(ABILITIES.DELETE_ESTIMATE))
const canSendEstimate = computed(() => userStore.hasAbilities(ABILITIES.SEND_ESTIMATE))
const canCreateInvoiceFromEstimate = computed(() => userStore.hasAbilities(ABILITIES.CREATE_INVOICE))
</script>
<template>
@@ -140,7 +159,16 @@ function hasAtleastOneEstimateAbility(): boolean {
v-if="hasAtleastOneInvoiceAbility()"
#cell-actions="{ row }"
>
<InvoiceDropdown :row="row.data" :table="invoiceTableComponent" />
<InvoiceDropdown
:row="row.data"
:table="invoiceTableComponent"
:can-edit="canEditInvoice"
:can-view="canViewInvoice"
:can-create="canCreateInvoice"
:can-delete="canDeleteInvoice"
:can-send="canSendInvoice"
:can-create-payment="canCreatePayment"
/>
</template>
</BaseTable>
</div>
@@ -189,7 +217,16 @@ function hasAtleastOneEstimateAbility(): boolean {
v-if="hasAtleastOneEstimateAbility()"
#cell-actions="{ row }"
>
<EstimateDropdown :row="row.data" :table="estimateTableComponent" />
<EstimateDropdown
:row="row.data"
:table="estimateTableComponent"
:can-edit="canEditEstimate"
:can-view="canViewEstimate"
:can-create="canCreateEstimate"
:can-delete="canDeleteEstimate"
:can-send="canSendEstimate"
:can-create-invoice="canCreateInvoiceFromEstimate"
/>
</template>
</BaseTable>
</div>

View File

@@ -6,6 +6,7 @@ const dashboardRoutes: RouteRecordRaw[] = [
name: 'dashboard',
component: () => import('./views/DashboardView.vue'),
meta: {
requiresAuth: true,
ability: 'dashboard',
},
},

View File

@@ -14,9 +14,9 @@ onMounted(() => {
const meta = route.meta as { ability?: string; isOwner?: boolean }
if (meta.ability && !userStore.hasAbilities(meta.ability)) {
router.push({ name: 'account.settings' })
router.push({ name: 'settings.account' })
} else if (meta.isOwner && !userStore.isOwner) {
router.push({ name: 'account.settings' })
router.push({ name: 'settings.account' })
}
})
</script>

View File

@@ -1,15 +1,14 @@
<template>
<div class="md:grid-cols-12 grid-cols-1 md:gap-x-6 mt-6 mb-8 grid gap-y-5">
<BaseCustomerSelectPopup
v-model="estimateStore.newEstimate.customer"
:valid="v.customer_id"
:content-loading="isLoading"
type="estimate"
class="col-span-5 pr-0"
class="col-span-6 pr-0"
/>
<BaseInputGrid
class="col-span-7 rounded-xl shadow border border-line-light bg-surface p-5"
class="col-span-6 rounded-xl shadow border border-line-light bg-surface p-5"
>
<BaseInputGroup
:label="$t('reports.estimates.estimate_date')"

View File

@@ -135,6 +135,8 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { useEstimateStore } from '../store'
import { useDialogStore } from '../../../../stores/dialog.store'
import { useModalStore } from '../../../../stores/modal.store'
import type { Estimate } from '../../../../types/domain/estimate'
interface TableRef {
@@ -163,6 +165,8 @@ const props = withDefaults(defineProps<Props>(), {
})
const estimateStore = useEstimateStore()
const dialogStore = useDialogStore()
const modalStore = useModalStore()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
@@ -177,46 +181,70 @@ const canResendEstimate = computed<boolean>(() => {
)
})
async function removeEstimate(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_delete'))
if (!confirmed) return
const res = await estimateStore.deleteEstimate({ ids: [props.row.id] })
if (res.data) {
props.table?.refresh()
if (res.data.success) {
router.push('/admin/estimates')
function removeEstimate(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await estimateStore.deleteEstimate({ ids: [props.row.id] })
if (response.data) {
props.table?.refresh()
if (response.data.success) {
router.push('/admin/estimates')
}
estimateStore.$patch((state) => {
state.selectedEstimates = []
state.selectAllField = false
})
}
}
estimateStore.$patch((state) => {
state.selectedEstimates = []
state.selectAllField = false
})
}
})
}
async function convertToInvoice(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_conversion'))
if (!confirmed) return
const res = await estimateStore.convertToInvoice(props.row.id)
if (res.data) {
router.push(`/admin/invoices/${res.data.data.id}/edit`)
}
function convertToInvoice(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_conversion'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await estimateStore.convertToInvoice(props.row.id)
if (response.data) {
router.push(`/admin/invoices/${response.data.data.id}/edit`)
}
}
})
}
async function onMarkAsSent(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_mark_as_sent'))
if (!confirmed) return
await estimateStore.markAsSent({ id: props.row.id, status: 'SENT' })
props.table?.refresh()
function onMarkAsSent(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_mark_as_sent'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
await estimateStore.markAsSent({ id: props.row.id, status: 'SENT' })
props.table?.refresh()
}
})
}
function sendEstimate(): void {
const modalStore = (window as Record<string, unknown>).__modalStore as
| { openModal: (opts: Record<string, unknown>) => void }
| undefined
modalStore?.openModal({
modalStore.openModal({
title: t('estimates.send_estimate'),
componentName: 'SendEstimateModal',
id: props.row.id,
@@ -225,20 +253,38 @@ function sendEstimate(): void {
})
}
async function onMarkAsAccepted(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_mark_as_accepted'))
if (!confirmed) return
await estimateStore.markAsAccepted({ id: props.row.id, status: 'ACCEPTED' })
props.table?.refresh()
function onMarkAsAccepted(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_mark_as_accepted'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
await estimateStore.markAsAccepted({ id: props.row.id, status: 'ACCEPTED' })
props.table?.refresh()
}
})
}
async function onMarkAsRejected(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_mark_as_rejected'))
if (!confirmed) return
await estimateStore.markAsRejected({ id: props.row.id, status: 'REJECTED' })
props.table?.refresh()
function onMarkAsRejected(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_mark_as_rejected'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
await estimateStore.markAsRejected({ id: props.row.id, status: 'REJECTED' })
props.table?.refresh()
}
})
}
function copyPdfUrl(): void {
@@ -253,11 +299,20 @@ function copyPdfUrl(): void {
})
}
async function cloneEstimateData(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_clone'))
if (!confirmed) return
const res = await estimateStore.cloneEstimate({ id: props.row.id })
router.push(`/admin/estimates/${res.data.data.id}/edit`)
function cloneEstimateData(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_clone'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await estimateStore.cloneEstimate({ id: props.row.id })
router.push(`/admin/estimates/${response.data.data.id}/edit`)
}
})
}
</script>

View File

@@ -0,0 +1,321 @@
<template>
<BaseModal
:show="modalActive"
@close="closeSendEstimateModal"
@open="setInitialData"
>
<template #header>
<div class="flex justify-between w-full">
{{ modalStore.title }}
<BaseIcon
name="XMarkIcon"
class="h-6 w-6 text-muted cursor-pointer"
@click="closeSendEstimateModal"
/>
</div>
</template>
<form v-if="!isPreview" action="">
<div class="px-8 py-8 sm:p-6">
<BaseInputGrid layout="one-column">
<BaseInputGroup
:label="$t('general.from')"
required
:error="v$.from.$error && v$.from.$errors[0].$message"
>
<BaseInput
v-model="estimateMailForm.from"
type="text"
:invalid="v$.from.$error"
@input="v$.from.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.to')"
required
:error="v$.to.$error && v$.to.$errors[0].$message"
>
<BaseInput
v-model="estimateMailForm.to"
type="text"
:invalid="v$.to.$error"
@input="v$.to.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.cc')"
:error="v$.cc && v$.cc.$error && v$.cc.$errors[0].$message"
>
<BaseInput
v-model="estimateMailForm.cc"
type="email"
:invalid="v$.cc && v$.cc.$error"
@input="v$.cc && v$.cc.$touch()"
placeholder="Optional: CC recipient"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.bcc')"
:error="v$.bcc && v$.bcc.$error && v$.bcc.$errors[0].$message"
>
<BaseInput
v-model="estimateMailForm.bcc"
type="email"
:invalid="v$.bcc && v$.bcc.$error"
@input="v$.bcc && v$.bcc.$touch()"
placeholder="Optional: BCC recipient"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.subject')"
required
:error="v$.subject.$error && v$.subject.$errors[0].$message"
>
<BaseInput
v-model="estimateMailForm.subject"
type="text"
:invalid="v$.subject.$error"
@input="v$.subject.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.body')"
:error="v$.body.$error && v$.body.$errors[0].$message"
required
>
<BaseCustomInput
v-model="estimateMailForm.body"
:fields="['customer', 'company', 'estimate']"
/>
</BaseInputGroup>
</BaseInputGrid>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
class="mr-3"
variant="primary-outline"
type="button"
@click="closeSendEstimateModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isLoading"
:disabled="isLoading"
variant="primary"
type="button"
class="mr-3"
@click="submitForm"
>
<BaseIcon v-if="!isLoading" name="PhotoIcon" class="h-5 mr-2" />
{{ $t('general.preview') }}
</BaseButton>
</div>
</form>
<div v-else>
<div class="my-6 mx-4 border border-line-default relative">
<BaseButton
class="absolute top-4 right-4"
:disabled="isLoading"
variant="primary-outline"
@click="cancelPreview"
>
<BaseIcon name="PencilIcon" class="h-5 mr-2" />
{{ $t('general.edit') }}
</BaseButton>
<iframe
:src="templateUrl"
frameborder="0"
class="w-full"
style="min-height: 500px"
></iframe>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
class="mr-3"
variant="primary-outline"
type="button"
@click="closeSendEstimateModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isLoading"
:disabled="isLoading"
variant="primary"
type="button"
@click="submitForm"
>
<BaseIcon
v-if="!isLoading"
name="PaperAirplaneIcon"
class="h-5 mr-2"
/>
{{ $t('general.send') }}
</BaseButton>
</div>
</div>
</BaseModal>
</template>
<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { required, email, helpers } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { useModalStore } from '../../../../stores/modal.store'
import { useCompanyStore } from '../../../../stores/company.store'
import { useNotificationStore } from '../../../../stores/notification.store'
import { useEstimateStore } from '../store'
const modalStore = useModalStore()
const companyStore = useCompanyStore()
const notificationStore = useNotificationStore()
const estimateStore = useEstimateStore()
const { t } = useI18n()
const isLoading = ref(false)
const templateUrl = ref<string>('')
const isPreview = ref(false)
const emit = defineEmits(['update'])
const estimateMailForm = reactive({
id: null as number | null,
from: null as string | null,
to: null as string | null,
cc: null as string | null,
bcc: null as string | null,
subject: t('estimates.new_estimate'),
body: null as string | null,
})
const modalActive = computed(() => {
return modalStore.active && modalStore.componentName === 'SendEstimateModal'
})
const modalData = computed(() => {
return modalStore.data as Record<string, unknown> | null
})
const rules = {
from: {
required: helpers.withMessage(t('validation.required'), required),
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
to: {
required: helpers.withMessage(t('validation.required'), required),
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
cc: {
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
bcc: {
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
subject: {
required: helpers.withMessage(t('validation.required'), required),
},
body: {
required: helpers.withMessage(t('validation.required'), required),
},
}
const v$ = useVuelidate(
rules,
computed(() => estimateMailForm),
)
function cancelPreview() {
isPreview.value = false
}
async function setInitialData() {
const admin = await companyStore.fetchBasicMailConfig()
estimateMailForm.id = modalStore.id as number
if (admin.data) {
estimateMailForm.from = (admin.data as Record<string, string>).from_mail
}
if (modalData.value) {
const customer = modalData.value.customer as Record<string, string> | undefined
if (customer) {
estimateMailForm.to = customer.email
}
}
estimateMailForm.body =
companyStore.selectedCompanySettings.estimate_mail_body
estimateMailForm.subject = t('estimates.new_estimate')
}
async function submitForm() {
v$.value.$touch()
if (v$.value.$invalid) {
return true
}
try {
isLoading.value = true
if (!isPreview.value) {
const previewResponse = await estimateStore.previewEstimate(
estimateMailForm as unknown as { id: number },
)
isLoading.value = false
isPreview.value = true
const blob = new Blob([(previewResponse as { data: string }).data], {
type: 'text/html',
})
templateUrl.value = URL.createObjectURL(blob)
return
}
await estimateStore.sendEstimate(
estimateMailForm as unknown as Parameters<typeof estimateStore.sendEstimate>[0],
)
isLoading.value = false
notificationStore.showNotification({
type: 'success',
message: 'estimates.estimate_sent_successfully',
})
if (modalStore.refreshData) {
modalStore.refreshData()
}
emit('update')
closeSendEstimateModal()
} catch (error) {
console.error(error)
isLoading.value = false
notificationStore.showNotification({
type: 'error',
message: 'estimates.something_went_wrong',
})
}
}
function closeSendEstimateModal() {
modalStore.closeModal()
setTimeout(() => {
v$.value.$reset()
isPreview.value = false
templateUrl.value = ''
}, 300)
}
</script>

View File

@@ -10,6 +10,7 @@ export const estimateRoutes: RouteRecordRaw[] = [
name: 'estimates.index',
component: EstimateIndexView,
meta: {
requiresAuth: true,
ability: 'view-estimate',
title: 'estimates.title',
},
@@ -19,6 +20,7 @@ export const estimateRoutes: RouteRecordRaw[] = [
name: 'estimates.create',
component: EstimateCreateView,
meta: {
requiresAuth: true,
ability: 'create-estimate',
title: 'estimates.new_estimate',
},
@@ -28,6 +30,7 @@ export const estimateRoutes: RouteRecordRaw[] = [
name: 'estimates.edit',
component: EstimateCreateView,
meta: {
requiresAuth: true,
ability: 'edit-estimate',
title: 'estimates.edit_estimate',
},
@@ -37,6 +40,7 @@ export const estimateRoutes: RouteRecordRaw[] = [
name: 'estimates.view',
component: EstimateDetailView,
meta: {
requiresAuth: true,
ability: 'view-estimate',
title: 'estimates.title',
},

View File

@@ -1,4 +1,6 @@
import { defineStore } from 'pinia'
import { useNotificationStore } from '../../../stores/notification.store'
import { useCompanyStore } from '../../../stores/company.store'
import { estimateService } from '../../../api/services/estimate.service'
import type {
EstimateListParams,
@@ -15,6 +17,7 @@ import type { Customer } from '../../../types/domain/customer'
import type { Note } from '../../../types/domain/note'
import type { CustomFieldValue } from '../../../types/domain/custom-field'
import type { DocumentTax, DocumentItem } from '../../shared/document-form/use-document-calculations'
import { generateClientId } from '../../../utils'
// ----------------------------------------------------------------
// Stub factories
@@ -22,11 +25,11 @@ import type { DocumentTax, DocumentItem } from '../../shared/document-form/use-d
function createTaxStub(): DocumentTax {
return {
id: crypto.randomUUID(),
id: generateClientId(),
name: '',
tax_type_id: 0,
type: 'GENERAL',
amount: 0,
amount: null,
percent: null,
compound_tax: false,
calculation_type: null,
@@ -36,7 +39,7 @@ function createTaxStub(): DocumentTax {
function createEstimateItemStub(): DocumentItem {
return {
id: crypto.randomUUID(),
id: generateClientId(),
estimate_id: null,
item_id: null,
name: '',
@@ -309,6 +312,13 @@ export const useEstimateStore = defineStore('estimate', {
async addEstimate(data: Record<string, unknown>): Promise<{ data: { data: Estimate } }> {
const response = await estimateService.create(data as never)
this.estimates = [...this.estimates, response.data]
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'estimates.created_message',
})
return { data: response }
},
@@ -342,6 +352,13 @@ export const useEstimateStore = defineStore('estimate', {
if (pos !== -1) {
this.estimates[pos] = response.data
}
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'estimates.updated_message',
})
return { data: response }
},
@@ -461,14 +478,17 @@ export const useEstimateStore = defineStore('estimate', {
async fetchEstimateInitialSettings(
isEdit: boolean,
routeParams?: { id?: string; query?: Record<string, string> },
companySettings?: Record<string, string>,
companySettingsParam?: Record<string, string>,
companyCurrency?: Currency,
userSettings?: Record<string, string>,
): Promise<void> {
this.isFetchingInitialSettings = true
if (companyCurrency) {
this.newEstimate.selectedCurrency = companyCurrency
const companyStore = useCompanyStore()
const companySettings = companySettingsParam ?? companyStore.selectedCompanySettings
if (companyCurrency || companyStore.selectedCompanyCurrency) {
this.newEstimate.selectedCurrency = companyCurrency ?? companyStore.selectedCompanyCurrency!
}
// If customer is specified in route query

View File

@@ -85,6 +85,7 @@
store-prop="newEstimate"
:is-mark-as-default="isMarkAsDefault"
/>
<SelectTemplateModal />
</div>
<DocumentTotals
@@ -104,6 +105,7 @@
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import cloneDeep from 'lodash/cloneDeep'
import {
required,
maxLength,
@@ -119,6 +121,7 @@ import {
DocumentTotals,
DocumentNotes,
TemplateSelectButton,
SelectTemplateModal,
} from '../../../shared/document-form'
const estimateStore = useEstimateStore()
@@ -130,7 +133,7 @@ const estimateValidationScope = 'newEstimate'
const isSaving = ref<boolean>(false)
const isMarkAsDefault = ref<boolean>(false)
const estimateNoteFieldList = ref<Record<string, unknown> | null>(null)
const estimateNoteFieldList = ref<string[]>(['customer', 'company', 'estimate'])
const isLoadingContent = computed<boolean>(
() => estimateStore.isFetchingInitialSettings,
@@ -156,11 +159,7 @@ const rules = {
required: helpers.withMessage(t('validation.required'), required),
},
exchange_rate: {
required: requiredIf(() => {
helpers.withMessage(t('validation.required'), required)
return estimateStore.showExchangeRate
}),
decimal: helpers.withMessage(t('validation.valid_exchange_rate'), decimal),
required: requiredIf(() => estimateStore.showExchangeRate),
},
}
@@ -193,13 +192,16 @@ async function submitForm(): Promise<void> {
v$.value.$touch()
if (v$.value.$invalid) {
console.log('Estimate form invalid. Errors:', JSON.stringify(
v$.value.$errors.map((e: { $property: string; $message: string }) => `${e.$property}: ${e.$message}`)
))
return
}
isSaving.value = true
const data: Record<string, unknown> = {
...structuredClone(estimateStore.newEstimate),
...cloneDeep(estimateStore.newEstimate),
sub_total: estimateStore.getSubTotal,
total: estimateStore.getTotal,
tax: estimateStore.getTotalTax,

View File

@@ -191,12 +191,9 @@
</div>
<!-- PDF Preview -->
<div class="flex flex-col min-h-0 mt-8 overflow-hidden" style="height: 75vh">
<iframe
:src="shareableLink"
class="flex-1 border border-gray-400 border-solid rounded-xl bg-surface frame-style"
/>
</div>
<BasePdfPreview :src="shareableLink" />
<SendEstimateModal @update="updateSentEstimate" />
</BasePage>
</template>
@@ -206,7 +203,11 @@ import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useEstimateStore } from '../store'
import EstimateDropdown from '../components/EstimateDropdown.vue'
import SendEstimateModal from '../components/SendEstimateModal.vue'
import LoadingIcon from '@v2/components/icons/LoadingIcon.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useDialogStore } from '../../../../stores/dialog.store'
import { useModalStore } from '../../../../stores/modal.store'
import type { Estimate } from '../../../../types/domain/estimate'
interface Props {
@@ -227,10 +228,48 @@ const props = withDefaults(defineProps<Props>(), {
canCreateInvoice: false,
})
const ABILITIES = {
EDIT: 'edit-estimate',
VIEW: 'view-estimate',
CREATE: 'create-estimate',
DELETE: 'delete-estimate',
SEND: 'send-estimate',
CREATE_INVOICE: 'create-invoice',
} as const
const estimateStore = useEstimateStore()
const userStore = useUserStore()
const dialogStore = useDialogStore()
const modalStore = useModalStore()
const { t } = useI18n()
const route = useRoute()
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canCreate = computed<boolean>(() => {
return props.canCreate || userStore.hasAbilities(ABILITIES.CREATE)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const canSend = computed<boolean>(() => {
return props.canSend || userStore.hasAbilities(ABILITIES.SEND)
})
const canCreateInvoice = computed<boolean>(() => {
return (
props.canCreateInvoice || userStore.hasAbilities(ABILITIES.CREATE_INVOICE)
)
})
const estimateData = ref<Estimate | null>(null)
const isMarkAsSent = ref<boolean>(false)
const isLoading = ref<boolean>(false)
@@ -373,29 +412,36 @@ function sortData(): void {
onSearched()
}
async function onMarkAsSent(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_mark_as_sent'))
if (!confirmed) return
isMarkAsSent.value = false
await estimateStore.markAsSent({
id: estimateData.value!.id,
status: 'SENT',
function onMarkAsSent(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_mark_as_sent'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
isMarkAsSent.value = false
await estimateStore.markAsSent({
id: estimateData.value!.id,
status: 'SENT',
})
estimateData.value!.status = 'SENT' as Estimate['status']
isMarkAsSent.value = true
isMarkAsSent.value = false
}
})
estimateData.value!.status = 'SENT' as Estimate['status']
isMarkAsSent.value = true
isMarkAsSent.value = false
}
function onSendEstimate(): void {
const modalStore = (window as Record<string, unknown>).__modalStore as
| { openModal: (opts: Record<string, unknown>) => void }
| undefined
modalStore?.openModal({
modalStore.openModal({
title: t('estimates.send_estimate'),
componentName: 'SendEstimateModal',
id: estimateData.value!.id,
data: estimateData.value,
refreshData: () => loadEstimate(),
})
}

View File

@@ -113,9 +113,9 @@
<!-- Table -->
<div v-show="!showEmptyScreen" class="relative table-container">
<div
class="relative flex items-center justify-between h-10 mt-5 list-none border-b-2 border-line-default border-solid"
class="relative flex items-center justify-between mt-5 list-none"
>
<BaseTabGroup class="-mb-5" @change="setStatusFilter">
<BaseTabGroup @change="setStatusFilter">
<BaseTab :title="$t('general.all')" filter="" />
<BaseTab :title="$t('general.draft')" filter="DRAFT" />
<BaseTab :title="$t('general.sent')" filter="SENT" />
@@ -147,7 +147,7 @@
:columns="estimateColumns"
:placeholder-count="estimateStore.totalEstimateCount >= 20 ? 10 : 5"
:key="tableKey"
class="mt-10"
class="mt-4"
>
<template #header>
<div class="absolute items-center left-6 top-2.5 select-none">
@@ -183,7 +183,14 @@
</template>
<template #cell-name="{ row }">
<BaseText :text="row.data.customer.name" />
<router-link
v-if="row.data.customer?.id"
:to="`/admin/customers/${row.data.customer.id}/view`"
class="font-medium text-primary-500 hover:text-primary-600"
>
{{ row.data.customer.name }}
</router-link>
<span v-else>{{ row.data.customer?.name ?? '-' }}</span>
</template>
<template #cell-status="{ row }">
@@ -221,6 +228,8 @@ import { useI18n } from 'vue-i18n'
import { debouncedWatch } from '@vueuse/core'
import { useEstimateStore } from '../store'
import EstimateDropdown from '../components/EstimateDropdown.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { Estimate } from '../../../../types/domain/estimate'
interface Props {
@@ -239,7 +248,17 @@ const props = withDefaults(defineProps<Props>(), {
canSend: false,
})
const ABILITIES = {
CREATE: 'create-estimate',
EDIT: 'edit-estimate',
VIEW: 'view-estimate',
DELETE: 'delete-estimate',
SEND: 'send-estimate',
} as const
const estimateStore = useEstimateStore()
const userStore = useUserStore()
const dialogStore = useDialogStore()
const { t } = useI18n()
const tableRef = ref<{ refresh: () => void } | null>(null)
@@ -289,8 +308,28 @@ const selectField = computed<number[]>({
},
})
const canCreate = computed<boolean>(() => {
return props.canCreate || userStore.hasAbilities(ABILITIES.CREATE)
})
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const canSend = computed<boolean>(() => {
return props.canSend || userStore.hasAbilities(ABILITIES.SEND)
})
const hasAtLeastOneAbility = computed<boolean>(() => {
return props.canCreate || props.canEdit || props.canView || props.canSend
return canCreate.value || canEdit.value || canView.value || canSend.value
})
interface TableColumn {
@@ -432,18 +471,27 @@ function toggleFilter(): void {
showFilters.value = !showFilters.value
}
async function removeMultipleEstimates(): Promise<void> {
const confirmed = window.confirm(t('estimates.confirm_delete'))
if (!confirmed) return
const res = await estimateStore.deleteMultipleEstimates()
if (res.data) {
refreshTable()
estimateStore.$patch((state) => {
state.selectedEstimates = []
state.selectAllField = false
})
}
function removeMultipleEstimates(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('estimates.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await estimateStore.deleteMultipleEstimates()
if (response.data) {
refreshTable()
estimateStore.$patch((state) => {
state.selectedEstimates = []
state.selectAllField = false
})
}
}
})
}
function setActiveTab(val: string): void {

View File

@@ -26,6 +26,8 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { useDialogStore } from '../../../../stores/dialog.store'
import { useModalStore } from '../../../../stores/modal.store'
import type { ExpenseCategory } from '../../../../types/domain/expense'
interface TableRef {
@@ -48,12 +50,11 @@ const props = withDefaults(defineProps<Props>(), {
})
const { t } = useI18n()
const dialogStore = useDialogStore()
const modalStore = useModalStore()
function editExpenseCategory(): void {
const modalStore = (window as Record<string, unknown>).__modalStore as
| { openModal: (opts: Record<string, unknown>) => void }
| undefined
modalStore?.openModal({
modalStore.openModal({
title: t('settings.expense_category.edit_category'),
componentName: 'CategoryModal',
refreshData: props.loadData,
@@ -61,22 +62,31 @@ function editExpenseCategory(): void {
})
}
async function removeExpenseCategory(): Promise<void> {
const confirmed = window.confirm(
t('settings.expense_category.confirm_delete'),
)
if (!confirmed) return
try {
const { expenseService } = await import(
'../../../../api/services/expense.service'
)
const response = await expenseService.deleteCategory(props.row.id)
if (response.success) {
props.loadData?.()
}
} catch {
props.loadData?.()
}
function removeExpenseCategory(): void {
dialogStore
.openDialog({
title: t('general.are_you_sure'),
message: t('settings.expense_category.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
.then(async (res: boolean) => {
if (res) {
try {
const { expenseService } = await import(
'../../../../api/services/expense.service'
)
const response = await expenseService.deleteCategory(props.row.id)
if (response.success) {
props.loadData?.()
}
} catch {
props.loadData?.()
}
}
})
}
</script>

View File

@@ -29,6 +29,7 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { useExpenseStore } from '../store'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { Expense } from '../../../../types/domain/expense'
interface TableRef {
@@ -51,15 +52,27 @@ const props = withDefaults(defineProps<Props>(), {
})
const expenseStore = useExpenseStore()
const dialogStore = useDialogStore()
const { t } = useI18n()
async function removeExpense(): Promise<void> {
const confirmed = window.confirm(t('expenses.confirm_delete'))
if (!confirmed) return
const res = await expenseStore.deleteExpense({ ids: [props.row.id] })
if (res) {
props.loadData?.()
}
function removeExpense(): void {
dialogStore
.openDialog({
title: t('general.are_you_sure'),
message: t('expenses.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
.then(async (res: boolean) => {
if (res) {
const response = await expenseStore.deleteExpense({ ids: [props.row.id] })
if (response) {
props.loadData?.()
}
}
})
}
</script>

View File

@@ -9,6 +9,7 @@ export const expenseRoutes: RouteRecordRaw[] = [
name: 'expenses.index',
component: ExpenseIndexView,
meta: {
requiresAuth: true,
ability: 'view-expense',
title: 'expenses.title',
},
@@ -18,6 +19,7 @@ export const expenseRoutes: RouteRecordRaw[] = [
name: 'expenses.create',
component: ExpenseCreateView,
meta: {
requiresAuth: true,
ability: 'create-expense',
title: 'expenses.new_expense',
},
@@ -27,6 +29,7 @@ export const expenseRoutes: RouteRecordRaw[] = [
name: 'expenses.edit',
component: ExpenseCreateView,
meta: {
requiresAuth: true,
ability: 'edit-expense',
title: 'expenses.edit_expense',
},

View File

@@ -182,9 +182,14 @@
</template>
<template #cell-user_name="{ row }">
<BaseText
:text="row.data.customer ? row.data.customer.name : '-'"
/>
<router-link
v-if="row.data.customer?.id"
:to="`/admin/customers/${row.data.customer.id}/view`"
class="font-medium text-primary-500 hover:text-primary-600"
>
{{ row.data.customer.name }}
</router-link>
<span v-else>-</span>
</template>
<template #cell-notes="{ row }">
@@ -215,6 +220,8 @@ import { useI18n } from 'vue-i18n'
import { debouncedWatch } from '@vueuse/core'
import { useExpenseStore } from '../store'
import ExpenseDropdown from '../components/ExpenseDropdown.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { Expense, ExpenseCategory } from '../../../../types/domain/expense'
interface Props {
@@ -229,15 +236,35 @@ const props = withDefaults(defineProps<Props>(), {
canDelete: false,
})
const ABILITIES = {
CREATE: 'create-expense',
EDIT: 'edit-expense',
DELETE: 'delete-expense',
} as const
const expenseStore = useExpenseStore()
const userStore = useUserStore()
const dialogStore = useDialogStore()
const { t } = useI18n()
const tableRef = ref<{ refresh: () => void } | null>(null)
const showFilters = ref<boolean>(false)
const isFetchingInitialData = ref<boolean>(true)
const canCreate = computed<boolean>(() => {
return props.canCreate || userStore.hasAbilities(ABILITIES.CREATE)
})
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const hasAtLeastOneAbility = computed<boolean>(() => {
return props.canDelete || props.canEdit
return canDelete.value || canEdit.value
})
interface ExpenseFilters {
@@ -402,13 +429,24 @@ function toggleFilter(): void {
showFilters.value = !showFilters.value
}
async function removeMultipleExpenses(): Promise<void> {
const confirmed = window.confirm(t('expenses.confirm_delete'))
if (!confirmed) return
const res = await expenseStore.deleteMultipleExpenses()
if (res.data) {
refreshTable()
}
function removeMultipleExpenses(): void {
dialogStore
.openDialog({
title: t('general.are_you_sure'),
message: t('expenses.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
.then(async (res: boolean) => {
if (res) {
const response = await expenseStore.deleteMultipleExpenses()
if (response.data) {
refreshTable()
}
}
})
}
</script>

View File

@@ -1,15 +1,21 @@
<template>
<div class="grid grid-cols-12 gap-8 mt-6 mb-8">
<BaseCustomerSelectPopup
v-model="invoiceStore.newInvoice.customer"
:valid="v.customer_id"
:content-loading="isLoading"
type="invoice"
class="col-span-12 lg:col-span-5 pr-0"
class="col-span-12 lg:col-span-6 pr-0"
/>
<RecurringFields
v-if="isRecurring"
:is-loading="isLoading"
:is-edit="isEdit"
/>
<BaseInputGrid
class="col-span-12 lg:col-span-7 rounded-xl shadow border border-line-light bg-surface p-5"
v-else
class="col-span-12 lg:col-span-6 rounded-xl shadow border border-line-light bg-surface p-5"
>
<BaseInputGroup
:label="$t('invoices.invoice_date')"
@@ -68,6 +74,7 @@
import { computed } from 'vue'
import { ExchangeRateConverter } from '../../../shared/document-form'
import { useInvoiceStore } from '../store'
import RecurringFields from './RecurringFields.vue'
interface ValidationField {
$error: boolean
@@ -79,12 +86,14 @@ interface Props {
v: Record<string, ValidationField>
isLoading?: boolean
isEdit?: boolean
isRecurring?: boolean
companySettings?: Record<string, string>
}
const props = withDefaults(defineProps<Props>(), {
isLoading: false,
isEdit: false,
isRecurring: false,
companySettings: () => ({}),
})

View File

@@ -65,7 +65,7 @@
<!-- Record Payment -->
<router-link :to="`/admin/payments/${row.id}/create`">
<BaseDropdownItem
v-if="row.status === 'SENT' && !isDetailView"
v-if="row.status === 'SENT' && !isDetailView && canCreatePayment"
>
<BaseIcon
name="CreditCardIcon"
@@ -109,6 +109,8 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { useInvoiceStore } from '../store'
import { useDialogStore } from '../../../../stores/dialog.store'
import { useModalStore } from '../../../../stores/modal.store'
import type { Invoice } from '../../../../types/domain/invoice'
interface TableRef {
@@ -124,6 +126,7 @@ interface Props {
canCreate?: boolean
canDelete?: boolean
canSend?: boolean
canCreatePayment?: boolean
}
const props = withDefaults(defineProps<Props>(), {
@@ -134,9 +137,12 @@ const props = withDefaults(defineProps<Props>(), {
canCreate: false,
canDelete: false,
canSend: false,
canCreatePayment: false,
})
const invoiceStore = useInvoiceStore()
const dialogStore = useDialogStore()
const modalStore = useModalStore()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
@@ -158,43 +164,66 @@ const canSendInvoice = computed<boolean>(() => {
)
})
async function removeInvoice(): Promise<void> {
// In v2, use a dialog composable or store
const confirmed = window.confirm(t('invoices.confirm_delete'))
if (!confirmed) return
const res = await invoiceStore.deleteInvoice({ ids: [props.row.id] })
if (res.data.success) {
router.push('/admin/invoices')
props.table?.refresh()
invoiceStore.$patch((state) => {
state.selectedInvoices = []
state.selectAllField = false
})
}
function removeInvoice(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await invoiceStore.deleteInvoice({ ids: [props.row.id] })
if (response.data.success) {
router.push('/admin/invoices')
props.table?.refresh()
invoiceStore.$patch((state) => {
state.selectedInvoices = []
state.selectAllField = false
})
}
}
})
}
async function cloneInvoiceData(): Promise<void> {
const confirmed = window.confirm(t('invoices.confirm_clone'))
if (!confirmed) return
const res = await invoiceStore.cloneInvoice({ id: props.row.id })
router.push(`/admin/invoices/${res.data.data.id}/edit`)
function cloneInvoiceData(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.confirm_clone'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await invoiceStore.cloneInvoice({ id: props.row.id })
router.push(`/admin/invoices/${response.data.data.id}/edit`)
}
})
}
async function onMarkAsSent(): Promise<void> {
const confirmed = window.confirm(t('invoices.invoice_mark_as_sent'))
if (!confirmed) return
await invoiceStore.markAsSent({ id: props.row.id, status: 'SENT' })
props.table?.refresh()
function onMarkAsSent(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.invoice_mark_as_sent'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
await invoiceStore.markAsSent({ id: props.row.id, status: 'SENT' })
props.table?.refresh()
}
})
}
function sendInvoice(): void {
const modalStore = (window as Record<string, unknown>).__modalStore as
| { openModal: (opts: Record<string, unknown>) => void }
| undefined
modalStore?.openModal({
modalStore.openModal({
title: t('invoices.send_invoice'),
componentName: 'SendInvoiceModal',
id: props.row.id,

View File

@@ -0,0 +1,234 @@
<template>
<div
class="col-span-12 lg:col-span-6 rounded-xl shadow border border-line-light bg-surface p-5"
>
<!-- Send Automatically -->
<BaseSwitchSection
v-model="recurringInvoiceStore.newRecurringInvoice.send_automatically"
:title="$t('recurring_invoices.send_automatically')"
:description="$t('recurring_invoices.send_automatically_desc')"
/>
<BaseDivider class="my-4" />
<!-- Schedule -->
<BaseInputGrid>
<BaseInputGroup
:label="$t('recurring_invoices.starts_at')"
:content-loading="isLoading"
required
>
<BaseDatePicker
v-model="recurringInvoiceStore.newRecurringInvoice.starts_at"
:content-loading="isLoading"
:calendar-button="true"
calendar-button-icon="calendar"
@change="getNextInvoiceDate()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('recurring_invoices.next_invoice_date')"
:content-loading="isLoading"
>
<BaseDatePicker
v-model="recurringInvoiceStore.newRecurringInvoice.next_invoice_at"
:content-loading="isLoading"
:calendar-button="true"
:disabled="true"
:loading="isLoadingNextDate"
calendar-button-icon="calendar"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('recurring_invoices.frequency.select_frequency')"
required
:content-loading="isLoading"
>
<BaseMultiselect
v-model="recurringInvoiceStore.newRecurringInvoice.selectedFrequency"
:content-loading="isLoading"
:options="recurringInvoiceStore.frequencies"
label="label"
object
@change="getNextInvoiceDate"
/>
</BaseInputGroup>
<BaseInputGroup
v-if="isCustomFrequency"
:label="$t('recurring_invoices.frequency.title')"
:content-loading="isLoading"
required
>
<BaseInput
v-model="recurringInvoiceStore.newRecurringInvoice.frequency"
:content-loading="isLoading"
:disabled="!isCustomFrequency"
:loading="isLoadingNextDate"
@update:model-value="debounceNextDate"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('recurring_invoices.limit_by')"
:content-loading="isLoading"
required
>
<BaseMultiselect
v-model="recurringInvoiceStore.newRecurringInvoice.limit_by"
:content-loading="isLoading"
:options="limits"
label="label"
value-prop="value"
/>
</BaseInputGroup>
<BaseInputGroup
v-if="hasLimitBy('DATE')"
:label="$t('recurring_invoices.limit_date')"
:content-loading="isLoading"
:required="hasLimitBy('DATE')"
>
<BaseDatePicker
v-model="recurringInvoiceStore.newRecurringInvoice.limit_date"
:content-loading="isLoading"
calendar-button-icon="calendar"
/>
</BaseInputGroup>
<BaseInputGroup
v-if="hasLimitBy('COUNT')"
:label="$t('recurring_invoices.count')"
:content-loading="isLoading"
:required="hasLimitBy('COUNT')"
>
<BaseInput
v-model="recurringInvoiceStore.newRecurringInvoice.limit_count"
:content-loading="isLoading"
type="number"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('recurring_invoices.status')"
required
:content-loading="isLoading"
>
<BaseMultiselect
v-model="recurringInvoiceStore.newRecurringInvoice.status"
:options="statusOptions"
:content-loading="isLoading"
:placeholder="$t('recurring_invoices.select_a_status')"
value-prop="value"
label="key"
/>
</BaseInputGroup>
</BaseInputGrid>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDebounceFn } from '@vueuse/core'
import { useRecurringInvoiceStore } from '@v2/features/company/recurring-invoices/store'
import type { FrequencyOption } from '@v2/features/company/recurring-invoices/store'
interface Props {
isLoading?: boolean
isEdit?: boolean
}
const props = withDefaults(defineProps<Props>(), {
isLoading: false,
isEdit: false,
})
const recurringInvoiceStore = useRecurringInvoiceStore()
const { t } = useI18n()
const isLoadingNextDate = ref<boolean>(false)
interface LimitOption {
label: string
value: string
}
const limits = reactive<LimitOption[]>([
{ label: t('recurring_invoices.limit.none'), value: 'NONE' },
{ label: t('recurring_invoices.limit.date'), value: 'DATE' },
{ label: t('recurring_invoices.limit.count'), value: 'COUNT' },
])
interface StatusOption {
key: string
value: string
}
const statusOptions = computed<StatusOption[]>(() => {
if (props.isEdit) {
return [
{ key: t('recurring_invoices.active'), value: 'ACTIVE' },
{ key: t('recurring_invoices.on_hold'), value: 'ON_HOLD' },
{ key: t('recurring_invoices.completed'), value: 'COMPLETED' },
]
}
return [
{ key: t('recurring_invoices.active'), value: 'ACTIVE' },
{ key: t('recurring_invoices.on_hold'), value: 'ON_HOLD' },
]
})
const isCustomFrequency = computed<boolean>(() => {
return (
recurringInvoiceStore.newRecurringInvoice.selectedFrequency != null &&
recurringInvoiceStore.newRecurringInvoice.selectedFrequency.value ===
'CUSTOM'
)
})
watch(
() => recurringInvoiceStore.newRecurringInvoice.selectedFrequency,
(newValue: FrequencyOption | null) => {
if (!recurringInvoiceStore.isFetchingInitialSettings) {
if (newValue && newValue.value !== 'CUSTOM') {
recurringInvoiceStore.newRecurringInvoice.frequency = newValue.value
} else {
recurringInvoiceStore.newRecurringInvoice.frequency = null
}
}
},
)
onMounted(() => {
getNextInvoiceDate()
})
function hasLimitBy(limitBy: string): boolean {
return recurringInvoiceStore.newRecurringInvoice.limit_by === limitBy
}
const debounceNextDate = useDebounceFn(() => {
getNextInvoiceDate()
}, 500)
async function getNextInvoiceDate(): Promise<void> {
const val = recurringInvoiceStore.newRecurringInvoice.frequency
if (!val) return
isLoadingNextDate.value = true
try {
await recurringInvoiceStore.fetchRecurringInvoiceFrequencyDate({
starts_at: recurringInvoiceStore.newRecurringInvoice.starts_at,
frequency: val,
})
} catch {
// Error handled in store
} finally {
isLoadingNextDate.value = false
}
}
</script>

View File

@@ -0,0 +1,378 @@
<template>
<BaseModal
:show="modalActive"
@close="closeModal"
@open="setInitialData"
>
<template #header>
<div class="flex justify-between w-full">
{{ modalTitle }}
<BaseIcon
name="XMarkIcon"
class="w-6 h-6 text-muted cursor-pointer"
@click="closeModal"
/>
</div>
</template>
<form v-if="!isPreview" @submit.prevent>
<div class="px-8 py-8 sm:p-6">
<BaseInputGrid layout="one-column" class="col-span-7">
<BaseInputGroup
:label="$t('general.from')"
required
:error="
v$.from.$error ? (v$.from.$errors[0]?.$message as string) : undefined
"
>
<BaseInput
v-model="form.from"
type="text"
:invalid="v$.from.$error"
@input="v$.from.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.to')"
required
:error="
v$.to.$error ? (v$.to.$errors[0]?.$message as string) : undefined
"
>
<BaseInput
v-model="form.to"
type="text"
:invalid="v$.to.$error"
@input="v$.to.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.cc')"
:error="
v$.cc.$error ? (v$.cc.$errors[0]?.$message as string) : undefined
"
>
<BaseInput
v-model="form.cc"
type="text"
:invalid="v$.cc.$error"
@input="v$.cc.$touch()"
placeholder="Optional: CC recipient"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.bcc')"
:error="
v$.bcc.$error ? (v$.bcc.$errors[0]?.$message as string) : undefined
"
>
<BaseInput
v-model="form.bcc"
type="text"
:invalid="v$.bcc.$error"
@input="v$.bcc.$touch()"
placeholder="Optional: BCC recipient"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.subject')"
required
:error="
v$.subject.$error
? (v$.subject.$errors[0]?.$message as string)
: undefined
"
>
<BaseInput
v-model="form.subject"
type="text"
:invalid="v$.subject.$error"
@input="v$.subject.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.body')"
required
:error="
v$.body.$error ? (v$.body.$errors[0]?.$message as string) : undefined
"
>
<BaseCustomInput
v-model="form.body"
:fields="invoiceMailFields"
/>
</BaseInputGroup>
</BaseInputGrid>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
class="mr-3"
variant="primary-outline"
type="button"
@click="closeModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isLoading"
:disabled="isLoading"
variant="primary"
type="button"
class="mr-3"
@click="submitForm"
>
<template #left="slotProps">
<BaseIcon
v-if="!isLoading"
:class="slotProps.class"
name="PhotoIcon"
/>
</template>
{{ $t('general.preview') }}
</BaseButton>
</div>
</form>
<div v-else>
<div class="my-6 mx-4 border border-line-default relative">
<BaseButton
class="absolute top-4 right-4"
:disabled="isLoading"
variant="primary-outline"
@click="cancelPreview"
>
<BaseIcon name="PencilIcon" class="h-5 mr-2" />
{{ $t('general.edit') }}
</BaseButton>
<iframe
:src="templateUrl"
frameborder="0"
class="w-full"
style="min-height: 500px"
/>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
class="mr-3"
variant="primary-outline"
type="button"
@click="closeModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isLoading"
:disabled="isLoading"
variant="primary"
type="button"
@click="submitForm"
>
<BaseIcon
v-if="!isLoading"
name="PaperAirplaneIcon"
class="h-5 mr-2"
/>
{{ $t('general.send') }}
</BaseButton>
</div>
</div>
</BaseModal>
</template>
<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useVuelidate } from '@vuelidate/core'
import { required, email, helpers } from '@vuelidate/validators'
import { useModalStore } from '../../../../stores/modal.store'
import { useCompanyStore } from '../../../../stores/company.store'
import { useNotificationStore } from '../../../../stores/notification.store'
import { useInvoiceStore } from '../store'
interface InvoiceMailForm {
id: number | string | null
from: string | null
to: string | null
cc: string | null
bcc: string | null
subject: string
body: string | null
}
type FieldType = 'customer' | 'customerCustom' | 'invoice' | 'invoiceCustom' | 'company'
const modalStore = useModalStore()
const companyStore = useCompanyStore()
const notificationStore = useNotificationStore()
const invoiceStore = useInvoiceStore()
const { t } = useI18n()
const isLoading = ref<boolean>(false)
const templateUrl = ref<string>('')
const isPreview = ref<boolean>(false)
const invoiceMailFields = ref<FieldType[]>([
'customer',
'customerCustom',
'invoice',
'invoiceCustom',
'company',
])
const form = reactive<InvoiceMailForm>({
id: null,
from: null,
to: null,
cc: null,
bcc: null,
subject: t('invoices.new_invoice'),
body: null,
})
const modalActive = computed<boolean>(() => {
return modalStore.active && modalStore.componentName === 'SendInvoiceModal'
})
const modalTitle = computed<string>(() => {
return modalStore.title
})
const modalData = computed<Record<string, unknown> | null>(() => {
return modalStore.data as Record<string, unknown> | null
})
const rules = computed(() => ({
from: {
required: helpers.withMessage(t('validation.required'), required),
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
to: {
required: helpers.withMessage(t('validation.required'), required),
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
cc: {
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
bcc: {
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
subject: {
required: helpers.withMessage(t('validation.required'), required),
},
body: {
required: helpers.withMessage(t('validation.required'), required),
},
}))
const v$ = useVuelidate(rules, form)
function cancelPreview(): void {
isPreview.value = false
}
async function setInitialData(): Promise<void> {
try {
const admin = await companyStore.fetchBasicMailConfig()
form.id = modalStore.id
if (admin?.data) {
form.from = (admin.data as Record<string, unknown>).from_mail as string
}
if (modalData.value?.customer) {
const customer = modalData.value.customer as Record<string, unknown>
form.to = (customer.email as string) ?? null
}
form.body = companyStore.selectedCompanySettings.invoice_mail_body ?? null
} catch {
// Silently handle initialization errors
}
}
async function submitForm(): Promise<void> {
v$.value.$touch()
if (v$.value.$invalid) {
return
}
try {
isLoading.value = true
if (!isPreview.value) {
const previewResponse = await invoiceStore.previewInvoice({
id: form.id as number,
from: form.from,
to: form.to,
cc: form.cc,
bcc: form.bcc,
subject: form.subject,
body: form.body,
})
isLoading.value = false
isPreview.value = true
const blob = new Blob(
[(previewResponse as { data: string }).data ?? previewResponse],
{ type: 'text/html' },
)
templateUrl.value = URL.createObjectURL(blob)
return
}
await invoiceStore.sendInvoice({
id: form.id as number,
from: form.from,
to: form.to,
cc: form.cc,
bcc: form.bcc,
subject: form.subject,
body: form.body,
})
isLoading.value = false
notificationStore.showNotification({
type: 'success',
message: 'invoices.invoice_sent_successfully',
})
if (modalStore.refreshData) {
modalStore.refreshData()
}
closeModal()
} catch {
isLoading.value = false
notificationStore.showNotification({
type: 'error',
message: t('invoices.something_went_wrong'),
})
}
}
function closeModal(): void {
modalStore.closeModal()
setTimeout(() => {
v$.value.$reset()
isPreview.value = false
templateUrl.value = ''
}, 300)
}
</script>

View File

@@ -10,6 +10,7 @@ export const invoiceRoutes: RouteRecordRaw[] = [
name: 'invoices.index',
component: InvoiceIndexView,
meta: {
requiresAuth: true,
ability: 'view-invoice',
title: 'invoices.title',
},
@@ -19,6 +20,7 @@ export const invoiceRoutes: RouteRecordRaw[] = [
name: 'invoices.create',
component: InvoiceCreateView,
meta: {
requiresAuth: true,
ability: 'create-invoice',
title: 'invoices.new_invoice',
},
@@ -28,6 +30,7 @@ export const invoiceRoutes: RouteRecordRaw[] = [
name: 'invoices.edit',
component: InvoiceCreateView,
meta: {
requiresAuth: true,
ability: 'edit-invoice',
title: 'invoices.edit_invoice',
},
@@ -37,6 +40,7 @@ export const invoiceRoutes: RouteRecordRaw[] = [
name: 'invoices.view',
component: InvoiceDetailView,
meta: {
requiresAuth: true,
ability: 'view-invoice',
title: 'invoices.title',
},

View File

@@ -1,4 +1,6 @@
import { defineStore } from 'pinia'
import { useNotificationStore } from '../../../stores/notification.store'
import { useCompanyStore } from '../../../stores/company.store'
import { invoiceService } from '../../../api/services/invoice.service'
import type {
InvoiceListParams,
@@ -14,6 +16,7 @@ import type { Customer } from '../../../types/domain/customer'
import type { Note } from '../../../types/domain/note'
import type { CustomFieldValue } from '../../../types/domain/custom-field'
import type { DocumentTax, DocumentItem } from '../../shared/document-form/use-document-calculations'
import { generateClientId } from '../../../utils'
// ----------------------------------------------------------------
// Stub factories
@@ -21,11 +24,11 @@ import type { DocumentTax, DocumentItem } from '../../shared/document-form/use-d
function createTaxStub(): DocumentTax {
return {
id: crypto.randomUUID(),
id: generateClientId(),
name: '',
tax_type_id: 0,
type: 'GENERAL',
amount: 0,
amount: null,
percent: null,
compound_tax: false,
calculation_type: null,
@@ -35,7 +38,7 @@ function createTaxStub(): DocumentTax {
function createInvoiceItemStub(): DocumentItem {
return {
id: crypto.randomUUID(),
id: generateClientId(),
invoice_id: null,
item_id: null,
name: '',
@@ -219,7 +222,7 @@ export const useInvoiceStore = defineStore('invoice', {
this.newInvoice = createInvoiceStub()
},
async previewInvoice(params: { id: number }): Promise<unknown> {
async previewInvoice(params: SendInvoicePayload): Promise<unknown> {
return invoiceService.sendPreview(params)
},
@@ -305,6 +308,13 @@ export const useInvoiceStore = defineStore('invoice', {
async addInvoice(data: Record<string, unknown>): Promise<{ data: { data: Invoice } }> {
const response = await invoiceService.create(data as never)
this.invoices = [...this.invoices, response.data]
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'invoices.created_message',
})
return { data: response }
},
@@ -336,6 +346,13 @@ export const useInvoiceStore = defineStore('invoice', {
if (pos !== -1) {
this.invoices[pos] = response.data
}
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'invoices.updated_message',
})
return { data: response }
},
@@ -440,14 +457,17 @@ export const useInvoiceStore = defineStore('invoice', {
async fetchInvoiceInitialSettings(
isEdit: boolean,
routeParams?: { id?: string; query?: Record<string, string> },
companySettings?: Record<string, string>,
companySettingsParam?: Record<string, string>,
companyCurrency?: Currency,
userSettings?: Record<string, string>,
): Promise<void> {
this.isFetchingInitialSettings = true
if (companyCurrency) {
this.newInvoice.selectedCurrency = companyCurrency
const companyStore = useCompanyStore()
const companySettings = companySettingsParam ?? companyStore.selectedCompanySettings
if (companyCurrency || companyStore.selectedCompanyCurrency) {
this.newInvoice.selectedCurrency = companyCurrency ?? companyStore.selectedCompanyCurrency!
}
// If customer is specified in route query

View File

@@ -15,6 +15,12 @@
</BaseBreadcrumb>
<template #actions>
<!-- Make Recurring Toggle -->
<div v-if="!isEdit" class="flex items-center mr-4">
<BaseSwitch v-model="isRecurring" class="mr-2" />
<span class="text-sm font-medium text-heading whitespace-nowrap">{{ $t('recurring_invoices.make_recurring') }}</span>
</div>
<router-link
v-if="isEdit"
:to="`/invoices/pdf/${invoiceStore.newInvoice.unique_hash}`"
@@ -40,7 +46,7 @@
:class="slotProps.class"
/>
</template>
{{ $t('invoices.save_invoice') }}
{{ isRecurring ? $t('recurring_invoices.save_invoice') : $t('invoices.save_invoice') }}
</BaseButton>
</template>
</BasePageHeader>
@@ -50,6 +56,7 @@
:v="v$"
:is-loading="isLoadingContent"
:is-edit="isEdit"
:is-recurring="isRecurring"
/>
<BaseScrollPane>
@@ -81,6 +88,7 @@
store-prop="newInvoice"
:is-mark-as-default="isMarkAsDefault"
/>
<SelectTemplateModal />
</div>
<DocumentTotals
@@ -100,6 +108,7 @@
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import cloneDeep from 'lodash/cloneDeep'
import {
required,
maxLength,
@@ -109,15 +118,18 @@ import {
} from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import { useInvoiceStore } from '../store'
import { useRecurringInvoiceStore } from '@v2/features/company/recurring-invoices/store'
import InvoiceBasicFields from '../components/InvoiceBasicFields.vue'
import {
DocumentItemsTable,
DocumentTotals,
DocumentNotes,
TemplateSelectButton,
SelectTemplateModal,
} from '../../../shared/document-form'
const invoiceStore = useInvoiceStore()
const recurringInvoiceStore = useRecurringInvoiceStore()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
@@ -125,40 +137,54 @@ const router = useRouter()
const invoiceValidationScope = 'newInvoice'
const isSaving = ref<boolean>(false)
const isMarkAsDefault = ref<boolean>(false)
const isRecurring = ref<boolean>(false)
const invoiceNoteFieldList = ref<Record<string, unknown> | null>(null)
const invoiceNoteFieldList = ref<string[]>(['customer', 'company', 'invoice'])
const isLoadingContent = computed<boolean>(
() => invoiceStore.isFetchingInvoice || invoiceStore.isFetchingInitialSettings,
)
const pageTitle = computed<string>(() =>
isEdit.value ? t('invoices.edit_invoice') : t('invoices.new_invoice'),
const pageTitle = computed<string>(() => {
if (isRecurringEdit.value) return t('recurring_invoices.edit_invoice')
if (isEdit.value) return t('invoices.edit_invoice')
return t('invoices.new_invoice')
})
const isEdit = computed<boolean>(() =>
route.name === 'invoices.edit' || route.name === 'recurring-invoices.edit',
)
const isEdit = computed<boolean>(() => route.name === 'invoices.edit')
const isRecurringEdit = computed<boolean>(() =>
route.name === 'recurring-invoices.edit',
)
const rules = {
invoice_date: {
required: helpers.withMessage(t('validation.required'), required),
},
reference_number: {
maxLength: helpers.withMessage(t('validation.price_maxlength'), maxLength(255)),
},
customer_id: {
required: helpers.withMessage(t('validation.required'), required),
},
invoice_number: {
required: helpers.withMessage(t('validation.required'), required),
},
exchange_rate: {
required: requiredIf(() => {
helpers.withMessage(t('validation.required'), required)
return invoiceStore.showExchangeRate
}),
decimal: helpers.withMessage(t('validation.valid_exchange_rate'), decimal),
},
}
const rules = computed(() => {
if (isRecurring.value) {
return {
customer_id: {
required: helpers.withMessage(t('validation.required'), required),
},
}
}
return {
invoice_date: {
required: helpers.withMessage(t('validation.required'), required),
},
reference_number: {
maxLength: helpers.withMessage(t('validation.price_maxlength'), maxLength(255)),
},
customer_id: {
required: helpers.withMessage(t('validation.required'), required),
},
invoice_number: {
required: helpers.withMessage(t('validation.required'), required),
},
exchange_rate: {
required: requiredIf(() => invoiceStore.showExchangeRate),
},
}
})
const v$ = useVuelidate(
rules,
@@ -169,10 +195,61 @@ const v$ = useVuelidate(
// Initialization
invoiceStore.resetCurrentInvoice()
v$.value.$reset
invoiceStore.fetchInvoiceInitialSettings(
isEdit.value,
{ id: route.params.id as string, query: route.query as Record<string, string> },
)
// Check for recurring mode
if (route.query.recurring === '1' || isRecurringEdit.value) {
isRecurring.value = true
}
// Initialize recurring store
recurringInvoiceStore.initFrequencies(t)
if (isRecurringEdit.value) {
// Editing a recurring invoice — load its data into both stores
recurringInvoiceStore.resetCurrentRecurringInvoice()
recurringInvoiceStore.fetchRecurringInvoiceInitialSettings(
true,
{ id: route.params.id as string, query: route.query as Record<string, string> },
).then(() => {
// Sync recurring data to invoice store for the shared form fields
const ri = recurringInvoiceStore.newRecurringInvoice
invoiceStore.newInvoice.customer = ri.customer
invoiceStore.newInvoice.customer_id = ri.customer_id
invoiceStore.newInvoice.items = ri.items as typeof invoiceStore.newInvoice.items
invoiceStore.newInvoice.taxes = ri.taxes as typeof invoiceStore.newInvoice.taxes
invoiceStore.newInvoice.notes = ri.notes
invoiceStore.newInvoice.discount = ri.discount
invoiceStore.newInvoice.discount_type = ri.discount_type as typeof invoiceStore.newInvoice.discount_type
invoiceStore.newInvoice.discount_val = ri.discount_val
invoiceStore.newInvoice.discount_per_item = ri.discount_per_item
invoiceStore.newInvoice.tax_per_item = ri.tax_per_item
invoiceStore.newInvoice.tax_included = ri.tax_included
invoiceStore.newInvoice.template_name = ri.template_name
invoiceStore.newInvoice.currency_id = ri.currency_id as typeof invoiceStore.newInvoice.currency_id
invoiceStore.newInvoice.exchange_rate = ri.exchange_rate as typeof invoiceStore.newInvoice.exchange_rate
invoiceStore.newInvoice.customFields = ri.customFields as typeof invoiceStore.newInvoice.customFields
})
} else if (!isRecurring.value) {
// Normal invoice create/edit
invoiceStore.fetchInvoiceInitialSettings(
isEdit.value,
{ id: route.params.id as string, query: route.query as Record<string, string> },
)
} else {
// New recurring invoice — just initialize
recurringInvoiceStore.resetCurrentRecurringInvoice()
invoiceStore.fetchInvoiceInitialSettings(
false,
{ query: route.query as Record<string, string> },
)
}
// Initialize recurring store when toggled on manually
watch(isRecurring, (newVal) => {
if (newVal && !isRecurringEdit.value) {
recurringInvoiceStore.resetCurrentRecurringInvoice()
}
})
watch(
() => invoiceStore.newInvoice.customer,
@@ -189,43 +266,95 @@ async function submitForm(): Promise<void> {
v$.value.$touch()
if (v$.value.$invalid) {
console.log('Invoice form invalid. Errors:', JSON.stringify(
v$.value.$errors.map((e: { $property: string; $message: string }) => `${e.$property}: ${e.$message}`)
))
return
}
isSaving.value = true
const data: Record<string, unknown> = {
...structuredClone(invoiceStore.newInvoice),
sub_total: invoiceStore.getSubTotal,
total: invoiceStore.getTotal,
tax: invoiceStore.getTotalTax,
}
const items = data.items as Array<Record<string, unknown>>
if (data.discount_per_item === 'YES') {
items.forEach((item, index) => {
if (item.discount_type === 'fixed') {
items[index].discount = (item.discount as number) * 100
}
})
} else {
if (data.discount_type === 'fixed') {
data.discount = (data.discount as number) * 100
}
}
const taxes = data.taxes as Array<Record<string, unknown>>
if (data.tax_per_item !== 'YES' && taxes.length) {
data.tax_type_ids = taxes.map((tax) => tax.tax_type_id)
}
try {
const action = isEdit.value
? invoiceStore.updateInvoice
: invoiceStore.addInvoice
if (isRecurring.value) {
const recurringData = recurringInvoiceStore.newRecurringInvoice
const invoiceData = invoiceStore.newInvoice
const response = await action(data)
router.push(`/admin/invoices/${response.data.data.id}/view`)
// Build clean payload with only backend-expected fields
const data: Record<string, unknown> = {
// Recurring-specific fields
starts_at: recurringData.starts_at,
send_automatically: recurringData.send_automatically ? 1 : 0,
frequency: recurringData.frequency,
status: recurringData.status || 'ACTIVE',
limit_by: recurringData.limit_by || 'NONE',
limit_count: recurringData.limit_count,
limit_date: recurringData.limit_date,
// Shared fields from invoice form
customer_id: invoiceData.customer_id,
discount: invoiceData.discount,
discount_type: invoiceData.discount_type,
discount_val: invoiceData.discount_val,
discount_per_item: invoiceData.discount_per_item,
tax_per_item: invoiceData.tax_per_item,
tax_included: invoiceData.tax_included,
sales_tax_type: invoiceData.sales_tax_type,
sales_tax_address_type: invoiceData.sales_tax_address_type,
notes: invoiceData.notes,
template_name: invoiceData.template_name,
items: cloneDeep(invoiceData.items),
taxes: cloneDeep(invoiceData.taxes),
currency_id: invoiceData.currency_id,
exchange_rate: invoiceData.exchange_rate,
customFields: invoiceData.customFields,
// Calculated totals
sub_total: invoiceStore.getSubTotal,
total: invoiceStore.getTotal,
tax: invoiceStore.getTotalTax,
}
let response
if (isRecurringEdit.value) {
data.id = recurringData.id
response = await recurringInvoiceStore.updateRecurringInvoice(data)
} else {
response = await recurringInvoiceStore.addRecurringInvoice(data)
}
router.push(`/admin/recurring-invoices/${response.data.data.id}/view`)
} else {
const data: Record<string, unknown> = {
...cloneDeep(invoiceStore.newInvoice),
sub_total: invoiceStore.getSubTotal,
total: invoiceStore.getTotal,
tax: invoiceStore.getTotalTax,
}
const items = data.items as Array<Record<string, unknown>>
if (data.discount_per_item === 'YES') {
items.forEach((item, index) => {
if (item.discount_type === 'fixed') {
items[index].discount = (item.discount as number) * 100
}
})
} else {
if (data.discount_type === 'fixed') {
data.discount = (data.discount as number) * 100
}
}
const taxes = data.taxes as Array<Record<string, unknown>>
if (data.tax_per_item !== 'YES' && taxes.length) {
data.tax_type_ids = taxes.map((tax) => tax.tax_type_id)
}
const action = isEdit.value
? invoiceStore.updateInvoice
: invoiceStore.addInvoice
const response = await action(data)
router.push(`/admin/invoices/${response.data.data.id}/view`)
}
} catch (err) {
console.error(err)
}

View File

@@ -16,7 +16,7 @@
<BaseButton
v-if="invoiceData.status === 'DRAFT' && canSend"
variant="primary"
class="text-sm"
class="text-sm mr-3"
@click="onSendInvoice"
>
{{ $t('invoices.send_invoice') }}
@@ -197,12 +197,9 @@
</div>
<!-- PDF Preview -->
<div class="flex flex-col min-h-0 mt-8 overflow-hidden" style="height: 75vh">
<iframe
:src="shareableLink"
class="flex-1 border border-gray-400 border-solid bg-surface rounded-xl frame-style"
/>
</div>
<BasePdfPreview :src="shareableLink" />
<SendInvoiceModal />
</BasePage>
</template>
@@ -212,7 +209,11 @@ import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useInvoiceStore } from '../store'
import InvoiceDropdown from '../components/InvoiceDropdown.vue'
import SendInvoiceModal from '../components/SendInvoiceModal.vue'
import LoadingIcon from '@v2/components/icons/LoadingIcon.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useDialogStore } from '../../../../stores/dialog.store'
import { useModalStore } from '../../../../stores/modal.store'
import type { Invoice } from '../../../../types/domain/invoice'
interface Props {
@@ -233,10 +234,48 @@ const props = withDefaults(defineProps<Props>(), {
canCreatePayment: false,
})
const ABILITIES = {
EDIT: 'edit-invoice',
VIEW: 'view-invoice',
CREATE: 'create-invoice',
DELETE: 'delete-invoice',
SEND: 'send-invoice',
CREATE_PAYMENT: 'create-payment',
} as const
const invoiceStore = useInvoiceStore()
const userStore = useUserStore()
const dialogStore = useDialogStore()
const modalStore = useModalStore()
const { t } = useI18n()
const route = useRoute()
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canCreate = computed<boolean>(() => {
return props.canCreate || userStore.hasAbilities(ABILITIES.CREATE)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const canSend = computed<boolean>(() => {
return props.canSend || userStore.hasAbilities(ABILITIES.SEND)
})
const canCreatePayment = computed<boolean>(() => {
return (
props.canCreatePayment || userStore.hasAbilities(ABILITIES.CREATE_PAYMENT)
)
})
const invoiceData = ref<Invoice | null>(null)
const isMarkAsSent = ref<boolean>(false)
const isLoading = ref<boolean>(false)
@@ -274,29 +313,36 @@ watch(route, (to) => {
}
})
async function onMarkAsSent(): Promise<void> {
const confirmed = window.confirm(t('invoices.invoice_mark_as_sent'))
if (!confirmed) return
isMarkAsSent.value = false
await invoiceStore.markAsSent({
id: invoiceData.value!.id,
status: 'SENT',
function onMarkAsSent(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.invoice_mark_as_sent'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'primary',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
isMarkAsSent.value = false
await invoiceStore.markAsSent({
id: invoiceData.value!.id,
status: 'SENT',
})
invoiceData.value!.status = 'SENT' as Invoice['status']
isMarkAsSent.value = true
isMarkAsSent.value = false
}
})
invoiceData.value!.status = 'SENT' as Invoice['status']
isMarkAsSent.value = true
isMarkAsSent.value = false
}
function onSendInvoice(): void {
const modalStore = (window as Record<string, unknown>).__modalStore as
| { openModal: (opts: Record<string, unknown>) => void }
| undefined
modalStore?.openModal({
modalStore.openModal({
title: t('invoices.send_invoice'),
componentName: 'SendInvoiceModal',
id: invoiceData.value!.id,
data: invoiceData.value,
refreshData: () => loadInvoice(),
})
}

View File

@@ -1,14 +1,50 @@
<template>
<BasePage>
<BasePageHeader :title="$t('invoices.title')">
<BaseBreadcrumb>
<BaseBreadcrumbItem :title="$t('general.home')" to="dashboard" />
<BaseBreadcrumbItem :title="$t('invoices.invoice', 2)" to="#" active />
</BaseBreadcrumb>
<BasePageHeader>
<template #default>
<div class="flex items-center gap-2">
<h1 class="text-2xl font-semibold text-heading">
{{ $t('invoices.title') }}
</h1>
<BaseDropdown position="bottom-start" width-class="w-44">
<template #activator>
<button
class="flex items-center gap-1 px-2 py-1 text-sm font-medium text-muted hover:text-heading rounded-md hover:bg-surface-secondary transition-colors"
>
<span class="text-xs text-primary-500 bg-primary-50 px-2 py-0.5 rounded-full">
{{ viewMode === 'one-time' ? $t('invoices.one_time') : $t('recurring_invoices.recurring') }}
</span>
<BaseIcon name="ChevronDownIcon" class="w-4 h-4 text-muted" />
</button>
</template>
<BaseDropdownItem
:class="{ 'bg-primary-50 text-primary-600': viewMode === 'one-time' }"
@click="setViewMode('one-time')"
>
<BaseIcon name="DocumentTextIcon" class="w-4 h-4 mr-2 text-subtle" />
{{ $t('invoices.one_time') }}
<BaseIcon v-if="viewMode === 'one-time'" name="CheckIcon" class="w-4 h-4 ml-auto text-primary-500" />
</BaseDropdownItem>
<BaseDropdownItem
v-if="canViewRecurring"
:class="{ 'bg-primary-50 text-primary-600': viewMode === 'recurring' }"
@click="setViewMode('recurring')"
>
<BaseIcon name="ArrowPathIcon" class="w-4 h-4 mr-2 text-subtle" />
{{ $t('recurring_invoices.recurring') }}
<BaseIcon v-if="viewMode === 'recurring'" name="CheckIcon" class="w-4 h-4 ml-auto text-primary-500" />
</BaseDropdownItem>
</BaseDropdown>
</div>
<BaseBreadcrumb>
<BaseBreadcrumbItem :title="$t('general.home')" to="dashboard" />
<BaseBreadcrumbItem :title="$t('invoices.invoice', 2)" to="#" active />
</BaseBreadcrumb>
</template>
<template #actions>
<BaseButton
v-show="invoiceStore.invoiceTotalCount"
v-show="viewMode === 'one-time' ? invoiceStore.invoiceTotalCount : recurringInvoiceStore.totalRecurringInvoices"
variant="primary-outline"
@click="toggleFilter"
>
@@ -23,7 +59,10 @@
</template>
</BaseButton>
<router-link v-if="canCreate" to="invoices/create">
<router-link
v-if="canCreate"
:to="viewMode === 'recurring' ? 'invoices/create?recurring=1' : 'invoices/create'"
>
<BaseButton variant="primary" class="ml-4">
<template #left="slotProps">
<BaseIcon name="PlusIcon" :class="slotProps.class" />
@@ -34,9 +73,9 @@
</template>
</BasePageHeader>
<!-- Filters -->
<!-- Filters (one-time) -->
<BaseFilterWrapper
v-show="showFilters"
v-show="showFilters && viewMode === 'one-time'"
:row-on-xl="true"
@clear="clearFilter"
>
@@ -91,162 +130,360 @@
</BaseInputGroup>
</BaseFilterWrapper>
<!-- Empty State -->
<BaseEmptyPlaceholder
v-show="showEmptyScreen"
:title="$t('invoices.no_invoices')"
:description="$t('invoices.list_of_invoices')"
<!-- Filters (recurring) -->
<BaseFilterWrapper
v-show="showFilters && viewMode === 'recurring'"
@clear="clearRecurringFilter"
>
<template v-if="canCreate" #actions>
<BaseButton
variant="primary-outline"
@click="$router.push('/admin/invoices/create')"
>
<template #left="slotProps">
<BaseIcon name="PlusIcon" :class="slotProps.class" />
</template>
{{ $t('invoices.add_new_invoice') }}
</BaseButton>
</template>
</BaseEmptyPlaceholder>
<BaseInputGroup :label="$t('customers.customer', 1)">
<BaseCustomerSelectInput
v-model="recurringFilters.customer_id"
:placeholder="$t('customers.type_or_click')"
value-prop="id"
label="name"
/>
</BaseInputGroup>
<BaseInputGroup :label="$t('recurring_invoices.status')">
<BaseMultiselect
v-model="recurringFilters.status"
:options="recurringStatusList"
searchable
:placeholder="$t('general.select_a_status')"
@update:model-value="setRecurringActiveTab"
@remove="clearRecurringStatusSearch()"
/>
</BaseInputGroup>
<BaseInputGroup :label="$t('general.from')">
<BaseDatePicker
v-model="recurringFilters.from_date"
:calendar-button="true"
calendar-button-icon="calendar"
/>
</BaseInputGroup>
<!-- Table -->
<div v-show="!showEmptyScreen" class="relative table-container">
<div
class="relative flex items-center justify-between h-10 mt-5 list-none border-b-2 border-line-default border-solid"
>
<BaseTabGroup class="-mb-5" @change="setStatusFilter">
<BaseTab :title="$t('general.all')" filter="" />
<BaseTab :title="$t('general.draft')" filter="DRAFT" />
<BaseTab :title="$t('general.sent')" filter="SENT" />
<BaseTab :title="$t('general.due')" filter="DUE" />
</BaseTabGroup>
class="hidden w-8 h-0 mx-4 border border-gray-400 border-solid xl:block"
style="margin-top: 1.5rem"
/>
<BaseDropdown
v-if="invoiceStore.selectedInvoices.length && canDelete"
class="absolute float-right"
<BaseInputGroup :label="$t('general.to')">
<BaseDatePicker
v-model="recurringFilters.to_date"
:calendar-button="true"
calendar-button-icon="calendar"
/>
</BaseInputGroup>
</BaseFilterWrapper>
<!-- One-time invoices section -->
<template v-if="viewMode === 'one-time'">
<!-- Empty State -->
<BaseEmptyPlaceholder
v-show="showEmptyScreen"
:title="$t('invoices.no_invoices')"
:description="$t('invoices.list_of_invoices')"
>
<template v-if="canCreate" #actions>
<BaseButton
variant="primary-outline"
@click="$router.push('/admin/invoices/create')"
>
<template #left="slotProps">
<BaseIcon name="PlusIcon" :class="slotProps.class" />
</template>
{{ $t('invoices.add_new_invoice') }}
</BaseButton>
</template>
</BaseEmptyPlaceholder>
<!-- Table -->
<div v-show="!showEmptyScreen" class="relative table-container">
<div
class="relative flex items-center justify-between mt-5 list-none"
>
<template #activator>
<span
class="flex text-sm font-medium cursor-pointer select-none text-primary-400"
>
{{ $t('general.actions') }}
<BaseIcon name="ChevronDownIcon" />
</span>
<BaseTabGroup @change="setStatusFilter">
<BaseTab :title="$t('general.all')" filter="" />
<BaseTab :title="$t('general.draft')" filter="DRAFT" />
<BaseTab :title="$t('general.sent')" filter="SENT" />
<BaseTab :title="$t('general.due')" filter="DUE" />
</BaseTabGroup>
<BaseDropdown
v-if="invoiceStore.selectedInvoices.length && canDelete"
class="absolute float-right"
>
<template #activator>
<span
class="flex text-sm font-medium cursor-pointer select-none text-primary-400"
>
{{ $t('general.actions') }}
<BaseIcon name="ChevronDownIcon" />
</span>
</template>
<BaseDropdownItem @click="removeMultipleInvoices">
<BaseIcon name="TrashIcon" class="mr-3 text-body" />
{{ $t('general.delete') }}
</BaseDropdownItem>
</BaseDropdown>
</div>
<BaseTable
ref="tableRef"
:data="fetchData"
:columns="invoiceColumns"
:placeholder-count="invoiceStore.invoiceTotalCount >= 20 ? 10 : 5"
:key="tableKey"
class="mt-4"
>
<template #header>
<div class="absolute items-center left-6 top-2.5 select-none">
<BaseCheckbox
v-model="invoiceStore.selectAllField"
variant="primary"
@change="invoiceStore.selectAllInvoices"
/>
</div>
</template>
<BaseDropdownItem @click="removeMultipleInvoices">
<BaseIcon name="TrashIcon" class="mr-3 text-body" />
{{ $t('general.delete') }}
</BaseDropdownItem>
</BaseDropdown>
</div>
<template #cell-checkbox="{ row }">
<div class="relative block">
<BaseCheckbox
:id="row.id"
v-model="selectField"
:value="row.data.id"
/>
</div>
</template>
<BaseTable
ref="tableRef"
:data="fetchData"
:columns="invoiceColumns"
:placeholder-count="invoiceStore.invoiceTotalCount >= 20 ? 10 : 5"
:key="tableKey"
class="mt-10"
>
<template #header>
<div class="absolute items-center left-6 top-2.5 select-none">
<BaseCheckbox
v-model="invoiceStore.selectAllField"
variant="primary"
@change="invoiceStore.selectAllInvoices"
/>
</div>
</template>
<template #cell-name="{ row }">
<router-link
v-if="row.data.customer?.id"
:to="`/admin/customers/${row.data.customer.id}/view`"
class="font-medium text-primary-500 hover:text-primary-600"
>
{{ row.data.customer.name }}
</router-link>
<span v-else>{{ row.data.customer?.name ?? '-' }}</span>
</template>
<template #cell-checkbox="{ row }">
<div class="relative block">
<BaseCheckbox
:id="row.id"
v-model="selectField"
:value="row.data.id"
/>
</div>
</template>
<template #cell-invoice_number="{ row }">
<router-link
:to="{ path: `invoices/${row.data.id}/view` }"
class="font-medium text-primary-500"
>
{{ row.data.invoice_number }}
</router-link>
</template>
<template #cell-name="{ row }">
<BaseText :text="row.data.customer.name" />
</template>
<template #cell-invoice_date="{ row }">
{{ row.data.formatted_invoice_date }}
</template>
<template #cell-invoice_number="{ row }">
<router-link
:to="{ path: `invoices/${row.data.id}/view` }"
class="font-medium text-primary-500"
>
{{ row.data.invoice_number }}
</router-link>
</template>
<template #cell-invoice_date="{ row }">
{{ row.data.formatted_invoice_date }}
</template>
<template #cell-total="{ row }">
<BaseFormatMoney
:amount="row.data.total"
:currency="row.data.customer.currency"
/>
</template>
<template #cell-status="{ row }">
<BaseInvoiceStatusBadge :status="row.data.status" class="px-3 py-1">
<BaseInvoiceStatusLabel :status="row.data.status" />
</BaseInvoiceStatusBadge>
</template>
<template #cell-due_amount="{ row }">
<div class="flex justify-between">
<template #cell-total="{ row }">
<BaseFormatMoney
:amount="row.data.due_amount"
:currency="row.data.currency"
:amount="row.data.total"
:currency="row.data.customer.currency"
/>
</template>
<BasePaidStatusBadge
v-if="row.data.overdue"
status="OVERDUE"
class="px-1 py-0.5 ml-2"
>
{{ $t('invoices.overdue') }}
</BasePaidStatusBadge>
<template #cell-status="{ row }">
<BaseInvoiceStatusBadge :status="row.data.status" class="px-3 py-1">
<BaseInvoiceStatusLabel :status="row.data.status" />
</BaseInvoiceStatusBadge>
</template>
<BasePaidStatusBadge
:status="row.data.paid_status"
class="px-1 py-0.5 ml-2"
>
<BaseInvoiceStatusLabel :status="row.data.paid_status" />
</BasePaidStatusBadge>
</div>
<template #cell-due_amount="{ row }">
<div class="flex justify-between">
<BaseFormatMoney
:amount="row.data.due_amount"
:currency="row.data.currency"
/>
<BasePaidStatusBadge
v-if="row.data.overdue"
status="OVERDUE"
class="px-1 py-0.5 ml-2"
>
{{ $t('invoices.overdue') }}
</BasePaidStatusBadge>
<BasePaidStatusBadge
:status="row.data.paid_status"
class="px-1 py-0.5 ml-2"
>
<BaseInvoiceStatusLabel :status="row.data.paid_status" />
</BasePaidStatusBadge>
</div>
</template>
<template v-if="hasAtLeastOneAbility" #cell-actions="{ row }">
<InvoiceDropdown
:row="row.data"
:table="tableRef"
:can-edit="canEdit"
:can-view="canView"
:can-create="canCreate"
:can-delete="canDelete"
:can-send="canSend"
:can-create-payment="canCreatePayment"
/>
</template>
</BaseTable>
</div>
</template>
<!-- Recurring invoices section -->
<template v-else-if="canViewRecurring">
<!-- Empty State -->
<BaseEmptyPlaceholder
v-show="showRecurringEmptyScreen"
:title="$t('recurring_invoices.no_invoices')"
:description="$t('recurring_invoices.list_of_invoices')"
>
<template v-if="canCreate" #actions>
<BaseButton
variant="primary-outline"
@click="$router.push('/admin/invoices/create?recurring=1')"
>
<template #left="slotProps">
<BaseIcon name="PlusIcon" :class="slotProps.class" />
</template>
{{ $t('recurring_invoices.add_new_invoice') }}
</BaseButton>
</template>
</BaseEmptyPlaceholder>
<template v-if="hasAtLeastOneAbility" #cell-actions="{ row }">
<InvoiceDropdown
:row="row.data"
:table="tableRef"
:can-edit="canEdit"
:can-view="canView"
:can-create="canCreate"
:can-delete="canDelete"
:can-send="canSend"
/>
</template>
</BaseTable>
</div>
<div v-show="!showRecurringEmptyScreen" class="relative table-container">
<!-- Recurring tabs -->
<div class="relative flex items-center justify-between mt-5 list-none">
<BaseTabGroup @change="setRecurringStatusFilter">
<BaseTab :title="$t('recurring_invoices.all')" filter="ALL" />
<BaseTab :title="$t('recurring_invoices.active')" filter="ACTIVE" />
<BaseTab :title="$t('recurring_invoices.on_hold')" filter="ON_HOLD" />
</BaseTabGroup>
<BaseDropdown
v-if="recurringInvoiceStore.selectedRecurringInvoices.length && canRecurringDelete"
class="absolute float-right"
>
<template #activator>
<span
class="flex text-sm font-medium cursor-pointer select-none text-primary-400"
>
{{ $t('general.actions') }}
<BaseIcon name="ChevronDownIcon" class="h-5" />
</span>
</template>
<BaseDropdownItem @click="removeMultipleRecurringInvoices">
<BaseIcon name="TrashIcon" class="mr-3 text-body" />
{{ $t('general.delete') }}
</BaseDropdownItem>
</BaseDropdown>
</div>
<!-- Recurring table -->
<BaseTable
ref="recurringTableRef"
:data="fetchRecurringData"
:columns="recurringColumns"
:placeholder-count="recurringInvoiceStore.totalRecurringInvoices >= 20 ? 10 : 5"
class="mt-4"
>
<template #header>
<div class="absolute items-center left-6 top-2.5 select-none">
<BaseCheckbox
v-model="recurringInvoiceStore.selectAllField"
variant="primary"
@change="recurringInvoiceStore.selectAllRecurringInvoices"
/>
</div>
</template>
<template #cell-checkbox="{ row }">
<div class="relative block">
<BaseCheckbox
:id="row.id"
v-model="recurringSelectField"
:value="row.data.id"
/>
</div>
</template>
<!-- starts_at column -->
<template #cell-starts_at="{ row }">
{{ row.data.formatted_starts_at }}
</template>
<!-- customer column -->
<template #cell-customer="{ row }">
<router-link
v-if="row.data.customer?.id"
:to="`/admin/customers/${row.data.customer.id}/view`"
class="flex flex-col"
>
<span class="font-medium text-primary-500 hover:text-primary-600">
{{ row.data.customer.name }}
</span>
<span v-if="row.data.customer.contact_name" class="text-xs text-subtle">
{{ row.data.customer.contact_name }}
</span>
</router-link>
<span v-else>-</span>
</template>
<!-- frequency column -->
<template #cell-frequency="{ row }">
{{ getFrequencyLabel(row.data.frequency) }}
</template>
<!-- status column -->
<template #cell-status="{ row }">
<BaseRecurringInvoiceStatusBadge :status="row.data.status" class="px-3 py-1">
<BaseRecurringInvoiceStatusLabel :status="row.data.status" />
</BaseRecurringInvoiceStatusBadge>
</template>
<!-- total column -->
<template #cell-total="{ row }">
<BaseFormatMoney
:amount="row.data.total"
:currency="row.data.customer?.currency"
/>
</template>
<!-- actions column -->
<template v-if="hasRecurringAtLeastOneAbility" #cell-actions="{ row }">
<RecurringInvoiceDropdown
:row="row.data"
:table="recurringTableRef"
:can-edit="canRecurringEdit"
:can-view="canRecurringView"
:can-delete="canRecurringDelete"
/>
</template>
</BaseTable>
</div>
</template>
</BasePage>
</template>
<script setup lang="ts">
import { computed, onUnmounted, reactive, ref } from 'vue'
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { debouncedWatch } from '@vueuse/core'
import { useInvoiceStore } from '../store'
import { useRecurringInvoiceStore } from '../../recurring-invoices/store'
import InvoiceDropdown from '../components/InvoiceDropdown.vue'
import RecurringInvoiceDropdown from '../../recurring-invoices/components/RecurringInvoiceDropdown.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { Invoice } from '../../../../types/domain/invoice'
import type { RecurringInvoice } from '../../../../types/domain/recurring-invoice'
interface Props {
canCreate?: boolean
@@ -264,9 +501,66 @@ const props = withDefaults(defineProps<Props>(), {
canSend: false,
})
const ABILITIES = {
CREATE: 'create-invoice',
EDIT: 'edit-invoice',
VIEW: 'view-invoice',
DELETE: 'delete-invoice',
SEND: 'send-invoice',
} as const
const RECURRING_ABILITIES = {
CREATE: 'create-recurring-invoice',
EDIT: 'edit-recurring-invoice',
VIEW: 'view-recurring-invoice',
DELETE: 'delete-recurring-invoice',
} as const
const invoiceStore = useInvoiceStore()
const recurringInvoiceStore = useRecurringInvoiceStore()
const userStore = useUserStore()
const dialogStore = useDialogStore()
const route = useRoute()
const router = useRouter()
const { t } = useI18n()
// ----------------------------------------------------------------
// Recurring invoice ability
// ----------------------------------------------------------------
const canViewRecurring = computed<boolean>(() => {
return userStore.hasAbilities(RECURRING_ABILITIES.VIEW)
})
// ----------------------------------------------------------------
// View mode toggle
// ----------------------------------------------------------------
const storedViewMode = localStorage.getItem('invoiceViewMode') as 'one-time' | 'recurring' | null
const viewMode = ref<'one-time' | 'recurring'>(
storedViewMode === 'recurring' && !canViewRecurring.value ? 'one-time' : (storedViewMode ?? 'one-time')
)
onMounted(() => {
if (route.query.view === 'recurring' && canViewRecurring.value) {
viewMode.value = 'recurring'
}
recurringInvoiceStore.initFrequencies(t)
})
function setViewMode(mode: 'one-time' | 'recurring'): void {
if (mode === 'recurring' && !canViewRecurring.value) return
viewMode.value = mode
localStorage.setItem('invoiceViewMode', mode)
router.replace({
query: mode === 'recurring' ? { view: 'recurring' } : {},
})
}
// ----------------------------------------------------------------
// One-time invoice state
// ----------------------------------------------------------------
const tableRef = ref<{ refresh: () => void } | null>(null)
const tableKey = ref<number>(0)
const showFilters = ref<boolean>(false)
@@ -331,8 +625,32 @@ const selectField = computed<number[]>({
},
})
const canCreate = computed<boolean>(() => {
return props.canCreate || userStore.hasAbilities(ABILITIES.CREATE)
})
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const canSend = computed<boolean>(() => {
return props.canSend || userStore.hasAbilities(ABILITIES.SEND)
})
const canCreatePayment = computed<boolean>(() => {
return userStore.hasAbilities('create-payment')
})
const hasAtLeastOneAbility = computed<boolean>(() => {
return props.canDelete || props.canEdit || props.canView || props.canSend
return canDelete.value || canEdit.value || canView.value || canSend.value
})
interface TableColumn {
@@ -385,6 +703,9 @@ onUnmounted(() => {
if (invoiceStore.selectAllField) {
invoiceStore.selectAllInvoices()
}
if (recurringInvoiceStore.selectAllField) {
recurringInvoiceStore.selectAllRecurringInvoices()
}
})
function clearStatusSearch(): void {
@@ -477,23 +798,36 @@ function clearFilter(): void {
activeTab.value = t('general.all')
}
async function removeMultipleInvoices(): Promise<void> {
const confirmed = window.confirm(t('invoices.confirm_delete'))
if (!confirmed) return
const res = await invoiceStore.deleteMultipleInvoices()
if (res.data.success) {
refreshTable()
invoiceStore.$patch((state) => {
state.selectedInvoices = []
state.selectAllField = false
})
}
function removeMultipleInvoices(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await invoiceStore.deleteMultipleInvoices()
if (response.data.success) {
refreshTable()
invoiceStore.$patch((state) => {
state.selectedInvoices = []
state.selectAllField = false
})
}
}
})
}
function toggleFilter(): void {
if (showFilters.value) {
clearFilter()
if (viewMode.value === 'one-time') {
clearFilter()
} else {
clearRecurringFilter()
}
}
showFilters.value = !showFilters.value
}
@@ -511,4 +845,214 @@ function setActiveTab(val: string): void {
}
activeTab.value = tabMap[val] ?? t('general.all')
}
// ----------------------------------------------------------------
// Recurring invoice state
// ----------------------------------------------------------------
const recurringTableRef = ref<{ refresh: () => void } | null>(null)
const isRecurringRequestOngoing = ref<boolean>(true)
const recurringActiveTab = ref<string>('recurring_invoices.all')
const recurringStatusList = ref<StatusOption[]>([
{ label: t('recurring_invoices.active'), value: 'ACTIVE' },
{ label: t('recurring_invoices.on_hold'), value: 'ON_HOLD' },
{ label: t('recurring_invoices.all'), value: 'ALL' },
])
interface RecurringInvoiceFilters {
customer_id: string | number
status: string
from_date: string
to_date: string
}
const recurringFilters = reactive<RecurringInvoiceFilters>({
customer_id: '',
status: '',
from_date: '',
to_date: '',
})
const showRecurringEmptyScreen = computed<boolean>(
() =>
!recurringInvoiceStore.totalRecurringInvoices &&
!isRecurringRequestOngoing.value,
)
const recurringSelectField = computed<number[]>({
get: () => recurringInvoiceStore.selectedRecurringInvoices,
set: (value: number[]) => {
recurringInvoiceStore.selectRecurringInvoice(value)
},
})
const canRecurringEdit = computed<boolean>(() => {
return userStore.hasAbilities(RECURRING_ABILITIES.EDIT)
})
const canRecurringView = computed<boolean>(() => {
return userStore.hasAbilities(RECURRING_ABILITIES.VIEW)
})
const canRecurringDelete = computed<boolean>(() => {
return userStore.hasAbilities(RECURRING_ABILITIES.DELETE)
})
const hasRecurringAtLeastOneAbility = computed<boolean>(() => {
return canRecurringDelete.value || canRecurringEdit.value || canRecurringView.value
})
const recurringColumns = computed<TableColumn[]>(() => [
{
key: 'checkbox',
thClass: 'extra',
tdClass: 'font-medium text-heading',
sortable: false,
},
{
key: 'starts_at',
label: t('recurring_invoices.starts_at'),
thClass: 'extra',
tdClass: 'font-medium',
},
{ key: 'customer', label: t('invoices.customer') },
{ key: 'frequency', label: t('recurring_invoices.frequency.title') },
{ key: 'status', label: t('invoices.status') },
{ key: 'total', label: t('invoices.total') },
{
key: 'actions',
label: t('recurring_invoices.action'),
tdClass: 'text-right text-sm font-medium',
thClass: 'text-right',
sortable: false,
},
])
debouncedWatch(recurringFilters, () => setRecurringFilters(), { debounce: 500 })
interface RecurringFetchResult {
data: RecurringInvoice[]
pagination: {
totalPages: number
currentPage: number
totalCount: number
limit: number
}
}
async function fetchRecurringData({
page,
sort,
}: FetchParams): Promise<RecurringFetchResult> {
const data = {
customer_id: recurringFilters.customer_id
? Number(recurringFilters.customer_id)
: undefined,
status: recurringFilters.status || undefined,
from_date: recurringFilters.from_date || undefined,
to_date: recurringFilters.to_date || undefined,
orderByField: sort.fieldName || 'created_at',
orderBy: sort.order || 'desc',
page,
}
isRecurringRequestOngoing.value = true
const response = await recurringInvoiceStore.fetchRecurringInvoices(
data as never,
)
isRecurringRequestOngoing.value = false
return {
data: response.data.data,
pagination: {
totalPages: response.data.meta.last_page,
currentPage: page,
totalCount: response.data.meta.total,
limit: 10,
},
}
}
function getFrequencyLabel(frequencyFormat: string): string {
const frequencyObj = recurringInvoiceStore.frequencies.find(
(f) => f.value === frequencyFormat,
)
return frequencyObj ? frequencyObj.label : `CUSTOM: ${frequencyFormat}`
}
function refreshRecurringTable(): void {
recurringTableRef.value?.refresh()
}
function setRecurringStatusFilter(val: { title: string }): void {
if (recurringActiveTab.value === val.title) return
recurringActiveTab.value = val.title
switch (val.title) {
case t('recurring_invoices.active'):
recurringFilters.status = 'ACTIVE'
break
case t('recurring_invoices.on_hold'):
recurringFilters.status = 'ON_HOLD'
break
default:
recurringFilters.status = ''
break
}
}
function setRecurringFilters(): void {
recurringInvoiceStore.$patch((state) => {
state.selectedRecurringInvoices = []
state.selectAllField = false
})
refreshRecurringTable()
}
function clearRecurringFilter(): void {
recurringFilters.customer_id = ''
recurringFilters.status = ''
recurringFilters.from_date = ''
recurringFilters.to_date = ''
recurringActiveTab.value = t('recurring_invoices.all')
}
function clearRecurringStatusSearch(): void {
recurringFilters.status = ''
refreshRecurringTable()
}
function setRecurringActiveTab(val: string): void {
const tabMap: Record<string, string> = {
ACTIVE: t('recurring_invoices.active'),
ON_HOLD: t('recurring_invoices.on_hold'),
ALL: t('recurring_invoices.all'),
}
recurringActiveTab.value = tabMap[val] ?? t('recurring_invoices.all')
}
function removeMultipleRecurringInvoices(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response =
await recurringInvoiceStore.deleteMultipleRecurringInvoices()
if (response.data.success) {
refreshRecurringTable()
recurringInvoiceStore.$patch((state) => {
state.selectedRecurringInvoices = []
state.selectAllField = false
})
}
}
})
}
</script>

View File

@@ -10,10 +10,11 @@ import {
import useVuelidate from '@vuelidate/core'
import { useModalStore } from '../../../../stores/modal.store'
import { useCompanyStore } from '../../../../stores/company.store'
import { useUserStore } from '../../../../stores/user.store'
import { useItemStore } from '../store'
// Tax type store - imported from original location
import { taxTypeService } from '@v2/api/services/tax-type.service'
import { useTaxTypes } from '../use-tax-types'
import ItemUnitModal from '@v2/features/company/settings/components/ItemUnitModal.vue'
import type { TaxType } from '@v2/types/domain/tax'
interface TaxOption {
id: number
@@ -24,6 +25,10 @@ interface TaxOption {
tax_name: string
}
const ABILITIES = {
VIEW_TAX_TYPE: 'view-tax-type',
} as const
interface Emits {
(e: 'newItem', item: unknown): void
}
@@ -33,7 +38,8 @@ const emit = defineEmits<Emits>()
const modalStore = useModalStore()
const itemStore = useItemStore()
const companyStore = useCompanyStore()
// Tax types fetched via service
const userStore = useUserStore()
const { taxTypes, fetchTaxTypes } = useTaxTypes()
const { t } = useI18n()
const isLoading = ref<boolean>(false)
@@ -54,7 +60,7 @@ const price = computed<number>({
const taxes = computed({
get: () =>
itemStore.currentItem.taxes.map((tax) => {
itemStore.currentItem.taxes?.map((tax) => {
if (tax) {
const currencySymbol = companyStore.selectedCompanyCurrency?.symbol ?? '$'
return {
@@ -68,7 +74,7 @@ const taxes = computed({
}
}
return tax
}),
}) ?? [],
set: (value: TaxOption[]) => {
itemStore.currentItem.taxes = value as unknown as typeof itemStore.currentItem.taxes
},
@@ -100,7 +106,7 @@ const v$ = useVuelidate(
)
const getTaxTypes = computed<TaxOption[]>(() => {
return taxTypeStore.taxTypes.map((tax) => {
return taxTypes.value.map((tax: TaxType) => {
const currencyCode = companyStore.selectedCompanyCurrency?.code ?? 'USD'
const amount =
tax.calculation_type === 'fixed'
@@ -117,9 +123,13 @@ const getTaxTypes = computed<TaxOption[]>(() => {
}) as TaxOption[]
})
onMounted(() => {
onMounted(async () => {
v$.value.$reset()
itemStore.fetchItemUnits({ limit: 'all' })
await itemStore.fetchItemUnits({ limit: 'all' })
if (userStore.hasAbilities(ABILITIES.VIEW_TAX_TYPE)) {
await fetchTaxTypes()
}
})
async function submitItemData(): Promise<void> {
@@ -163,6 +173,17 @@ async function submitItemData(): Promise<void> {
}
}
function addItemUnit(): void {
modalStore.openModal({
title: t('settings.customization.items.add_item_unit'),
componentName: 'ItemUnitModal',
size: 'sm',
refreshData: (unit: { id: number }) => {
itemStore.currentItem.unit_id = unit.id
},
})
}
function closeItemModal(): void {
modalStore.closeModal()
setTimeout(() => {
@@ -225,7 +246,18 @@ function closeItemModal(): void {
:placeholder="$t('items.select_a_unit')"
searchable
track-by="name"
/>
>
<template #action>
<BaseSelectAction @click="addItemUnit">
<BaseIcon
name="PlusCircleIcon"
class="h-4 mr-2 -ml-2 text-center text-primary-400"
/>
{{ $t('settings.customization.items.add_item_unit') }}
</BaseSelectAction>
</template>
</BaseMultiselect>
<ItemUnitModal />
</BaseInputGroup>
<BaseInputGroup

View File

@@ -6,6 +6,7 @@ const itemRoutes: RouteRecordRaw[] = [
name: 'items.index',
component: () => import('./views/ItemIndexView.vue'),
meta: {
requiresAuth: true,
ability: 'view-item',
},
},
@@ -14,6 +15,7 @@ const itemRoutes: RouteRecordRaw[] = [
name: 'items.create',
component: () => import('./views/ItemCreateView.vue'),
meta: {
requiresAuth: true,
ability: 'create-item',
},
},
@@ -22,6 +24,7 @@ const itemRoutes: RouteRecordRaw[] = [
name: 'items.edit',
component: () => import('./views/ItemCreateView.vue'),
meta: {
requiresAuth: true,
ability: 'edit-item',
},
},

View File

@@ -0,0 +1,28 @@
import { ref } from 'vue'
import type { Ref } from 'vue'
import { taxTypeService } from '@v2/api/services/tax-type.service'
import type { TaxType } from '@v2/types/domain/tax'
import { handleApiError } from '@v2/utils/error-handling'
export function useTaxTypes(): {
taxTypes: Ref<TaxType[]>
fetchTaxTypes: () => Promise<TaxType[]>
} {
const taxTypes = ref<TaxType[]>([])
async function fetchTaxTypes(): Promise<TaxType[]> {
try {
const response = await taxTypeService.list({ limit: 'all' })
taxTypes.value = response.data
return taxTypes.value
} catch (error: unknown) {
handleApiError(error)
throw error
}
}
return {
taxTypes,
fetchTaxTypes,
}
}

View File

@@ -10,13 +10,12 @@ import {
} from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import { useItemStore } from '../store'
import { useTaxTypes } from '../use-tax-types'
import { useCompanyStore } from '../../../../stores/company.store'
import { useModalStore } from '../../../../stores/modal.store'
import { useUserStore } from '../../../../stores/user.store'
import ItemUnitModal from '@v2/features/company/settings/components/ItemUnitModal.vue'
// Tax type store - imported from original location
import { taxTypeService } from '@v2/api/services/tax-type.service'
import type { TaxType } from '@v2/types/domain/tax'
interface TaxOption {
id: number
@@ -33,7 +32,7 @@ const ABILITIES = {
} as const
const itemStore = useItemStore()
// Tax types fetched via service
const { taxTypes, fetchTaxTypes } = useTaxTypes()
const modalStore = useModalStore()
const companyStore = useCompanyStore()
const userStore = useUserStore()
@@ -45,6 +44,7 @@ const router = useRouter()
const isSaving = ref<boolean>(false)
const taxPerItem = ref<string>(companyStore.selectedCompanySettings.tax_per_item || 'NO')
const isFetchingInitialData = ref<boolean>(false)
const isEdit = computed<boolean>(() => route.name === 'items.edit')
itemStore.resetCurrentItem()
loadData()
@@ -81,14 +81,12 @@ const taxes = computed({
},
})
const isEdit = computed<boolean>(() => route.name === 'items.edit')
const pageTitle = computed<string>(() =>
isEdit.value ? t('items.edit_item') : t('items.new_item')
)
const getTaxTypes = computed<TaxOption[]>(() => {
return taxTypeStore.taxTypes.map((tax) => {
return taxTypes.value.map((tax: TaxType) => {
const currencyCode = companyStore.selectedCompanyCurrency?.code ?? 'USD'
return {
...tax,
@@ -132,6 +130,9 @@ async function addItemUnit(): Promise<void> {
title: t('settings.customization.items.add_item_unit'),
componentName: 'ItemUnitModal',
size: 'sm',
refreshData: (unit: { id: number }) => {
itemStore.currentItem.unit_id = unit.id
},
})
}
@@ -140,7 +141,7 @@ async function loadData(): Promise<void> {
await itemStore.fetchItemUnits({ limit: 'all' })
if (userStore.hasAbilities(ABILITIES.VIEW_TAX_TYPE)) {
await taxTypeStore.fetchTaxTypes({ limit: 'all' })
await fetchTaxTypes()
}
if (isEdit.value) {

View File

@@ -64,7 +64,7 @@ async function submitInvitation(): Promise<void> {
try {
await memberStore.inviteMember({
email: form.email,
role: form.role_id !== null ? String(form.role_id) : undefined,
role_id: form.role_id,
})
form.email = ''
form.role_id = null

View File

@@ -6,7 +6,8 @@ const memberRoutes: RouteRecordRaw[] = [
name: 'members.index',
component: () => import('./views/MemberIndexView.vue'),
meta: {
ability: 'view-member',
requiresAuth: true,
isOwner: true,
},
},
]

View File

@@ -37,7 +37,7 @@ interface FetchResult {
interface MemberFilters {
name: string
email: string
phone: string
role: string
}
const notificationStore = useNotificationStore()
@@ -54,7 +54,7 @@ const { t } = useI18n()
const filters = reactive<MemberFilters>({
name: '',
email: '',
phone: '',
role: '',
})
const userTableColumns = computed<TableColumn[]>(() => [
@@ -76,10 +76,6 @@ const userTableColumns = computed<TableColumn[]>(() => [
label: t('members.role'),
sortable: false,
},
{
key: 'phone',
label: t('members.phone'),
},
{
key: 'created_at',
label: t('members.added_on'),
@@ -136,8 +132,8 @@ function refreshTable(): void {
async function fetchData({ page, sort }: FetchParams): Promise<FetchResult> {
const data = {
display_name: filters.name,
phone: filters.phone,
email: filters.email,
role: filters.role || undefined,
orderByField: sort.fieldName || 'created_at',
orderBy: sort.order || 'desc',
page,
@@ -161,7 +157,7 @@ async function fetchData({ page, sort }: FetchParams): Promise<FetchResult> {
function clearFilter(): void {
filters.name = ''
filters.email = ''
filters.phone = ''
filters.role = ''
}
function toggleFilter(): void {
@@ -261,12 +257,16 @@ function removeMultipleUsers(): void {
/>
</BaseInputGroup>
<BaseInputGroup class="flex-1 mt-2" :label="$t('members.phone')">
<BaseInput
v-model="filters.phone"
type="text"
name="phone"
autocomplete="off"
<BaseInputGroup class="flex-1 mt-2" :label="$t('members.role')">
<BaseMultiselect
v-model="filters.role"
:options="memberStore.roles"
label="title"
value-prop="id"
:placeholder="$t('members.select_role')"
:can-clear="true"
:can-deselect="true"
searchable
/>
</BaseInputGroup>
</BaseFilterWrapper>
@@ -341,10 +341,6 @@ function removeMultipleUsers(): void {
<span>{{ row.data.roles?.length ? row.data.roles[0].title : '-' }}</span>
</template>
<template #cell-phone="{ row }">
<span>{{ row.data.phone ? row.data.phone : '-' }}</span>
</template>
<template #cell-created_at="{ row }">
<span>{{ row.data.formatted_created_at }}</span>
</template>

View File

@@ -9,6 +9,7 @@ export const moduleRoutes: RouteRecordRaw[] = [
name: 'modules.index',
component: ModuleIndexView,
meta: {
requiresAuth: true,
ability: 'manage-module',
title: 'modules.title',
},
@@ -18,6 +19,7 @@ export const moduleRoutes: RouteRecordRaw[] = [
name: 'modules.view',
component: ModuleDetailView,
meta: {
requiresAuth: true,
ability: 'manage-module',
title: 'modules.title',
},

View File

@@ -316,6 +316,7 @@ import { useI18n } from 'vue-i18n'
import { useModuleStore } from '../store'
import type { InstallationStep } from '../store'
import ModuleCard from '../components/ModuleCard.vue'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { Module, ModuleLink } from '../../../../types/domain/module'
interface ModuleLinkItem {
@@ -330,6 +331,7 @@ interface TabItem {
}
const moduleStore = useModuleStore()
const dialogStore = useDialogStore()
const route = useRoute()
const router = useRouter()
const { t } = useI18n()
@@ -449,18 +451,30 @@ async function handleInstall(): Promise<void> {
}
}
async function handleDisable(): Promise<void> {
function handleDisable(): void {
if (!moduleData.value) return
const confirmed = window.confirm(t('modules.disable_warning'))
if (!confirmed) return
isDisabling.value = true
const res = await moduleStore.disableModule(moduleData.value.module_name)
isDisabling.value = false
dialogStore
.openDialog({
title: t('general.are_you_sure'),
message: t('modules.disable_warning'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
.then(async (res: boolean) => {
if (res) {
isDisabling.value = true
const response = await moduleStore.disableModule(moduleData.value!.module_name)
isDisabling.value = false
if (res.success) {
setTimeout(() => location.reload(), 1500)
}
if (response.success) {
setTimeout(() => location.reload(), 1500)
}
}
})
}
async function handleEnable(): Promise<void> {

View File

@@ -9,7 +9,7 @@
<!-- Connected: module listing -->
<div v-if="hasApiToken && moduleStore.modules">
<BaseTabGroup class="-mb-5" @change="setStatusFilter">
<BaseTabGroup @change="setStatusFilter">
<BaseTab :title="$t('general.all')" filter="" />
<BaseTab :title="$t('modules.installed')" filter="INSTALLED" />
</BaseTabGroup>

View File

@@ -76,6 +76,8 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { usePaymentStore } from '../store'
import { useDialogStore } from '../../../../stores/dialog.store'
import { useModalStore } from '../../../../stores/modal.store'
import type { Payment } from '../../../../types/domain/payment'
interface TableRef {
@@ -102,20 +104,33 @@ const props = withDefaults(defineProps<Props>(), {
})
const paymentStore = usePaymentStore()
const dialogStore = useDialogStore()
const modalStore = useModalStore()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const isDetailView = computed<boolean>(() => route.name === 'payments.view')
async function removePayment(): Promise<void> {
const confirmed = window.confirm(t('payments.confirm_delete'))
if (!confirmed) return
const payment = props.row as Payment
await paymentStore.deletePayment({ ids: [payment.id] })
router.push('/admin/payments')
props.table?.refresh()
function removePayment(): void {
dialogStore
.openDialog({
title: t('general.are_you_sure'),
message: t('payments.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
.then(async (res: boolean) => {
if (res) {
const payment = props.row as Payment
await paymentStore.deletePayment({ ids: [payment.id] })
router.push('/admin/payments')
props.table?.refresh()
}
})
}
function copyPdfUrl(): void {
@@ -133,10 +148,7 @@ function copyPdfUrl(): void {
function sendPayment(): void {
const payment = props.row as Payment
const modalStore = (window as Record<string, unknown>).__modalStore as
| { openModal: (opts: Record<string, unknown>) => void }
| undefined
modalStore?.openModal({
modalStore.openModal({
title: t('payments.send_payment'),
componentName: 'SendPaymentModal',
id: payment.id,

View File

@@ -0,0 +1,321 @@
<template>
<BaseModal
:show="modalActive"
@close="closeSendPaymentModal"
@open="setInitialData"
>
<template #header>
<div class="flex justify-between w-full">
{{ modalTitle }}
<BaseIcon
name="XMarkIcon"
class="w-6 h-6 text-muted cursor-pointer"
@click="closeSendPaymentModal"
/>
</div>
</template>
<form v-if="!isPreview" action="">
<div class="px-8 py-8 sm:p-6">
<BaseInputGrid layout="one-column" class="col-span-7">
<BaseInputGroup
:label="$t('general.from')"
required
:error="v$.from.$error && v$.from.$errors[0].$message"
>
<BaseInput
v-model="paymentMailForm.from"
type="text"
:invalid="v$.from.$error"
@input="v$.from.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.to')"
required
:error="v$.to.$error && v$.to.$errors[0].$message"
>
<BaseInput
v-model="paymentMailForm.to"
type="text"
:invalid="v$.to.$error"
@input="v$.to.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.cc')"
:error="v$.cc && v$.cc.$error && v$.cc.$errors[0].$message"
>
<BaseInput
v-model="paymentMailForm.cc"
type="email"
:invalid="v$.cc && v$.cc.$error"
@input="v$.cc && v$.cc.$touch()"
placeholder="Optional: CC recipient"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.bcc')"
:error="v$.bcc && v$.bcc.$error && v$.bcc.$errors[0].$message"
>
<BaseInput
v-model="paymentMailForm.bcc"
type="email"
:invalid="v$.bcc && v$.bcc.$error"
@input="v$.bcc && v$.bcc.$touch()"
placeholder="Optional: BCC recipient"
/>
</BaseInputGroup>
<BaseInputGroup
:error="v$.subject.$error && v$.subject.$errors[0].$message"
:label="$t('general.subject')"
required
>
<BaseInput
v-model="paymentMailForm.subject"
type="text"
:invalid="v$.subject.$error"
@input="v$.subject.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('general.body')"
:error="v$.body.$error && v$.body.$errors[0].$message"
required
>
<BaseCustomInput
v-model="paymentMailForm.body"
:fields="['customer', 'company', 'payment']"
/>
</BaseInputGroup>
</BaseInputGrid>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
class="mr-3"
variant="primary-outline"
type="button"
@click="closeSendPaymentModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isLoading"
:disabled="isLoading"
variant="primary"
type="button"
class="mr-3"
@click="sendPaymentData"
>
<template #left="slotProps">
<BaseIcon
v-if="!isLoading"
:class="slotProps.class"
name="PhotoIcon"
/>
</template>
{{ $t('general.preview') }}
</BaseButton>
</div>
</form>
<div v-else>
<div class="my-6 mx-4 border border-line-default relative">
<BaseButton
class="absolute top-4 right-4"
:disabled="isLoading"
variant="primary-outline"
@click="cancelPreview"
>
<BaseIcon name="PencilIcon" class="h-5 mr-2" />
{{ $t('general.edit') }}
</BaseButton>
<iframe
:src="templateUrl"
frameborder="0"
class="w-full"
style="min-height: 500px"
></iframe>
</div>
<div
class="z-0 flex justify-end p-4 border-t border-line-default border-solid"
>
<BaseButton
class="mr-3"
variant="primary-outline"
type="button"
@click="closeSendPaymentModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isLoading"
:disabled="isLoading"
variant="primary"
type="button"
@click="sendPaymentData()"
>
<BaseIcon
v-if="!isLoading"
name="PaperAirplaneIcon"
class="h-5 mr-2"
/>
{{ $t('general.send') }}
</BaseButton>
</div>
</div>
</BaseModal>
</template>
<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { required, email, helpers } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { useModalStore } from '../../../../stores/modal.store'
import { useCompanyStore } from '../../../../stores/company.store'
import { useNotificationStore } from '../../../../stores/notification.store'
import { usePaymentStore } from '../store'
const modalStore = useModalStore()
const companyStore = useCompanyStore()
const notificationStore = useNotificationStore()
const paymentStore = usePaymentStore()
const { t } = useI18n()
const isLoading = ref(false)
const templateUrl = ref<string>('')
const isPreview = ref(false)
const paymentMailForm = reactive({
id: null as number | null,
from: null as string | null,
to: null as string | null,
cc: null as string | null,
bcc: null as string | null,
subject: t('payments.new_payment'),
body: null as string | null,
})
const modalActive = computed(() => {
return modalStore.active && modalStore.componentName === 'SendPaymentModal'
})
const modalTitle = computed(() => {
return modalStore.title
})
const modalData = computed(() => {
return modalStore.data as Record<string, unknown> | null
})
const rules = {
from: {
required: helpers.withMessage(t('validation.required'), required),
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
to: {
required: helpers.withMessage(t('validation.required'), required),
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
cc: {
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
bcc: {
email: helpers.withMessage(t('validation.email_incorrect'), email),
},
subject: {
required: helpers.withMessage(t('validation.required'), required),
},
body: {
required: helpers.withMessage(t('validation.required'), required),
},
}
const v$ = useVuelidate(rules, paymentMailForm)
function cancelPreview() {
isPreview.value = false
}
async function setInitialData() {
const admin = await companyStore.fetchBasicMailConfig()
paymentMailForm.id = modalStore.id as number
if (admin.data) {
paymentMailForm.from = (admin.data as Record<string, string>).from_mail
}
if (modalData.value) {
const customer = modalData.value.customer as Record<string, string> | undefined
if (customer) {
paymentMailForm.to = customer.email
}
}
paymentMailForm.body = companyStore.selectedCompanySettings.payment_mail_body
paymentMailForm.subject = t('payments.new_payment')
}
async function sendPaymentData() {
v$.value.$touch()
if (v$.value.$invalid) {
return true
}
try {
isLoading.value = true
if (!isPreview.value) {
const previewResponse = await paymentStore.previewPayment(
paymentMailForm as unknown as { id: number } & Record<string, unknown>,
)
isLoading.value = false
isPreview.value = true
const blob = new Blob([(previewResponse as { data: string }).data], {
type: 'text/html',
})
templateUrl.value = URL.createObjectURL(blob)
return
}
await paymentStore.sendEmail(
paymentMailForm as unknown as Parameters<typeof paymentStore.sendEmail>[0],
)
isLoading.value = false
notificationStore.showNotification({
type: 'success',
message: 'payments.payment_sent_successfully',
})
if (modalStore.refreshData) {
modalStore.refreshData()
}
closeSendPaymentModal()
} catch (error) {
console.error(error)
isLoading.value = false
notificationStore.showNotification({
type: 'error',
message: 'payments.something_went_wrong',
})
}
}
function closeSendPaymentModal() {
modalStore.closeModal()
setTimeout(() => {
v$.value.$reset()
isPreview.value = false
templateUrl.value = ''
}, 300)
}
</script>

View File

@@ -10,6 +10,7 @@ export const paymentRoutes: RouteRecordRaw[] = [
name: 'payments.index',
component: PaymentIndexView,
meta: {
requiresAuth: true,
ability: 'view-payment',
title: 'payments.title',
},
@@ -19,6 +20,7 @@ export const paymentRoutes: RouteRecordRaw[] = [
name: 'payments.create',
component: PaymentCreateView,
meta: {
requiresAuth: true,
ability: 'create-payment',
title: 'payments.new_payment',
},
@@ -28,6 +30,7 @@ export const paymentRoutes: RouteRecordRaw[] = [
name: 'payments.edit',
component: PaymentCreateView,
meta: {
requiresAuth: true,
ability: 'edit-payment',
title: 'payments.edit_payment',
},
@@ -37,6 +40,7 @@ export const paymentRoutes: RouteRecordRaw[] = [
name: 'payments.view',
component: PaymentDetailView,
meta: {
requiresAuth: true,
ability: 'view-payment',
title: 'payments.title',
},
@@ -46,6 +50,7 @@ export const paymentRoutes: RouteRecordRaw[] = [
name: 'payments.create-from-invoice',
component: PaymentCreateView,
meta: {
requiresAuth: true,
ability: 'create-payment',
title: 'payments.new_payment',
},

View File

@@ -1,4 +1,5 @@
import { defineStore } from 'pinia'
import { useNotificationStore } from '../../../stores/notification.store'
import { paymentService } from '../../../api/services/payment.service'
import type {
PaymentListParams,
@@ -129,6 +130,13 @@ export const usePaymentStore = defineStore('payment', {
): Promise<{ data: { data: Payment } }> {
const response = await paymentService.create(data as never)
this.payments.push(response.data)
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'payments.created_message',
})
return { data: response }
},
@@ -143,6 +151,13 @@ export const usePaymentStore = defineStore('payment', {
if (pos !== -1) {
this.payments[pos] = response.data
}
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'payments.updated_message',
})
return { data: response }
},
@@ -176,8 +191,8 @@ export const usePaymentStore = defineStore('payment', {
return paymentService.send(data)
},
async previewPayment(id: number): Promise<unknown> {
return paymentService.sendPreview(id)
async previewPayment(params: { id: number } & Record<string, unknown>): Promise<unknown> {
return paymentService.sendPreview(params.id, params)
},
async getNextNumber(

View File

@@ -78,9 +78,7 @@
:content-loading="isLoadingContent"
:placeholder="$t('customers.select_a_customer')"
show-action
@update:model-value="
selectNewCustomer(paymentStore.currentPayment.customer_id)
"
@update:model-value="onManualCustomerSelect"
/>
</BaseInputGroup>
@@ -177,10 +175,12 @@
</template>
<script setup lang="ts">
import { ref, computed, onBeforeUnmount } from 'vue'
import { ref, computed, watchEffect, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import cloneDeep from 'lodash/cloneDeep'
import { usePaymentStore } from '../store'
import { invoiceService } from '../../../../api/services/invoice.service'
import type { Invoice } from '../../../../types/domain/invoice'
const route = useRoute()
@@ -226,9 +226,90 @@ if (route.query.customer) {
}
paymentStore.fetchPaymentInitialData(isEdit.value, {
id: route.params.id as string | undefined,
id: isEdit.value ? (route.params.id as string) : undefined,
})
// Create-from-invoice: pre-select the invoice and its customer
if (route.params.id && !isEdit.value) {
setInvoiceFromUrl()
}
async function setInvoiceFromUrl(): Promise<void> {
try {
const response = await invoiceService.get(Number(route.params.id))
const invoice = response.data
paymentStore.currentPayment.customer_id = invoice.customer_id ?? (invoice.customer as Record<string, unknown>)?.id as number
paymentStore.currentPayment.invoice_id = invoice.id
} catch {
// Invoice not found
}
}
// Reactively fetch invoices whenever customer_id changes
// Handles: edit data load, manual selection, create-from-invoice
watchEffect(() => {
if (paymentStore.currentPayment.customer_id) {
onCustomerChange(paymentStore.currentPayment.customer_id)
}
})
async function onCustomerChange(customerId: number): Promise<void> {
const params: Record<string, unknown> = {
customer_id: customerId,
status: isEdit.value ? '' : 'DUE',
limit: 'all',
}
isLoadingInvoices.value = true
try {
const response = await invoiceService.list(params as never)
invoiceList.value = [...(response.data as unknown as Invoice[])]
if (paymentStore.currentPayment.invoice_id) {
selectedInvoice.value =
invoiceList.value.find(
(inv) => inv.id === paymentStore.currentPayment.invoice_id,
) ?? null
if (selectedInvoice.value) {
paymentStore.currentPayment.maxPayableAmount =
selectedInvoice.value.due_amount +
paymentStore.currentPayment.amount
if (amount.value === 0) {
amount.value = selectedInvoice.value.due_amount / 100
}
}
}
if (isEdit.value) {
invoiceList.value = invoiceList.value.filter(
(v) =>
v.due_amount > 0 ||
v.id === paymentStore.currentPayment.invoice_id,
)
}
} catch {
invoiceList.value = []
} finally {
isLoadingInvoices.value = false
}
}
function onManualCustomerSelect(): void {
const params: Record<string, unknown> = {
userId: paymentStore.currentPayment.customer_id,
}
if (route.params.id) {
params.model_id = route.params.id
}
paymentStore.currentPayment.invoice_id = null
selectedInvoice.value = null
paymentStore.currentPayment.amount = 0
paymentStore.getNextNumber(params, true)
}
function onSelectInvoice(id: number): void {
if (id) {
selectedInvoice.value =
@@ -241,26 +322,11 @@ function onSelectInvoice(id: number): void {
}
}
function selectNewCustomer(id: number | null): void {
if (!id) return
const params: Record<string, unknown> = { userId: id }
if (route.params.id) {
params.model_id = route.params.id
}
paymentStore.currentPayment.invoice_id = null
selectedInvoice.value = null
paymentStore.currentPayment.amount = 0
invoiceList.value = []
paymentStore.getNextNumber(params, true)
}
async function submitPaymentData(): Promise<void> {
isSaving.value = true
const data = {
...paymentStore.currentPayment,
...cloneDeep(paymentStore.currentPayment),
}
try {

View File

@@ -151,16 +151,9 @@
</div>
<!-- PDF Preview -->
<div
class="flex flex-col min-h-0 mt-8 overflow-hidden"
style="height: 75vh"
>
<iframe
v-if="shareableLink"
:src="shareableLink"
class="flex-1 border border-gray-400 border-solid rounded-md"
/>
</div>
<BasePdfPreview :src="shareableLink" />
<SendPaymentModal />
</BasePage>
</template>
@@ -170,7 +163,10 @@ import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { usePaymentStore } from '../store'
import PaymentDropdown from '../components/PaymentDropdown.vue'
import SendPaymentModal from '../components/SendPaymentModal.vue'
import LoadingIcon from '@v2/components/icons/LoadingIcon.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useModalStore } from '../../../../stores/modal.store'
import type { Payment } from '../../../../types/domain/payment'
interface Props {
@@ -187,10 +183,35 @@ const props = withDefaults(defineProps<Props>(), {
canSend: false,
})
const ABILITIES = {
EDIT: 'edit-payment',
VIEW: 'view-payment',
DELETE: 'delete-payment',
SEND: 'send-payment',
} as const
const paymentStore = usePaymentStore()
const userStore = useUserStore()
const modalStore = useModalStore()
const { t } = useI18n()
const route = useRoute()
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const canSend = computed<boolean>(() => {
return props.canSend || userStore.hasAbilities(ABILITIES.SEND)
})
const paymentData = ref<Payment | Record<string, unknown>>({})
const isFetching = ref<boolean>(false)
const isLoading = ref<boolean>(false)
@@ -340,15 +361,13 @@ function sortData(): void {
}
function onPaymentSend(): void {
const modalStore = (window as Record<string, unknown>).__modalStore as
| { openModal: (opts: Record<string, unknown>) => void }
| undefined
modalStore?.openModal({
modalStore.openModal({
title: t('payments.send_payment'),
componentName: 'SendPaymentModal',
id: (paymentData.value as Payment).id,
data: paymentData.value,
variant: 'lg',
refreshData: () => loadPayment(),
})
}
</script>

View File

@@ -155,7 +155,14 @@
</template>
<template #cell-name="{ row }">
<BaseText :text="row.data.customer.name" tag="span" />
<router-link
v-if="row.data.customer?.id"
:to="`/admin/customers/${row.data.customer.id}/view`"
class="font-medium text-primary-500 hover:text-primary-600"
>
{{ row.data.customer.name }}
</router-link>
<span v-else>{{ row.data.customer?.name ?? '-' }}</span>
</template>
<template #cell-payment_mode="{ row }">
@@ -165,9 +172,14 @@
</template>
<template #cell-invoice_number="{ row }">
<span>
{{ row.data.invoice?.invoice_number ?? '-' }}
</span>
<router-link
v-if="row.data.invoice?.id"
:to="`/admin/invoices/${row.data.invoice.id}/view`"
class="font-medium text-primary-500 hover:text-primary-600"
>
{{ row.data.invoice.invoice_number }}
</router-link>
<span v-else>-</span>
</template>
<template #cell-amount="{ row }">
@@ -198,6 +210,8 @@ import { useI18n } from 'vue-i18n'
import { debouncedWatch } from '@vueuse/core'
import { usePaymentStore } from '../store'
import PaymentDropdown from '../components/PaymentDropdown.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { Payment, PaymentMethod } from '../../../../types/domain/payment'
interface Props {
@@ -216,7 +230,17 @@ const props = withDefaults(defineProps<Props>(), {
canSend: false,
})
const ABILITIES = {
CREATE: 'create-payment',
EDIT: 'edit-payment',
VIEW: 'view-payment',
DELETE: 'delete-payment',
SEND: 'send-payment',
} as const
const paymentStore = usePaymentStore()
const userStore = useUserStore()
const dialogStore = useDialogStore()
const { t } = useI18n()
const tableRef = ref<{ refresh: () => void } | null>(null)
@@ -239,8 +263,28 @@ const showEmptyScreen = computed<boolean>(
() => !paymentStore.paymentTotalCount && !isFetchingInitialData.value,
)
const canCreate = computed<boolean>(() => {
return props.canCreate || userStore.hasAbilities(ABILITIES.CREATE)
})
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const canSend = computed<boolean>(() => {
return props.canSend || userStore.hasAbilities(ABILITIES.SEND)
})
const hasAtLeastOneAbility = computed<boolean>(() => {
return props.canDelete || props.canEdit || props.canView || props.canSend
return canDelete.value || canEdit.value || canView.value || canSend.value
})
interface TableColumn {
@@ -370,13 +414,24 @@ function toggleFilter(): void {
showFilters.value = !showFilters.value
}
async function removeMultiplePayments(): Promise<void> {
const confirmed = window.confirm(t('payments.confirm_delete'))
if (!confirmed) return
const res = await paymentStore.deleteMultiplePayments()
if (res.data.success) {
refreshTable()
}
function removeMultiplePayments(): void {
dialogStore
.openDialog({
title: t('general.are_you_sure'),
message: t('payments.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
})
.then(async (res: boolean) => {
if (res) {
const response = await paymentStore.deleteMultiplePayments()
if (response.data.success) {
refreshTable()
}
}
})
}
</script>

View File

@@ -1,7 +1,6 @@
<template>
<div class="col-span-5 pr-0">
<div class="col-span-6 pr-0">
<BaseCustomerSelectPopup
v-model="recurringInvoiceStore.newRecurringInvoice.customer"
:content-loading="isLoading"
type="recurring-invoice"
/>

View File

@@ -51,6 +51,7 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { useRecurringInvoiceStore } from '../store'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { RecurringInvoice } from '../../../../types/domain/recurring-invoice'
interface TableRef {
@@ -75,6 +76,7 @@ const props = withDefaults(defineProps<Props>(), {
})
const recurringInvoiceStore = useRecurringInvoiceStore()
const dialogStore = useDialogStore()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
@@ -83,25 +85,34 @@ const isDetailView = computed<boolean>(
() => route.name === 'recurring-invoices.view',
)
async function removeRecurringInvoice(): Promise<void> {
const confirmed = window.confirm(t('invoices.confirm_delete'))
if (!confirmed) return
function removeRecurringInvoice(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const invoiceRow = props.row as RecurringInvoice
const response = await recurringInvoiceStore.deleteMultipleRecurringInvoices(
invoiceRow.id,
)
const invoiceRow = props.row as RecurringInvoice
const res = await recurringInvoiceStore.deleteMultipleRecurringInvoices(
invoiceRow.id,
)
if (response.data.success) {
props.table?.refresh()
recurringInvoiceStore.$patch((state) => {
state.selectedRecurringInvoices = []
state.selectAllField = false
})
if (res.data.success) {
props.table?.refresh()
recurringInvoiceStore.$patch((state) => {
state.selectedRecurringInvoices = []
state.selectAllField = false
})
if (isDetailView.value) {
router.push('/admin/recurring-invoices')
if (isDetailView.value) {
router.push('/admin/recurring-invoices')
}
}
}
}
})
}
</script>

View File

@@ -1,36 +1,26 @@
import type { RouteRecordRaw } from 'vue-router'
const RecurringInvoiceIndexView = () =>
import('./views/RecurringInvoiceIndexView.vue')
const RecurringInvoiceCreateView = () =>
import('./views/RecurringInvoiceCreateView.vue')
const InvoiceCreateView = () =>
import('../invoices/views/InvoiceCreateView.vue')
const RecurringInvoiceDetailView = () =>
import('./views/RecurringInvoiceDetailView.vue')
export const recurringInvoiceRoutes: RouteRecordRaw[] = [
{
path: 'recurring-invoices',
name: 'recurring-invoices.index',
component: RecurringInvoiceIndexView,
meta: {
ability: 'view-recurring-invoice',
title: 'recurring_invoices.title',
},
redirect: '/admin/invoices?view=recurring',
},
{
path: 'recurring-invoices/create',
name: 'recurring-invoices.create',
component: RecurringInvoiceCreateView,
meta: {
ability: 'create-recurring-invoice',
title: 'recurring_invoices.new_invoice',
},
redirect: '/admin/invoices/create?recurring=1',
},
{
path: 'recurring-invoices/:id/edit',
name: 'recurring-invoices.edit',
component: RecurringInvoiceCreateView,
component: InvoiceCreateView,
meta: {
requiresAuth: true,
ability: 'edit-recurring-invoice',
title: 'recurring_invoices.edit_invoice',
},
@@ -40,6 +30,7 @@ export const recurringInvoiceRoutes: RouteRecordRaw[] = [
name: 'recurring-invoices.view',
component: RecurringInvoiceDetailView,
meta: {
requiresAuth: true,
ability: 'view-recurring-invoice',
title: 'recurring_invoices.title',
},

View File

@@ -1,4 +1,6 @@
import { defineStore } from 'pinia'
import { useNotificationStore } from '../../../stores/notification.store'
import { useCompanyStore } from '../../../stores/company.store'
import { recurringInvoiceService } from '../../../api/services/recurring-invoice.service'
import type {
RecurringInvoiceListParams,
@@ -19,6 +21,7 @@ import type {
DocumentTax,
DocumentItem,
} from '../../shared/document-form/use-document-calculations'
import { generateClientId } from '../../../utils'
// ----------------------------------------------------------------
// Frequency options
@@ -35,11 +38,11 @@ export interface FrequencyOption {
function createTaxStub(): DocumentTax {
return {
id: crypto.randomUUID(),
id: generateClientId(),
name: '',
tax_type_id: 0,
type: 'GENERAL',
amount: 0,
amount: null,
percent: null,
compound_tax: false,
calculation_type: null,
@@ -49,7 +52,7 @@ function createTaxStub(): DocumentTax {
function createRecurringInvoiceItemStub(): DocumentItem {
return {
id: crypto.randomUUID(),
id: generateClientId(),
item_id: null,
name: '',
description: null,
@@ -240,56 +243,21 @@ export const useRecurringInvoiceStore = defineStore('recurring-invoice', {
actions: {
initFrequencies(t: (key: string) => string): void {
this.frequencies = [
{
label: t('recurring_invoices.frequency.every_minute'),
value: '* * * * *',
},
{
label: t('recurring_invoices.frequency.every_30_minute'),
value: '*/30 * * * *',
},
{
label: t('recurring_invoices.frequency.every_hour'),
value: '0 * * * *',
},
{
label: t('recurring_invoices.frequency.every_2_hour'),
value: '0 */2 * * *',
},
{
label: t('recurring_invoices.frequency.every_day_at_midnight'),
value: '0 0 * * *',
},
{
label: t('recurring_invoices.frequency.every_week'),
value: '0 0 * * 0',
},
{
label: t(
'recurring_invoices.frequency.every_15_days_at_midnight',
),
value: '0 5 */15 * *',
},
{
label: t(
'recurring_invoices.frequency.on_the_first_day_of_every_month_at_midnight',
),
value: '0 0 1 * *',
},
{
label: t('recurring_invoices.frequency.every_6_month'),
value: '0 0 1 */6 *',
},
{
label: t(
'recurring_invoices.frequency.every_year_on_the_first_day_of_january_at_midnight',
),
value: '0 0 1 1 *',
},
{
label: t('recurring_invoices.frequency.custom'),
value: 'CUSTOM',
},
// Common business intervals
{ label: t('recurring_invoices.frequency.every_week'), value: '0 0 * * 0' },
{ label: t('recurring_invoices.frequency.every_2_weeks'), value: '0 0 */14 * *' },
{ label: t('recurring_invoices.frequency.every_month'), value: '0 0 1 * *' },
{ label: t('recurring_invoices.frequency.every_2_months'), value: '0 0 1 */2 *' },
{ label: t('recurring_invoices.frequency.every_quarter'), value: '0 0 1 */3 *' },
{ label: t('recurring_invoices.frequency.every_6_month'), value: '0 0 1 */6 *' },
{ label: t('recurring_invoices.frequency.every_year'), value: '0 0 1 1 *' },
// Less common intervals
{ label: t('recurring_invoices.frequency.every_day'), value: '0 0 * * *' },
{ label: t('recurring_invoices.frequency.every_15_days_at_midnight'), value: '0 5 */15 * *' },
{ label: t('recurring_invoices.frequency.every_hour'), value: '0 * * * *' },
{ label: t('recurring_invoices.frequency.every_minute'), value: '* * * * *' },
// Custom cron expression
{ label: t('recurring_invoices.frequency.custom'), value: 'CUSTOM' },
]
},
@@ -400,6 +368,13 @@ export const useRecurringInvoiceStore = defineStore('recurring-invoice', {
...this.recurringInvoices,
response.data,
]
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'recurring_invoices.created_message',
})
return { data: response }
},
@@ -416,6 +391,13 @@ export const useRecurringInvoiceStore = defineStore('recurring-invoice', {
if (pos !== -1) {
this.recurringInvoices[pos] = response.data
}
const notificationStore = useNotificationStore()
notificationStore.showNotification({
type: 'success',
message: 'recurring_invoices.updated_message',
})
return { data: response }
},
@@ -502,13 +484,16 @@ export const useRecurringInvoiceStore = defineStore('recurring-invoice', {
async fetchRecurringInvoiceInitialSettings(
isEdit: boolean,
routeParams?: { id?: string; query?: Record<string, string> },
companySettings?: Record<string, string>,
companySettingsParam?: Record<string, string>,
companyCurrency?: Currency,
): Promise<void> {
this.isFetchingInitialSettings = true
if (companyCurrency) {
this.newRecurringInvoice.currency = companyCurrency
const companyStore = useCompanyStore()
const companySettings = companySettingsParam ?? companyStore.selectedCompanySettings
if (companyCurrency || companyStore.selectedCompanyCurrency) {
this.newRecurringInvoice.currency = companyCurrency ?? companyStore.selectedCompanyCurrency!
}
if (routeParams?.query?.customer) {

View File

@@ -48,6 +48,7 @@
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import cloneDeep from 'lodash/cloneDeep'
import { useRecurringInvoiceStore } from '../store'
import RecurringInvoiceBasicFields from '../components/RecurringInvoiceBasicFields.vue'
@@ -99,7 +100,7 @@ async function submitForm(): Promise<void> {
isSaving.value = true
const data: Record<string, unknown> = {
...recurringInvoiceStore.newRecurringInvoice,
...cloneDeep(recurringInvoiceStore.newRecurringInvoice),
sub_total: recurringInvoiceStore.getSubTotal,
total: recurringInvoiceStore.getTotal,
tax: recurringInvoiceStore.getTotalTax,

View File

@@ -1,5 +1,5 @@
<template>
<BasePage class="xl:pl-96 xl:ml-8">
<BasePage class="xl:pl-96">
<BasePageHeader :title="pageTitle">
<template #actions>
<RecurringInvoiceDropdown
@@ -12,86 +12,266 @@
</template>
</BasePageHeader>
<!-- Content loaded from partials / child components would go here -->
<div class="mt-8">
<!-- LEFT SIDEBAR (fixed) -->
<div
class="fixed top-0 left-0 hidden h-full pt-16 pb-[6.4rem] ml-56 bg-surface xl:ml-64 w-88 xl:block"
>
<div
v-if="recurringInvoiceStore.isFetchingViewData"
class="flex justify-center p-12"
class="flex items-center justify-between px-4 pt-8 pb-2 border border-line-default border-solid height-full"
>
<LoadingIcon class="h-8 animate-spin text-primary-400" />
</div>
<div class="mb-6">
<BaseInput
v-model="searchData.searchText"
:placeholder="$t('general.search')"
type="text"
variant="gray"
@input="onSearched()"
>
<template #right>
<BaseIcon name="MagnifyingGlassIcon" class="h-5 text-subtle" />
</template>
</BaseInput>
</div>
<div v-else>
<!-- Invoice details info would be rendered here -->
<div class="bg-surface rounded-xl border border-line-default p-6">
<div class="grid grid-cols-2 gap-4 text-sm">
<div>
<span class="text-muted">{{ $t('recurring_invoices.starts_at') }}:</span>
<span class="ml-2 text-heading">
{{ recurringInvoiceStore.newRecurringInvoice.starts_at }}
</span>
<div class="flex mb-6 ml-3" role="group" aria-label="First group">
<BaseDropdown class="ml-3" position="bottom-start">
<template #activator>
<BaseButton size="md" variant="gray">
<BaseIcon name="FunnelIcon" class="h-5" />
</BaseButton>
</template>
<div
class="px-2 py-1 pb-2 mb-1 mb-2 text-sm border-b border-line-default border-solid"
>
{{ $t('general.sort_by') }}
</div>
<div>
<span class="text-muted">{{ $t('recurring_invoices.next_invoice_date') }}:</span>
<span class="ml-2 text-heading">
{{ recurringInvoiceStore.newRecurringInvoice.next_invoice_at }}
</span>
</div>
<div>
<span class="text-muted">{{ $t('recurring_invoices.frequency.title') }}:</span>
<span class="ml-2 text-heading">
{{ recurringInvoiceStore.newRecurringInvoice.frequency }}
</span>
</div>
<div>
<span class="text-muted">{{ $t('recurring_invoices.status') }}:</span>
<span class="ml-2">
<BaseRecurringInvoiceStatusBadge
:status="recurringInvoiceStore.newRecurringInvoice.status"
class="px-2 py-0.5"
>
{{ recurringInvoiceStore.newRecurringInvoice.status }}
</BaseRecurringInvoiceStatusBadge>
</span>
</div>
<div>
<span class="text-muted">{{ $t('recurring_invoices.limit_by') }}:</span>
<span class="ml-2 text-heading">
{{ recurringInvoiceStore.newRecurringInvoice.limit_by }}
</span>
</div>
<div v-if="recurringInvoiceStore.newRecurringInvoice.limit_by === 'COUNT'">
<span class="text-muted">{{ $t('recurring_invoices.count') }}:</span>
<span class="ml-2 text-heading">
{{ recurringInvoiceStore.newRecurringInvoice.limit_count }}
</span>
</div>
<div v-if="recurringInvoiceStore.newRecurringInvoice.limit_by === 'DATE'">
<span class="text-muted">{{ $t('recurring_invoices.limit_date') }}:</span>
<span class="ml-2 text-heading">
{{ recurringInvoiceStore.newRecurringInvoice.limit_date }}
</span>
</div>
<div>
<span class="text-muted">{{ $t('recurring_invoices.send_automatically') }}:</span>
<span class="ml-2 text-heading">
{{ recurringInvoiceStore.newRecurringInvoice.send_automatically ? $t('general.yes') : $t('general.no') }}
</span>
</div>
</div>
<BaseDropdownItem class="flex px-1 py-2 cursor-pointer">
<BaseInputGroup class="-mt-3 font-normal">
<BaseRadio
id="filter_next_invoice_date"
v-model="searchData.orderByField"
:label="$t('recurring_invoices.next_invoice_date')"
size="sm"
name="filter"
value="next_invoice_at"
@update:model-value="onSearched"
/>
</BaseInputGroup>
</BaseDropdownItem>
<BaseDropdownItem class="flex px-1 py-2 cursor-pointer">
<BaseInputGroup class="-mt-3 font-normal">
<BaseRadio
id="filter_start_date"
v-model="searchData.orderByField"
:label="$t('recurring_invoices.starts_at')"
value="starts_at"
size="sm"
name="filter"
@update:model-value="onSearched"
/>
</BaseInputGroup>
</BaseDropdownItem>
</BaseDropdown>
<BaseButton class="ml-1" size="md" variant="gray" @click="sortData">
<BaseIcon v-if="getOrderBy" name="BarsArrowUpIcon" class="h-5" />
<BaseIcon v-else name="BarsArrowDownIcon" class="h-5" />
</BaseButton>
</div>
</div>
<div
ref="invoiceListSection"
class="h-full overflow-y-scroll border-l border-line-default border-solid base-scroll"
>
<div v-for="(invoice, index) in invoiceList" :key="index">
<router-link
v-if="invoice"
:id="'recurring-invoice-' + invoice.id"
:to="`/admin/recurring-invoices/${invoice.id}/view`"
:class="[
'flex justify-between side-invoice p-4 cursor-pointer hover:bg-hover-strong items-center border-l-4 border-l-transparent',
{
'bg-surface-tertiary border-l-4 border-l-primary-500 border-solid':
hasActiveUrl(invoice.id),
},
]"
style="border-bottom: 1px solid rgba(185, 193, 209, 0.41)"
>
<div class="flex-2">
<BaseText
:text="invoice.customer?.name ?? ''"
class="pr-2 mb-2 text-sm not-italic font-normal leading-5 text-heading capitalize truncate"
/>
<div
class="mt-1 mb-2 text-xs not-italic font-medium leading-5 text-body"
>
{{ invoice.invoice_number }}
</div>
<BaseRecurringInvoiceStatusBadge
:status="invoice.status"
class="px-1 text-xs"
>
<BaseRecurringInvoiceStatusLabel :status="invoice.status" />
</BaseRecurringInvoiceStatusBadge>
</div>
<div class="flex-1 whitespace-nowrap right">
<BaseFormatMoney
class="block mb-2 text-xl not-italic font-semibold leading-8 text-right text-heading"
:amount="invoice.total"
:currency="invoice.customer?.currency"
/>
<div
class="text-sm not-italic font-normal leading-5 text-right text-body est-date"
>
{{ invoice.formatted_starts_at }}
</div>
</div>
</router-link>
</div>
<div v-if="isSidebarLoading" class="flex justify-center p-4 items-center">
<LoadingIcon class="h-6 m-1 animate-spin text-primary-400" />
</div>
<p
v-if="!invoiceList?.length && !isSidebarLoading"
class="flex justify-center px-4 mt-5 text-sm text-body"
>
{{ $t('invoices.no_matching_invoices') }}
</p>
</div>
</div>
<!-- MAIN CONTENT -->
<div
v-if="recurringInvoiceStore.isFetchingViewData"
class="flex justify-center p-12"
>
<LoadingIcon class="h-8 animate-spin text-primary-400" />
</div>
<BaseCard v-else class="mt-10">
<BaseHeading>
{{ $t('customers.basic_info') }}
</BaseHeading>
<BaseDescriptionList class="mt-5">
<BaseDescriptionListItem
:label="$t('recurring_invoices.starts_at')"
:content-loading="recurringInvoiceStore.isFetchingViewData"
:value="recurringInvoiceStore.newRecurringInvoice?.formatted_starts_at"
/>
<BaseDescriptionListItem
:label="$t('recurring_invoices.next_invoice_date')"
:content-loading="recurringInvoiceStore.isFetchingViewData"
:value="recurringInvoiceStore.newRecurringInvoice?.formatted_next_invoice_at"
/>
<BaseDescriptionListItem
v-if="selectedFrequencyLabel"
:label="$t('recurring_invoices.frequency.title')"
:value="selectedFrequencyLabel"
:content-loading="recurringInvoiceStore.isFetchingViewData"
/>
<BaseDescriptionListItem
v-if="
recurringInvoiceStore.newRecurringInvoice?.limit_by !== 'NONE'
"
:label="$t('recurring_invoices.limit_by')"
:content-loading="recurringInvoiceStore.isFetchingViewData"
:value="recurringInvoiceStore.newRecurringInvoice?.limit_by"
/>
<BaseDescriptionListItem
v-if="
recurringInvoiceStore.newRecurringInvoice?.limit_date &&
recurringInvoiceStore.newRecurringInvoice?.limit_by !== 'NONE'
"
:label="$t('recurring_invoices.limit_date')"
:content-loading="recurringInvoiceStore.isFetchingViewData"
:value="recurringInvoiceStore.newRecurringInvoice?.limit_date"
/>
<BaseDescriptionListItem
v-if="recurringInvoiceStore.newRecurringInvoice?.limit_by === 'COUNT'"
:label="$t('recurring_invoices.limit_count')"
:value="recurringInvoiceStore.newRecurringInvoice?.limit_count"
:content-loading="recurringInvoiceStore.isFetchingViewData"
/>
<BaseDescriptionListItem
:label="$t('recurring_invoices.send_automatically')"
:content-loading="recurringInvoiceStore.isFetchingViewData"
:value="
recurringInvoiceStore.newRecurringInvoice?.send_automatically
? $t('general.yes')
: $t('general.no')
"
/>
</BaseDescriptionList>
<BaseHeading class="mt-8">
{{ $t('invoices.title', 2) }}
</BaseHeading>
<div class="relative table-container">
<BaseTable
:data="recurringInvoiceStore.newRecurringInvoice.invoices"
:columns="invoiceColumns"
:loading="recurringInvoiceStore.isFetchingViewData"
:placeholder-count="5"
class="mt-5"
>
<!-- Invoice date -->
<template #cell-invoice_date="{ row }">
{{ row.data.formatted_invoice_date }}
</template>
<!-- Invoice Number -->
<template #cell-invoice_number="{ row }">
<router-link
:to="{ path: `/admin/invoices/${row.data.id}/view` }"
class="font-medium text-primary-500"
>
{{ row.data.invoice_number }}
</router-link>
</template>
<!-- Invoice total -->
<template #cell-total="{ row }">
<BaseFormatMoney
:amount="row.data.due_amount"
:currency="row.data.currency"
/>
</template>
<!-- Invoice status -->
<template #cell-status="{ row }">
<BaseInvoiceStatusBadge :status="row.data.status" class="px-3 py-1">
<BaseInvoiceStatusLabel :status="row.data.status" />
</BaseInvoiceStatusBadge>
</template>
</BaseTable>
</div>
</BaseCard>
</BasePage>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { computed, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useRecurringInvoiceStore } from '../store'
import RecurringInvoiceDropdown from '../components/RecurringInvoiceDropdown.vue'
import LoadingIcon from '@v2/components/icons/LoadingIcon.vue'
import { useUserStore } from '../../../../stores/user.store'
import type { RecurringInvoice } from '../../../../types/domain/recurring-invoice'
interface Props {
canEdit?: boolean
@@ -105,23 +285,229 @@ const props = withDefaults(defineProps<Props>(), {
canDelete: false,
})
const ABILITIES = {
EDIT: 'edit-recurring-invoice',
VIEW: 'view-recurring-invoice',
DELETE: 'delete-recurring-invoice',
} as const
const recurringInvoiceStore = useRecurringInvoiceStore()
const userStore = useUserStore()
const { t } = useI18n()
const route = useRoute()
// ---------------------------------------------------------------------------
// Ability checks
// ---------------------------------------------------------------------------
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const hasAtLeastOneAbility = computed<boolean>(() => {
return canDelete.value || canEdit.value
})
// ---------------------------------------------------------------------------
// Page title
// ---------------------------------------------------------------------------
const pageTitle = computed<string>(() => {
return recurringInvoiceStore.newRecurringInvoice?.customer?.name ?? ''
})
const hasAtLeastOneAbility = computed<boolean>(() => {
return props.canDelete || props.canEdit
// ---------------------------------------------------------------------------
// Frequency label
// ---------------------------------------------------------------------------
const selectedFrequencyLabel = computed<string>(() => {
const inv = recurringInvoiceStore.newRecurringInvoice
if (inv?.selectedFrequency?.label) {
return inv.selectedFrequency.label
}
return inv?.frequency ?? ''
})
// Initialize frequencies
recurringInvoiceStore.initFrequencies(t)
// ---------------------------------------------------------------------------
// Invoices table columns
// ---------------------------------------------------------------------------
// Load the recurring invoice
if (route.params.id) {
recurringInvoiceStore.fetchRecurringInvoice(Number(route.params.id))
const invoiceColumns = computed(() => {
return [
{
key: 'invoice_date',
label: t('invoices.date'),
thClass: 'extra',
tdClass: 'font-medium text-heading',
},
{ key: 'invoice_number', label: t('invoices.invoice') },
{ key: 'customer.name', label: t('invoices.customer') },
{ key: 'status', label: t('invoices.status') },
{ key: 'total', label: t('invoices.total') },
]
})
// ---------------------------------------------------------------------------
// Sidebar state
// ---------------------------------------------------------------------------
const isSidebarLoading = ref<boolean>(false)
const invoiceList = ref<RecurringInvoice[] | null>(null)
const currentPageNumber = ref<number>(1)
const lastPageNumber = ref<number>(1)
const invoiceListSection = ref<HTMLElement | null>(null)
interface SearchData {
orderBy: string | null
orderByField: string | null
searchText: string | null
}
const searchData = reactive<SearchData>({
orderBy: null,
orderByField: null,
searchText: null,
})
const getOrderBy = computed<boolean>(() => {
return searchData.orderBy === 'asc' || searchData.orderBy === null
})
function hasActiveUrl(id: number): boolean {
return Number(route.params.id) === id
}
// ---------------------------------------------------------------------------
// Sidebar data loading
// ---------------------------------------------------------------------------
async function loadRecurringInvoices(
pageNumber?: number,
fromScrollListener = false,
): Promise<void> {
if (isSidebarLoading.value) return
const params: Record<string, unknown> = {}
if (searchData.searchText) {
params.search = searchData.searchText
}
if (searchData.orderBy != null) {
params.orderBy = searchData.orderBy
}
if (searchData.orderByField != null) {
params.orderByField = searchData.orderByField
}
isSidebarLoading.value = true
const response = await recurringInvoiceStore.fetchRecurringInvoices({
page: pageNumber,
...params,
} as never)
isSidebarLoading.value = false
invoiceList.value = invoiceList.value ?? []
invoiceList.value = [...invoiceList.value, ...response.data.data]
currentPageNumber.value = pageNumber ?? 1
lastPageNumber.value = response.data.meta.last_page
const invoiceFound = invoiceList.value.find(
(inv) => inv.id === Number(route.params.id),
)
if (
!fromScrollListener &&
!invoiceFound &&
currentPageNumber.value < lastPageNumber.value &&
Object.keys(params).length === 0
) {
loadRecurringInvoices(++currentPageNumber.value)
}
if (invoiceFound && !fromScrollListener) {
setTimeout(() => scrollToRecurringInvoice(), 500)
}
}
function scrollToRecurringInvoice(): void {
const el = document.getElementById(`recurring-invoice-${route.params.id}`)
if (el) {
el.scrollIntoView({ behavior: 'smooth' })
el.classList.add('shake')
addScrollListener()
}
}
function addScrollListener(): void {
invoiceListSection.value?.addEventListener('scroll', (ev) => {
const target = ev.target as HTMLElement
if (
target.scrollTop > 0 &&
target.scrollTop + target.clientHeight > target.scrollHeight - 200
) {
if (currentPageNumber.value < lastPageNumber.value) {
loadRecurringInvoices(++currentPageNumber.value, true)
}
}
})
}
let searchTimeout: ReturnType<typeof setTimeout> | null = null
function onSearched(): void {
if (searchTimeout) clearTimeout(searchTimeout)
searchTimeout = setTimeout(() => {
invoiceList.value = []
loadRecurringInvoices()
}, 500)
}
function sortData(): void {
if (searchData.orderBy === 'asc') {
searchData.orderBy = 'desc'
} else {
searchData.orderBy = 'asc'
}
onSearched()
}
// ---------------------------------------------------------------------------
// Main content loading
// ---------------------------------------------------------------------------
async function loadRecurringInvoice(): Promise<void> {
if (route.params.id) {
await recurringInvoiceStore.fetchRecurringInvoice(Number(route.params.id))
}
}
// ---------------------------------------------------------------------------
// Watch route changes to reload data
// ---------------------------------------------------------------------------
watch(
() => route.params.id,
(newId) => {
if (newId && route.name === 'recurring-invoices.view') {
loadRecurringInvoice()
}
},
)
// ---------------------------------------------------------------------------
// Initialize
// ---------------------------------------------------------------------------
recurringInvoiceStore.initFrequencies(t)
loadRecurringInvoices()
loadRecurringInvoice()
</script>

View File

@@ -107,10 +107,9 @@
<!-- Table -->
<div v-show="!showEmptyScreen" class="relative table-container">
<div
class="relative flex items-center justify-between h-10 mt-5 list-none border-b-2 border-line-default border-solid"
class="relative flex items-center justify-between mt-5 list-none"
>
<BaseTabGroup
class="-mb-5"
:default-index="currentStatusIndex"
@change="setStatusFilter"
>
@@ -149,7 +148,7 @@
:placeholder-count="
recurringInvoiceStore.totalRecurringInvoices >= 20 ? 10 : 5
"
class="mt-10"
class="mt-4"
>
<template #header>
<div class="absolute items-center left-6 top-2.5 select-none">
@@ -232,6 +231,8 @@ import { useI18n } from 'vue-i18n'
import { debouncedWatch } from '@vueuse/core'
import { useRecurringInvoiceStore } from '../store'
import RecurringInvoiceDropdown from '../components/RecurringInvoiceDropdown.vue'
import { useUserStore } from '../../../../stores/user.store'
import { useDialogStore } from '../../../../stores/dialog.store'
import type { RecurringInvoice } from '../../../../types/domain/recurring-invoice'
interface Props {
@@ -248,7 +249,16 @@ const props = withDefaults(defineProps<Props>(), {
canDelete: false,
})
const ABILITIES = {
CREATE: 'create-recurring-invoice',
EDIT: 'edit-recurring-invoice',
VIEW: 'view-recurring-invoice',
DELETE: 'delete-recurring-invoice',
} as const
const recurringInvoiceStore = useRecurringInvoiceStore()
const userStore = useUserStore()
const dialogStore = useDialogStore()
const { t } = useI18n()
// Initialize frequencies with translations
@@ -289,8 +299,24 @@ const showEmptyScreen = computed<boolean>(
!recurringInvoiceStore.totalRecurringInvoices && !isRequestOngoing.value,
)
const canCreate = computed<boolean>(() => {
return props.canCreate || userStore.hasAbilities(ABILITIES.CREATE)
})
const canEdit = computed<boolean>(() => {
return props.canEdit || userStore.hasAbilities(ABILITIES.EDIT)
})
const canView = computed<boolean>(() => {
return props.canView || userStore.hasAbilities(ABILITIES.VIEW)
})
const canDelete = computed<boolean>(() => {
return props.canDelete || userStore.hasAbilities(ABILITIES.DELETE)
})
const hasAtLeastOneAbility = computed<boolean>(() => {
return props.canDelete || props.canEdit || props.canView
return canDelete.value || canEdit.value || canView.value
})
const selectField = computed<number[]>({
@@ -461,17 +487,26 @@ function setActiveTab(val: string): void {
activeTab.value = tabMap[val] ?? t('general.all')
}
async function removeMultipleRecurringInvoices(): Promise<void> {
const confirmed = window.confirm(t('invoices.confirm_delete'))
if (!confirmed) return
const res = await recurringInvoiceStore.deleteMultipleRecurringInvoices()
if (res.data.success) {
refreshTable()
recurringInvoiceStore.$patch((state) => {
state.selectedRecurringInvoices = []
state.selectAllField = false
})
}
function removeMultipleRecurringInvoices(): void {
dialogStore.openDialog({
title: t('general.are_you_sure'),
message: t('invoices.confirm_delete'),
yesLabel: t('general.ok'),
noLabel: t('general.cancel'),
variant: 'danger',
hideNoButton: false,
size: 'lg',
}).then(async (res: boolean) => {
if (res) {
const response = await recurringInvoiceStore.deleteMultipleRecurringInvoices()
if (response.data.success) {
refreshTable()
recurringInvoiceStore.$patch((state) => {
state.selectedRecurringInvoices = []
state.selectAllField = false
})
}
}
})
}
</script>

View File

@@ -2,35 +2,12 @@ import type { RouteRecordRaw } from 'vue-router'
const reportRoutes: RouteRecordRaw[] = [
{
path: 'reports/sales',
name: 'reports.sales',
component: () => import('./views/SalesReportView.vue'),
path: 'reports',
name: 'reports',
component: () => import('./views/ReportsLayoutView.vue'),
meta: {
ability: 'view-financial-report',
},
},
{
path: 'reports/profit-loss',
name: 'reports.profit-loss',
component: () => import('./views/ProfitLossReportView.vue'),
meta: {
ability: 'view-financial-report',
},
},
{
path: 'reports/expenses',
name: 'reports.expenses',
component: () => import('./views/ExpensesReportView.vue'),
meta: {
ability: 'view-financial-report',
},
},
{
path: 'reports/taxes',
name: 'reports.taxes',
component: () => import('./views/TaxReportView.vue'),
meta: {
ability: 'view-financial-report',
requiresAuth: true,
ability: 'view-financial-reports',
},
},
]

View File

@@ -51,7 +51,7 @@ const dateRangeUrl = computed<string>(() => {
)}&to_date=${moment(formData.to_date).format('YYYY-MM-DD')}`
})
globalStore.downloadReport = downloadReport as unknown as string | null
globalStore.downloadReport = downloadReport
onMounted(() => {
siteURL.value = `/reports/expenses/${selectedCompany.value?.unique_hash}`
@@ -163,11 +163,14 @@ function downloadReport(): void {
</div>
<BaseButton
variant="primary-outline"
class="content-center hidden mt-0 w-md md:flex md:mt-8"
variant="primary"
class="hidden w-full mt-6 md:flex justify-center"
type="submit"
@click.prevent="getReports"
>
<template #left="slotProps">
<BaseIcon name="ArrowPathIcon" :class="slotProps.class" />
</template>
{{ $t('reports.update_report') }}
</BaseButton>
</div>

View File

@@ -51,7 +51,7 @@ const dateRangeUrl = computed<string>(() => {
)}&to_date=${moment(formData.to_date).format('YYYY-MM-DD')}`
})
globalStore.downloadReport = downloadReport as unknown as string | null
globalStore.downloadReport = downloadReport
onMounted(() => {
siteURL.value = `/reports/profit-loss/${selectedCompany.value?.unique_hash}`
@@ -163,11 +163,14 @@ function downloadReport(): void {
</div>
<BaseButton
variant="primary-outline"
class="content-center hidden mt-0 w-md md:flex md:mt-8"
variant="primary"
class="hidden w-full mt-6 md:flex justify-center"
type="submit"
@click.prevent="getReports"
>
<template #left="slotProps">
<BaseIcon name="ArrowPathIcon" :class="slotProps.class" />
</template>
{{ $t('reports.update_report') }}
</BaseButton>
</div>

View File

@@ -0,0 +1,72 @@
<script setup lang="ts">
import { useGlobalStore } from '../../../../stores/global.store'
import SalesReportView from './SalesReportView.vue'
import ProfitLossReportView from './ProfitLossReportView.vue'
import ExpensesReportView from './ExpensesReportView.vue'
import TaxReportView from './TaxReportView.vue'
const globalStore = useGlobalStore()
function onDownload(): void {
if (globalStore.downloadReport) {
globalStore.downloadReport()
}
}
</script>
<template>
<BasePage>
<BasePageHeader :title="$t('reports.report', 2)">
<BaseBreadcrumb>
<BaseBreadcrumbItem
:title="$t('general.home')"
to="/admin/dashboard"
/>
<BaseBreadcrumbItem
:title="$t('reports.report', 2)"
to="#"
active
/>
</BaseBreadcrumb>
<template #actions>
<BaseButton variant="primary" class="ml-4" @click="onDownload">
<template #left="slotProps">
<BaseIcon name="ArrowDownTrayIcon" :class="slotProps.class" />
</template>
{{ $t('reports.download_pdf') }}
</BaseButton>
</template>
</BasePageHeader>
<BaseTabGroup class="p-2">
<BaseTab
:title="$t('reports.sales.sales')"
tab-panel-container="px-0 py-0"
>
<SalesReportView />
</BaseTab>
<BaseTab
:title="$t('reports.profit_loss.profit_loss')"
tab-panel-container="px-0 py-0"
>
<ProfitLossReportView />
</BaseTab>
<BaseTab
:title="$t('reports.expenses.expenses')"
tab-panel-container="px-0 py-0"
>
<ExpensesReportView />
</BaseTab>
<BaseTab
:title="$t('reports.taxes.taxes')"
tab-panel-container="px-0 py-0"
>
<TaxReportView />
</BaseTab>
</BaseTabGroup>
</BasePage>
</template>

View File

@@ -68,7 +68,7 @@ const itemDateRangeUrl = computed<string>(() => {
)}&to_date=${moment(formData.to_date).format('YYYY-MM-DD')}`
})
globalStore.downloadReport = downloadReport as unknown as string | null
globalStore.downloadReport = downloadReport
onMounted(() => {
customerSiteURL.value = `/reports/sales/customers/${selectedCompany.value?.unique_hash}`
@@ -211,11 +211,14 @@ function downloadReport(): void {
</BaseInputGroup>
<BaseButton
variant="primary-outline"
class="content-center hidden mt-0 w-md md:flex md:mt-8"
variant="primary"
class="hidden w-full mt-6 md:flex justify-center"
type="submit"
@click.prevent="getReports"
>
<template #left="slotProps">
<BaseIcon name="ArrowPathIcon" :class="slotProps.class" />
</template>
{{ $t('reports.update_report') }}
</BaseButton>
</div>

View File

@@ -51,7 +51,7 @@ const dateRangeUrl = computed<string>(() => {
)}&to_date=${moment(formData.to_date).format('YYYY-MM-DD')}`
})
globalStore.downloadReport = downloadReport as unknown as string | null
globalStore.downloadReport = downloadReport
onMounted(() => {
siteURL.value = `/reports/tax-summary/${selectedCompany.value?.unique_hash}`
@@ -163,11 +163,14 @@ function downloadReport(): void {
</div>
<BaseButton
variant="primary-outline"
class="content-center hidden mt-0 w-md md:flex md:mt-8"
variant="primary"
class="hidden w-full mt-6 md:flex justify-center"
type="submit"
@click.prevent="getReports"
>
<template #left="slotProps">
<BaseIcon name="ArrowPathIcon" :class="slotProps.class" />
</template>
{{ $t('reports.update_report') }}
</BaseButton>
</div>

View File

@@ -4,6 +4,7 @@ import { useI18n } from 'vue-i18n'
import { required, minLength, maxLength, helpers } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import { useModalStore } from '@v2/stores/modal.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { expenseService } from '@v2/api/services/expense.service'
interface CategoryForm {
@@ -13,6 +14,7 @@ interface CategoryForm {
}
const modalStore = useModalStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const isSaving = ref<boolean>(false)
@@ -77,11 +79,19 @@ async function submitCategoryData(): Promise<void> {
name: currentCategory.value.name,
description: currentCategory.value.description || null,
})
notificationStore.showNotification({
type: 'success',
message: 'settings.expense_category.updated_message',
})
} else {
await expenseService.createCategory({
name: currentCategory.value.name,
description: currentCategory.value.description || null,
})
notificationStore.showNotification({
type: 'success',
message: 'settings.expense_category.created_message',
})
}
isSaving.value = false

View File

@@ -0,0 +1,260 @@
<script setup lang="ts">
import { computed, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { required, minLength, helpers } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { useModalStore } from '@v2/stores/modal.store'
import { useCompanyStore } from '@v2/stores/company.store'
import { useGlobalStore } from '@v2/stores/global.store'
const router = useRouter()
const modalStore = useModalStore()
const companyStore = useCompanyStore()
const globalStore = useGlobalStore()
const { t } = useI18n()
const isSaving = ref<boolean>(false)
const isFetchingInitialData = ref<boolean>(false)
const previewLogo = ref<string | null>(null)
const companyLogoFileBlob = ref<string | null>(null)
const companyLogoName = ref<string | null>(null)
const newCompanyForm = reactive<{
name: string
currency: string | number
address: { country_id: number | null }
}>({
name: '',
currency: '',
address: {
country_id: null,
},
})
const modalActive = computed<boolean>(
() => modalStore.active && modalStore.componentName === 'CompanyModal',
)
const rules = computed(() => ({
newCompanyForm: {
name: {
required: helpers.withMessage(t('validation.required'), required),
minLength: helpers.withMessage(
t('validation.name_min_length', { count: 3 }),
minLength(3),
),
},
address: {
country_id: {
required: helpers.withMessage(t('validation.required'), required),
},
},
currency: {
required: helpers.withMessage(t('validation.required'), required),
},
},
}))
const v$ = useVuelidate(rules, { newCompanyForm })
async function getInitials(): Promise<void> {
isFetchingInitialData.value = true
await globalStore.fetchCurrencies()
await globalStore.fetchCountries()
newCompanyForm.currency = companyStore.selectedCompanyCurrency?.id ?? ''
newCompanyForm.address.country_id =
(companyStore.selectedCompany as Record<string, unknown>)?.address
? ((companyStore.selectedCompany as Record<string, unknown>).address as Record<string, unknown>)?.country_id as number | null
: null
isFetchingInitialData.value = false
}
function onFileInputChange(fileName: string, file: string): void {
companyLogoName.value = fileName
companyLogoFileBlob.value = file
}
function onFileInputRemove(): void {
companyLogoName.value = null
companyLogoFileBlob.value = null
}
async function submitCompanyData(): Promise<void> {
v$.value.newCompanyForm.$touch()
if (v$.value.$invalid) {
return
}
isSaving.value = true
try {
const res = await companyStore.addNewCompany(newCompanyForm as never)
if (res.data) {
companyStore.setSelectedCompany(res.data)
if (companyLogoFileBlob.value) {
const logoData = new FormData()
logoData.append(
'company_logo',
JSON.stringify({
name: companyLogoName.value,
data: companyLogoFileBlob.value,
}),
)
await companyStore.updateCompanyLogo(logoData)
}
globalStore.setIsAppLoaded(false)
await globalStore.bootstrap()
closeCompanyModal()
router.push('/admin/dashboard')
}
} finally {
isSaving.value = false
}
}
function resetNewCompanyForm(): void {
newCompanyForm.name = ''
newCompanyForm.currency = ''
newCompanyForm.address.country_id = null
v$.value.$reset()
}
function closeCompanyModal(): void {
modalStore.closeModal()
setTimeout(() => {
resetNewCompanyForm()
}, 300)
}
</script>
<template>
<BaseModal :show="modalActive" @close="closeCompanyModal" @open="getInitials">
<template #header>
<div class="flex justify-between w-full">
{{ modalStore.title }}
<BaseIcon
name="XMarkIcon"
class="w-6 h-6 text-muted cursor-pointer"
@click="closeCompanyModal"
/>
</div>
</template>
<form action="" @submit.prevent="submitCompanyData">
<div class="p-4 mb-16 sm:p-6 space-y-4">
<BaseInputGrid layout="one-column">
<BaseInputGroup
:content-loading="isFetchingInitialData"
:label="$t('settings.company_info.company_logo')"
>
<BaseContentPlaceholders v-if="isFetchingInitialData">
<BaseContentPlaceholdersBox :rounded="true" class="w-full h-24" />
</BaseContentPlaceholders>
<div v-else class="flex flex-col items-center">
<BaseFileUploader
:preview-image="previewLogo"
base64
@remove="onFileInputRemove"
@change="onFileInputChange"
/>
</div>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.company_info.company_name')"
:error="
v$.newCompanyForm.name.$error &&
v$.newCompanyForm.name.$errors[0].$message
"
:content-loading="isFetchingInitialData"
required
>
<BaseInput
v-model="newCompanyForm.name"
:invalid="v$.newCompanyForm.name.$error"
:content-loading="isFetchingInitialData"
@input="v$.newCompanyForm.name.$touch()"
/>
</BaseInputGroup>
<BaseInputGroup
:content-loading="isFetchingInitialData"
:label="$t('settings.company_info.country')"
:error="
v$.newCompanyForm.address.country_id.$error &&
v$.newCompanyForm.address.country_id.$errors[0].$message
"
required
>
<BaseMultiselect
v-model="newCompanyForm.address.country_id"
:content-loading="isFetchingInitialData"
label="name"
:invalid="v$.newCompanyForm.address.country_id.$error"
:options="globalStore.countries"
value-prop="id"
:can-deselect="true"
:can-clear="false"
searchable
track-by="name"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('wizard.currency')"
:error="
v$.newCompanyForm.currency.$error &&
v$.newCompanyForm.currency.$errors[0].$message
"
:content-loading="isFetchingInitialData"
:help-text="$t('wizard.currency_set_alert')"
required
>
<BaseMultiselect
v-model="newCompanyForm.currency"
:content-loading="isFetchingInitialData"
:options="globalStore.currencies"
label="name"
value-prop="id"
:searchable="true"
track-by="name"
:placeholder="$t('settings.currencies.select_currency')"
:invalid="v$.newCompanyForm.currency.$error"
class="w-full"
/>
</BaseInputGroup>
</BaseInputGrid>
</div>
<div class="z-0 flex justify-end p-4 bg-surface-secondary border-t border-line-default">
<BaseButton
class="mr-3 text-sm"
variant="primary-outline"
type="button"
@click="closeCompanyModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
>
<template #left="slotProps">
<BaseIcon
v-if="!isSaving"
name="ArrowDownOnSquareIcon"
:class="slotProps.class"
/>
</template>
{{ $t('general.save') }}
</BaseButton>
</div>
</form>
</BaseModal>
</template>

View File

@@ -4,6 +4,7 @@ import { useI18n } from 'vue-i18n'
import useVuelidate from '@vuelidate/core'
import { required, numeric, helpers } from '@vuelidate/validators'
import { useModalStore } from '@v2/stores/modal.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { customFieldService } from '@v2/api/services/custom-field.service'
import type { CreateCustomFieldPayload } from '@v2/api/services/custom-field.service'
@@ -32,6 +33,7 @@ interface CustomFieldForm {
}
const modalStore = useModalStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const isSaving = ref<boolean>(false)
@@ -178,6 +180,13 @@ async function submitCustomFieldData(): Promise<void> {
isSaving.value = true
let defaultAnswer = currentCustomField.value.default_answer
// Handle Time type — convert object {HH, mm, ss} to 'HH:mm' string
if (currentCustomField.value.type === 'Time' && typeof defaultAnswer === 'object' && defaultAnswer !== null) {
const timeObj = defaultAnswer as Record<string, string>
defaultAnswer = `${timeObj.HH ?? '00'}:${timeObj.mm ?? '00'}`
}
const payload: CreateCustomFieldPayload = {
name: currentCustomField.value.name,
label: currentCustomField.value.label,
@@ -189,13 +198,22 @@ async function submitCustomFieldData(): Promise<void> {
? currentCustomField.value.options.map((o) => o.name)
: null,
order: currentCustomField.value.order,
default_answer: defaultAnswer as string ?? null,
}
try {
if (isEdit.value && currentCustomField.value.id) {
await customFieldService.update(currentCustomField.value.id, payload)
notificationStore.showNotification({
type: 'success',
message: 'settings.custom_fields.updated_message',
})
} else {
await customFieldService.create(payload)
notificationStore.showNotification({
type: 'success',
message: 'settings.custom_fields.created_message',
})
}
isSaving.value = false
@@ -208,6 +226,17 @@ async function submitCustomFieldData(): Promise<void> {
}
}
const newOptionValue = ref<string>('')
function onAddOption(): void {
if (!newOptionValue.value?.trim()) return
currentCustomField.value.options = [
{ name: newOptionValue.value.trim() },
...currentCustomField.value.options,
]
newOptionValue.value = ''
}
function addNewOption(option: string): void {
currentCustomField.value.options = [
{ name: option },
@@ -357,6 +386,22 @@ function closeCustomFieldModal(): void {
v-if="isDropdownSelected"
:label="$t('settings.custom_fields.options')"
>
<!-- Add Option Input -->
<div class="flex items-center mt-1">
<BaseInput
v-model="newOptionValue"
type="text"
class="w-full md:w-96"
:placeholder="$t('settings.custom_fields.press_enter_to_add')"
@keydown.enter.prevent.stop="onAddOption"
/>
<BaseIcon
name="PlusCircleIcon"
class="ml-1 text-primary-500 cursor-pointer"
@click="onAddOption"
/>
</div>
<div
v-for="(option, index) in currentCustomField.options"
:key="index"

View File

@@ -0,0 +1,139 @@
<script setup lang="ts">
import { computed, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { required, helpers, sameAs } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { useModalStore } from '@v2/stores/modal.store'
import { useCompanyStore } from '@v2/stores/company.store'
import { useGlobalStore } from '@v2/stores/global.store'
const companyStore = useCompanyStore()
const modalStore = useModalStore()
const globalStore = useGlobalStore()
const router = useRouter()
const { t } = useI18n()
const isDeleting = ref<boolean>(false)
const formData = reactive<{ id: number | null; name: string }>({
id: null,
name: '',
})
const modalActive = computed<boolean>(
() => modalStore.active && modalStore.componentName === 'DeleteCompanyModal',
)
const companyName = computed<string>(
() => companyStore.selectedCompany?.name ?? '',
)
const rules = computed(() => ({
name: {
required: helpers.withMessage(t('validation.required'), required),
sameAsName: helpers.withMessage(
t('validation.company_name_not_same'),
sameAs(companyName.value),
),
},
}))
const v$ = useVuelidate(rules, formData)
function setInitialData(): void {
formData.id = companyStore.selectedCompany?.id ?? null
formData.name = ''
}
async function submitDelete(): Promise<void> {
v$.value.$touch()
if (v$.value.$invalid) return
isDeleting.value = true
try {
await companyStore.deleteCompany(formData)
closeModal()
const remaining = companyStore.companies.filter(
(c) => c.id !== formData.id,
)
if (remaining.length) {
companyStore.setSelectedCompany(remaining[0])
}
router.push('/admin/dashboard')
globalStore.setIsAppLoaded(false)
await globalStore.bootstrap()
} catch {
// Error handled
} finally {
isDeleting.value = false
}
}
function closeModal(): void {
modalStore.closeModal()
setTimeout(() => {
formData.id = null
formData.name = ''
v$.value.$reset()
}, 300)
}
</script>
<template>
<BaseModal :show="modalActive" @close="closeModal" @open="setInitialData">
<div class="px-6 pt-6">
<h6 class="font-medium text-lg text-heading">
{{ $t('settings.company_info.are_you_absolutely_sure') }}
</h6>
<p class="mt-2 text-sm text-muted" style="max-width: 680px">
{{ $t('settings.company_info.delete_company_modal_desc', { company: companyName }) }}
</p>
</div>
<form @submit.prevent="submitDelete">
<div class="p-4 sm:p-6 space-y-4">
<BaseInputGroup
:label="$t('settings.company_info.delete_company_modal_label', { company: companyName })"
:error="v$.name.$error ? String(v$.name.$errors[0]?.$message) : undefined"
required
>
<BaseInput
v-model="formData.name"
:invalid="v$.name.$error"
@input="v$.name.$touch()"
/>
</BaseInputGroup>
</div>
<div class="z-0 flex justify-end p-4 bg-surface-secondary border-t border-line-default">
<BaseButton
class="mr-3 text-sm"
variant="primary-outline"
type="button"
@click="closeModal"
>
{{ $t('general.cancel') }}
</BaseButton>
<BaseButton
:loading="isDeleting"
:disabled="isDeleting"
variant="danger"
type="submit"
>
<template #left="slotProps">
<BaseIcon
v-if="!isDeleting"
name="TrashIcon"
:class="slotProps.class"
/>
</template>
{{ $t('general.delete') }}
</BaseButton>
</div>
</form>
</BaseModal>
</template>

View File

@@ -1,7 +1,11 @@
<script setup lang="ts">
import { computed, reactive, inject } from 'vue'
import { useCompanyStore } from '@v2/stores/company.store'
import { useEstimateStore } from '@v2/features/company/estimates/store'
import NumberCustomizer from './NumberCustomizer.vue'
import EstimatesTabExpiryDate from './EstimatesTabExpiryDate.vue'
import EstimatesTabConvertEstimate from './EstimatesTabConvertEstimate.vue'
import EstimatesTabDefaultFormats from './EstimatesTabDefaultFormats.vue'
interface Utils {
mergeSettings: (target: Record<string, unknown>, source: Record<string, unknown>) => void
@@ -9,6 +13,7 @@ interface Utils {
const utils = inject<Utils>('utils')!
const companyStore = useCompanyStore()
const estimateStore = useEstimateStore()
const estimateSettings = reactive<{ estimate_email_attachment: string | null }>({
estimate_email_attachment: null,
@@ -41,8 +46,14 @@ const sendAsAttachmentField = computed<boolean>({
</script>
<template>
<NumberCustomizer type="estimate" :type-store="companyStore" />
<NumberCustomizer type="estimate" :type-store="estimateStore" />
<BaseDivider class="mt-6 mb-2" />
<EstimatesTabExpiryDate />
<BaseDivider class="mt-6 mb-2" />
<EstimatesTabConvertEstimate />
<BaseDivider class="mt-6 mb-2" />
<EstimatesTabDefaultFormats />
<BaseDivider class="mt-6 mb-2" />
<ul class="divide-y divide-line-default">

View File

@@ -0,0 +1,67 @@
<script setup lang="ts">
import { reactive, inject } from 'vue'
import { useCompanyStore } from '@v2/stores/company.store'
import { useGlobalStore } from '@v2/stores/global.store'
interface Utils {
mergeSettings: (target: Record<string, unknown>, source: Record<string, unknown>) => void
}
const companyStore = useCompanyStore()
const globalStore = useGlobalStore()
const utils = inject<Utils>('utils')!
const settingsForm = reactive<{ estimate_convert_action: string | null }>({
estimate_convert_action: null,
})
utils.mergeSettings(
settingsForm as unknown as Record<string, unknown>,
{ ...companyStore.selectedCompanySettings }
)
const convertEstimateOptions = [
{ key: 'settings.customization.estimates.no_action', value: 'no_action' },
{ key: 'settings.customization.estimates.delete_estimate', value: 'delete_estimate' },
{ key: 'settings.customization.estimates.mark_estimate_as_accepted', value: 'mark_estimate_as_accepted' },
]
async function submitForm() {
const data = {
settings: {
...settingsForm,
},
}
await companyStore.updateCompanySettings({
data,
message: 'settings.customization.estimates.estimate_settings_updated',
})
return true
}
</script>
<template>
<h6 class="text-heading text-lg font-medium">
{{ $t('settings.customization.estimates.convert_estimate_setting') }}
</h6>
<p class="mt-1 text-sm text-muted">
{{ $t('settings.customization.estimates.convert_estimate_description') }}
</p>
<BaseInputGroup required>
<BaseRadio
v-for="option in convertEstimateOptions"
:id="option.value"
:key="option.value"
v-model="settingsForm.estimate_convert_action"
:label="$t(option.key)"
size="sm"
name="estimate_convert_action"
:value="option.value"
class="mt-2"
@update:modelValue="submitForm"
/>
</BaseInputGroup>
</template>

View File

@@ -0,0 +1,120 @@
<script setup lang="ts">
import { ref, reactive, inject } from 'vue'
import { useCompanyStore } from '@v2/stores/company.store'
interface Utils {
mergeSettings: (target: Record<string, unknown>, source: Record<string, unknown>) => void
}
const companyStore = useCompanyStore()
const utils = inject<Utils>('utils')!
const estimateMailFields = ref(['customer', 'company', 'estimate'])
const companyFields = ref(['company'])
const shippingFields = ref(['shipping', 'customer'])
const billingFields = ref(['billing', 'customer'])
const isSaving = ref(false)
const formatSettings = reactive<{
estimate_mail_body: string | null
estimate_company_address_format: string | null
estimate_shipping_address_format: string | null
estimate_billing_address_format: string | null
}>({
estimate_mail_body: null,
estimate_company_address_format: null,
estimate_shipping_address_format: null,
estimate_billing_address_format: null,
})
utils.mergeSettings(
formatSettings as unknown as Record<string, unknown>,
{ ...companyStore.selectedCompanySettings }
)
async function submitForm() {
isSaving.value = true
const data = {
settings: {
...formatSettings,
},
}
await companyStore.updateCompanySettings({
data,
message: 'settings.customization.estimates.estimate_settings_updated',
})
isSaving.value = false
return true
}
</script>
<template>
<form @submit.prevent="submitForm">
<h6 class="text-heading text-lg font-medium">
{{ $t('settings.customization.estimates.default_formats') }}
</h6>
<p class="mt-1 text-sm text-muted mb-2">
{{ $t('settings.customization.estimates.default_formats_description') }}
</p>
<BaseInputGroup
:label="
$t('settings.customization.estimates.default_estimate_email_body')
"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="formatSettings.estimate_mail_body"
:fields="estimateMailFields"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.customization.estimates.company_address_format')"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="formatSettings.estimate_company_address_format"
:fields="companyFields"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.customization.estimates.shipping_address_format')"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="formatSettings.estimate_shipping_address_format"
:fields="shippingFields"
/>
</BaseInputGroup>
<BaseInputGroup
:label="$t('settings.customization.estimates.billing_address_format')"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="formatSettings.estimate_billing_address_format"
:fields="billingFields"
/>
</BaseInputGroup>
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
class="mt-4"
>
<template #left="slotProps">
<BaseIcon v-if="!isSaving" :class="slotProps.class" name="ArrowDownOnSquareIcon" />
</template>
{{ $t('settings.customization.save') }}
</BaseButton>
</form>
</template>

View File

@@ -0,0 +1,139 @@
<script setup lang="ts">
import { ref, computed, reactive, inject } from 'vue'
import { useI18n } from 'vue-i18n'
import { useCompanyStore } from '@v2/stores/company.store'
import { numeric, helpers, requiredIf } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
interface Utils {
mergeSettings: (target: Record<string, unknown>, source: Record<string, unknown>) => void
}
const { t } = useI18n()
const companyStore = useCompanyStore()
const utils = inject<Utils>('utils')!
const isSaving = ref(false)
const expiryDateSettings = reactive<{
estimate_set_expiry_date_automatically: string | null
estimate_expiry_date_days: string | null
}>({
estimate_set_expiry_date_automatically: null,
estimate_expiry_date_days: null,
})
utils.mergeSettings(
expiryDateSettings as unknown as Record<string, unknown>,
{ ...companyStore.selectedCompanySettings }
)
const expiryDateAutoField = computed<boolean>({
get: () => expiryDateSettings.estimate_set_expiry_date_automatically === 'YES',
set: (newValue: boolean) => {
const value = newValue ? 'YES' : 'NO'
expiryDateSettings.estimate_set_expiry_date_automatically = value
},
})
const rules = computed(() => {
return {
expiryDateSettings: {
estimate_expiry_date_days: {
required: helpers.withMessage(
t('validation.required'),
requiredIf(expiryDateAutoField.value)
),
numeric: helpers.withMessage(t('validation.numbers_only'), numeric),
},
},
}
})
const v$ = useVuelidate(rules, { expiryDateSettings })
async function submitForm() {
v$.value.expiryDateSettings.$touch()
if (v$.value.expiryDateSettings.$invalid) {
return false
}
isSaving.value = true
const data = {
settings: {
...expiryDateSettings,
},
}
// Don't pass expiry_date_days if setting is not enabled
if (!expiryDateAutoField.value) {
delete data.settings.estimate_expiry_date_days
}
await companyStore.updateCompanySettings({
data,
message: 'settings.customization.estimates.estimate_settings_updated',
})
isSaving.value = false
return true
}
</script>
<template>
<form @submit.prevent="submitForm">
<h6 class="text-heading text-lg font-medium">
{{ $t('settings.customization.estimates.expiry_date_setting') }}
</h6>
<p class="mt-1 text-sm text-muted mb-2">
{{ $t('settings.customization.estimates.expiry_date_description') }}
</p>
<BaseSwitchSection
v-model="expiryDateAutoField"
:title="
$t('settings.customization.estimates.set_expiry_date_automatically')
"
:description="
$t(
'settings.customization.estimates.set_expiry_date_automatically_description'
)
"
/>
<BaseInputGroup
v-if="expiryDateAutoField"
:label="$t('settings.customization.estimates.expiry_date_days')"
:error="
v$.expiryDateSettings.estimate_expiry_date_days.$error &&
v$.expiryDateSettings.estimate_expiry_date_days.$errors[0].$message
"
class="mt-2 mb-4"
>
<div class="w-full sm:w-1/2 md:w-1/4 lg:w-1/5">
<BaseInput
v-model="expiryDateSettings.estimate_expiry_date_days"
:invalid="v$.expiryDateSettings.estimate_expiry_date_days.$error"
type="number"
@input="v$.expiryDateSettings.estimate_expiry_date_days.$touch()"
/>
</div>
</BaseInputGroup>
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
class="mt-4"
>
<template #left="slotProps">
<BaseIcon v-if="!isSaving" :class="slotProps.class" name="ArrowDownOnSquareIcon" />
</template>
{{ $t('settings.customization.save') }}
</BaseButton>
</form>
</template>

View File

@@ -4,6 +4,7 @@ import { useI18n } from 'vue-i18n'
import useVuelidate from '@vuelidate/core'
import { required, helpers, requiredIf, url } from '@vuelidate/validators'
import { useModalStore } from '@v2/stores/modal.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { exchangeRateService } from '@v2/api/services/exchange-rate.service'
import { useDebounceFn } from '@vueuse/core'
@@ -31,6 +32,7 @@ interface CurrencyConverterForm {
const { t } = useI18n()
const modalStore = useModalStore()
const notificationStore = useNotificationStore()
const isSaving = ref<boolean>(false)
const isFetchingInitialData = ref<boolean>(false)
@@ -243,10 +245,18 @@ async function submitExchangeRate(): Promise<void> {
currentExchangeRate.value.id,
data as Parameters<typeof exchangeRateService.updateProvider>[1]
)
notificationStore.showNotification({
type: 'success',
message: 'settings.exchange_rate.updated_message',
})
} else {
await exchangeRateService.createProvider(
data as Parameters<typeof exchangeRateService.createProvider>[0]
)
notificationStore.showNotification({
type: 'success',
message: 'settings.exchange_rate.created_message',
})
}
if (modalStore.refreshData) {

View File

@@ -4,6 +4,7 @@ import { useRoute } from 'vue-router'
import { useDialogStore } from '@v2/stores/dialog.store'
import { useUserStore } from '@v2/stores/user.store'
import { useModalStore } from '@v2/stores/modal.store'
import { useNotificationStore } from '@v2/stores/notification.store'
import { expenseService } from '@v2/api/services/expense.service'
const ABILITIES = {
@@ -24,6 +25,7 @@ const props = defineProps<{
}>()
const dialogStore = useDialogStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()
const route = useRoute()
const userStore = useUserStore()
@@ -54,6 +56,10 @@ function removeExpenseCategory(id: number): void {
if (res) {
const response = await expenseService.deleteCategory(id)
if (response.success) {
notificationStore.showNotification({
type: 'success',
message: 'settings.expense_category.deleted_message',
})
props.loadData?.()
}
}
@@ -65,7 +71,7 @@ function removeExpenseCategory(id: number): void {
<BaseDropdown>
<template #activator>
<BaseButton
v-if="route.name === 'expenseCategorys.view'"
v-if="route.name === 'settings.expense-categories'"
variant="primary"
>
<BaseIcon name="EllipsisHorizontalIcon" class="h-5 text-white" />

View File

@@ -1,7 +1,11 @@
<script setup lang="ts">
import { computed, reactive, inject } from 'vue'
import { useCompanyStore } from '@v2/stores/company.store'
import { useInvoiceStore } from '@v2/features/company/invoices/store'
import NumberCustomizer from './NumberCustomizer.vue'
import InvoicesTabDueDate from './InvoicesTabDueDate.vue'
import InvoicesTabRetrospective from './InvoicesTabRetrospective.vue'
import InvoicesTabDefaultFormats from './InvoicesTabDefaultFormats.vue'
interface Utils {
mergeSettings: (target: Record<string, unknown>, source: Record<string, unknown>) => void
@@ -9,6 +13,7 @@ interface Utils {
const utils = inject<Utils>('utils')!
const companyStore = useCompanyStore()
const invoiceStore = useInvoiceStore()
const invoiceSettings = reactive<{ invoice_email_attachment: string | null }>({
invoice_email_attachment: null,
@@ -41,7 +46,19 @@ const sendAsAttachmentField = computed<boolean>({
</script>
<template>
<NumberCustomizer type="invoice" :type-store="companyStore" />
<NumberCustomizer type="invoice" :type-store="invoiceStore" />
<BaseDivider class="mt-6 mb-2" />
<InvoicesTabDueDate />
<BaseDivider class="mt-6 mb-2" />
<InvoicesTabRetrospective />
<BaseDivider class="mt-6 mb-2" />
<InvoicesTabDefaultFormats />
<BaseDivider class="mt-6 mb-2" />

View File

@@ -0,0 +1,117 @@
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useCompanyStore } from '@v2/stores/company.store'
const companyStore = useCompanyStore()
const isSaving = ref<boolean>(false)
const settingsForm = reactive<{
invoice_mail_body: string
invoice_company_address_format: string
invoice_shipping_address_format: string
invoice_billing_address_format: string
}>({
invoice_mail_body:
companyStore.selectedCompanySettings.invoice_mail_body ?? '',
invoice_company_address_format:
companyStore.selectedCompanySettings.invoice_company_address_format ?? '',
invoice_shipping_address_format:
companyStore.selectedCompanySettings.invoice_shipping_address_format ?? '',
invoice_billing_address_format:
companyStore.selectedCompanySettings.invoice_billing_address_format ?? '',
})
async function submitForm(): Promise<void> {
isSaving.value = true
const data = {
settings: {
...settingsForm,
},
}
await companyStore.updateCompanySettings({
data,
message: 'settings.customization.invoices.invoice_settings_updated',
})
isSaving.value = false
}
</script>
<template>
<form @submit.prevent="submitForm">
<BaseSettingCard
:title="$t('settings.customization.invoices.default_formats')"
:description="
$t('settings.customization.invoices.default_formats_description')
"
>
<BaseInputGroup
:label="
$t('settings.customization.invoices.default_invoice_email_body')
"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="settingsForm.invoice_mail_body"
:fields="['customer', 'company', 'invoice']"
/>
</BaseInputGroup>
<BaseInputGroup
:label="
$t('settings.customization.invoices.company_address_format')
"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="settingsForm.invoice_company_address_format"
:fields="['company']"
/>
</BaseInputGroup>
<BaseInputGroup
:label="
$t('settings.customization.invoices.shipping_address_format')
"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="settingsForm.invoice_shipping_address_format"
:fields="['shipping', 'customer']"
/>
</BaseInputGroup>
<BaseInputGroup
:label="
$t('settings.customization.invoices.billing_address_format')
"
class="mt-6 mb-4"
>
<BaseCustomInput
v-model="settingsForm.invoice_billing_address_format"
:fields="['billing', 'customer']"
/>
</BaseInputGroup>
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
class="mt-4"
>
<template #left="slotProps">
<BaseIcon
v-if="!isSaving"
:class="slotProps.class"
name="ArrowDownOnSquareIcon"
/>
</template>
{{ $t('settings.customization.save') }}
</BaseButton>
</BaseSettingCard>
</form>
</template>

View File

@@ -0,0 +1,134 @@
<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { numeric, helpers, requiredIf } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'
import { useCompanyStore } from '@v2/stores/company.store'
const { t } = useI18n()
const companyStore = useCompanyStore()
const isSaving = ref<boolean>(false)
const dueDateSettings = reactive<{
invoice_set_due_date_automatically: string
invoice_due_date_days: string
}>({
invoice_set_due_date_automatically:
companyStore.selectedCompanySettings.invoice_set_due_date_automatically ??
'NO',
invoice_due_date_days:
companyStore.selectedCompanySettings.invoice_due_date_days ?? '',
})
const dueDateAutoField = computed<boolean>({
get: () => dueDateSettings.invoice_set_due_date_automatically === 'YES',
set: (newValue: boolean) => {
dueDateSettings.invoice_set_due_date_automatically = newValue
? 'YES'
: 'NO'
},
})
const rules = computed(() => ({
dueDateSettings: {
invoice_due_date_days: {
required: helpers.withMessage(
t('validation.required'),
requiredIf(dueDateAutoField.value)
),
numeric: helpers.withMessage(t('validation.numbers_only'), numeric),
},
},
}))
const v$ = useVuelidate(rules, { dueDateSettings })
async function submitForm(): Promise<void> {
v$.value.dueDateSettings.$touch()
if (v$.value.dueDateSettings.$invalid) {
return
}
isSaving.value = true
const data: { settings: Record<string, string> } = {
settings: {
invoice_set_due_date_automatically:
dueDateSettings.invoice_set_due_date_automatically,
},
}
if (dueDateAutoField.value) {
data.settings.invoice_due_date_days =
dueDateSettings.invoice_due_date_days
}
await companyStore.updateCompanySettings({
data,
message: 'settings.customization.invoices.invoice_settings_updated',
})
isSaving.value = false
}
</script>
<template>
<form @submit.prevent="submitForm">
<BaseSettingCard
:title="$t('settings.customization.invoices.due_date')"
:description="
$t('settings.customization.invoices.due_date_description')
"
>
<BaseSwitchSection
v-model="dueDateAutoField"
:title="
$t('settings.customization.invoices.set_due_date_automatically')
"
:description="
$t(
'settings.customization.invoices.set_due_date_automatically_description'
)
"
/>
<BaseInputGroup
v-if="dueDateAutoField"
:label="$t('settings.customization.invoices.due_date_days')"
:error="
v$.dueDateSettings.invoice_due_date_days.$error &&
v$.dueDateSettings.invoice_due_date_days.$errors[0].$message
"
class="mt-2 mb-4"
>
<div class="w-full sm:w-1/2 md:w-1/4 lg:w-1/5">
<BaseInput
v-model="dueDateSettings.invoice_due_date_days"
:invalid="v$.dueDateSettings.invoice_due_date_days.$error"
type="number"
@input="v$.dueDateSettings.invoice_due_date_days.$touch()"
/>
</div>
</BaseInputGroup>
<BaseButton
:loading="isSaving"
:disabled="isSaving"
variant="primary"
type="submit"
class="mt-4"
>
<template #left="slotProps">
<BaseIcon
v-if="!isSaving"
:class="slotProps.class"
name="ArrowDownOnSquareIcon"
/>
</template>
{{ $t('settings.customization.save') }}
</BaseButton>
</BaseSettingCard>
</form>
</template>

Some files were not shown because too many files have changed in this diff Show More