@innertia-solutions/innertia-nuxt 0.1.81 → 0.1.83
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -1
- package/components/Auth/PasskeyButton.vue +4 -2
- package/components/Auth/PasskeyInvite.vue +4 -2
- package/components/Auth/PasskeyManager.vue +10 -2
- package/components/Auth/PasskeySettings.vue +130 -0
- package/components/Files/DriveBrowser.vue +155 -0
- package/components/Files/DriveFolderField.vue +77 -0
- package/components/Files/DriveImport.vue +157 -0
- package/components/Files/ProviderOrigin.vue +70 -0
- package/components/Files/VersionHistory.vue +90 -0
- package/components/Files/__tests__/sfc-compile.test.ts +25 -0
- package/composables/useDriveBrowser/index.ts +72 -0
- package/composables/useDriveBrowser/internal/__tests__/browser.test.ts +97 -0
- package/composables/useDriveBrowser/internal/browser.ts +113 -0
- package/composables/useFileImports/index.ts +40 -0
- package/composables/useFileImports/internal/__tests__/progress.test.ts +65 -0
- package/composables/useFileImports/internal/progress.ts +100 -0
- package/composables/useFileVersions/index.ts +34 -0
- package/composables/useFileVersions/internal/__tests__/versions.test.ts +30 -0
- package/composables/useFileVersions/internal/versions.ts +52 -0
- package/composables/usePasskeys/index.ts +52 -2
- package/composables/usePasskeys/internal/__tests__/statusCache.test.ts +38 -0
- package/composables/usePasskeys/internal/statusCache.ts +43 -0
- package/docs/files-drive.md +112 -0
- package/docs/passkeys.md +12 -5
- package/nuxt.config.ts +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
<script setup>
|
|
2
|
+
/**
|
|
3
|
+
* <Files.ProviderOrigin> — franja "Importado de Google Drive" con "Actualizar" y "Abrir en Drive".
|
|
4
|
+
* Solo se muestra si el archivo vino de un proveedor (file.provider). El botón aparece si
|
|
5
|
+
* file.can_refresh (fuente disponible). Emite `changed` cuando hubo versión nueva.
|
|
6
|
+
*
|
|
7
|
+
* <Files.ProviderOrigin :file="file" drive-base="platform" @changed="refetch" />
|
|
8
|
+
*/
|
|
9
|
+
import { IconBrandGoogleDrive, IconRefresh, IconExternalLink } from '@tabler/icons-vue'
|
|
10
|
+
import { isFinished, refreshOutcome } from '../../composables/useFileImports/internal/progress'
|
|
11
|
+
|
|
12
|
+
const props = defineProps({
|
|
13
|
+
file: { type: Object, required: true },
|
|
14
|
+
driveBase: { type: String, default: '' },
|
|
15
|
+
})
|
|
16
|
+
const emit = defineEmits(['changed'])
|
|
17
|
+
|
|
18
|
+
const toast = useToast()
|
|
19
|
+
const queryClient = useQueryClient()
|
|
20
|
+
const { refresh, track } = useFileImports(() => props.driveBase)
|
|
21
|
+
const importId = ref(null)
|
|
22
|
+
const tracker = track(importId)
|
|
23
|
+
const busy = computed(() => refresh.isPending.value || (!!importId.value && !isFinished(tracker.data.value?.status)))
|
|
24
|
+
|
|
25
|
+
const syncedLabel = computed(() => {
|
|
26
|
+
const at = props.file.external_synced_at
|
|
27
|
+
return at ? new Date(at).toLocaleString('es-CL', { dateStyle: 'medium', timeStyle: 'short' }) : null
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
async function onRefresh() {
|
|
31
|
+
try {
|
|
32
|
+
const imp = await refresh.mutateAsync(props.file.id)
|
|
33
|
+
importId.value = imp.id
|
|
34
|
+
} catch (e) {
|
|
35
|
+
toast.error(e?.data?.message ?? 'No se pudo actualizar desde Google Drive.')
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
watch(() => tracker.data.value?.status, (status) => {
|
|
40
|
+
if (!isFinished(status)) return
|
|
41
|
+
const outcome = refreshOutcome(tracker.data.value)
|
|
42
|
+
if (outcome.kind === 'failed') toast.error(outcome.message)
|
|
43
|
+
else toast.success(outcome.message)
|
|
44
|
+
if (outcome.kind === 'updated') {
|
|
45
|
+
queryClient.invalidateQueries({ queryKey: ['files', 'versions'] })
|
|
46
|
+
emit('changed')
|
|
47
|
+
}
|
|
48
|
+
importId.value = null
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
// Sin esto, un error al consultar el estado deja el botón cargando para siempre.
|
|
52
|
+
watch(() => tracker.isError.value, (failed) => {
|
|
53
|
+
if (!failed || !importId.value) return
|
|
54
|
+
toast.error(tracker.error.value?.data?.message ?? 'No se pudo consultar el estado de la actualización.')
|
|
55
|
+
importId.value = null
|
|
56
|
+
})
|
|
57
|
+
</script>
|
|
58
|
+
|
|
59
|
+
<template>
|
|
60
|
+
<div v-if="file.provider" class="flex flex-wrap items-center gap-2 rounded-control border border-card-line bg-card px-3 py-2 text-xs">
|
|
61
|
+
<IconBrandGoogleDrive class="size-4 shrink-0 text-muted-foreground" />
|
|
62
|
+
<span class="flex-1 min-w-0 text-muted-foreground">
|
|
63
|
+
Importado de Google Drive<template v-if="syncedLabel"> · sincronizado {{ syncedLabel }}</template>
|
|
64
|
+
</span>
|
|
65
|
+
<a v-if="file.external_url" :href="file.external_url" target="_blank" rel="noopener" class="inline-flex items-center gap-1 text-muted-foreground hover:text-primary">
|
|
66
|
+
<IconExternalLink class="size-3.5" /> Abrir en Drive
|
|
67
|
+
</a>
|
|
68
|
+
<AppButton v-if="file.can_refresh" text="Actualizar" :icon="IconRefresh" severity="secondary" size="xs" :loading="busy" @click="onRefresh" />
|
|
69
|
+
</div>
|
|
70
|
+
</template>
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
<script setup>
|
|
2
|
+
/**
|
|
3
|
+
* <Files.VersionHistory> — historial de versiones de un archivo: descargar cualquiera,
|
|
4
|
+
* restaurar (crea una versión nueva) y subir una versión nueva.
|
|
5
|
+
*
|
|
6
|
+
* <Files.VersionHistory files-base="platform/files" :file-id="file.id" @changed="refetch" />
|
|
7
|
+
*/
|
|
8
|
+
import { IconDownload, IconRestore, IconUpload, IconHistory } from '@tabler/icons-vue'
|
|
9
|
+
import { versionSourceLabel, formatBytes, versionResultMessage } from '../../composables/useFileVersions/internal/versions'
|
|
10
|
+
|
|
11
|
+
const props = defineProps({
|
|
12
|
+
filesBase: { type: String, required: true },
|
|
13
|
+
fileId: { type: String, required: true },
|
|
14
|
+
allowRestore: { type: Boolean, default: true },
|
|
15
|
+
allowUpload: { type: Boolean, default: true },
|
|
16
|
+
})
|
|
17
|
+
const emit = defineEmits(['changed'])
|
|
18
|
+
|
|
19
|
+
const toast = useToast()
|
|
20
|
+
const { confirm } = useModal()
|
|
21
|
+
const { list, restore, replace } = useFileVersions(() => ({ filesBase: props.filesBase, fileId: props.fileId }))
|
|
22
|
+
const versions = computed(() => list.data.value ?? [])
|
|
23
|
+
const restoring = ref(null)
|
|
24
|
+
|
|
25
|
+
function fmtDate(v) {
|
|
26
|
+
return v ? new Date(v).toLocaleString('es-CL', { dateStyle: 'medium', timeStyle: 'short' }) : '—'
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function onRestore(v) {
|
|
30
|
+
if (!await confirm({ title: `Restaurar v${v.version}`, message: 'Se creará una versión nueva con este contenido. El historial no se borra.', confirmText: 'Restaurar' })) return
|
|
31
|
+
restoring.value = v.version
|
|
32
|
+
try {
|
|
33
|
+
const res = await restore.mutateAsync(v.version)
|
|
34
|
+
toast.success(versionResultMessage(res))
|
|
35
|
+
if (res.status === 'created') emit('changed', res.file)
|
|
36
|
+
} catch (e) {
|
|
37
|
+
toast.error(e?.data?.message ?? 'No se pudo restaurar la versión.')
|
|
38
|
+
} finally {
|
|
39
|
+
restoring.value = null
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const picker = ref(null)
|
|
44
|
+
async function onPick(e) {
|
|
45
|
+
const file = e.target.files?.[0]
|
|
46
|
+
e.target.value = ''
|
|
47
|
+
if (!file) return
|
|
48
|
+
try {
|
|
49
|
+
const res = await replace.mutateAsync(file)
|
|
50
|
+
toast.success(versionResultMessage(res))
|
|
51
|
+
if (res.status === 'created') emit('changed', res.file)
|
|
52
|
+
} catch (err) {
|
|
53
|
+
toast.error(err?.data?.message ?? 'No se pudo subir la nueva versión.')
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
</script>
|
|
57
|
+
|
|
58
|
+
<template>
|
|
59
|
+
<div class="rounded-card border border-card-line bg-card">
|
|
60
|
+
<div class="flex items-center justify-between gap-2 px-4 py-3 border-b border-card-line">
|
|
61
|
+
<p class="flex items-center gap-1.5 text-sm font-medium text-foreground"><IconHistory class="size-4 text-muted-foreground" /> Versiones</p>
|
|
62
|
+
<template v-if="allowUpload">
|
|
63
|
+
<input ref="picker" type="file" class="hidden" @change="onPick">
|
|
64
|
+
<AppButton text="Subir nueva versión" :icon="IconUpload" severity="secondary" size="xs" :loading="replace.isPending.value" @click="picker?.click()" />
|
|
65
|
+
</template>
|
|
66
|
+
</div>
|
|
67
|
+
|
|
68
|
+
<p v-if="list.isLoading.value" class="px-4 py-3 text-sm text-muted-foreground">Cargando…</p>
|
|
69
|
+
<p v-else-if="list.error.value" class="px-4 py-3 text-sm text-red-600 dark:text-red-400">{{ list.error.value?.data?.message ?? 'No se pudo cargar el historial.' }}</p>
|
|
70
|
+
<ul v-else class="divide-y divide-card-line">
|
|
71
|
+
<li v-for="v in versions" :key="v.version" class="flex items-center gap-3 px-4 py-2.5 text-sm">
|
|
72
|
+
<span class="w-9 shrink-0 font-mono text-xs" :class="v.is_current ? 'text-primary font-semibold' : 'text-muted-foreground'">v{{ v.version }}</span>
|
|
73
|
+
<div class="flex-1 min-w-0">
|
|
74
|
+
<p class="text-foreground truncate">
|
|
75
|
+
{{ versionSourceLabel(v.source, v.restored_from_version) }}
|
|
76
|
+
<span v-if="v.is_current" class="ml-1 rounded-control bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary">Vigente</span>
|
|
77
|
+
</p>
|
|
78
|
+
<p class="text-[11px] text-muted-foreground">{{ fmtDate(v.created_at) }} · {{ formatBytes(v.size) }}</p>
|
|
79
|
+
</div>
|
|
80
|
+
<a v-if="v.download_url" :href="v.download_url" class="text-muted-foreground hover:text-primary" title="Descargar">
|
|
81
|
+
<IconDownload class="size-4" />
|
|
82
|
+
</a>
|
|
83
|
+
<button v-if="allowRestore && !v.is_current" type="button" class="text-muted-foreground hover:text-primary disabled:opacity-50"
|
|
84
|
+
:disabled="restoring !== null" title="Restaurar" @click="onRestore(v)">
|
|
85
|
+
<IconRestore class="size-4" :class="restoring === v.version ? 'animate-spin' : ''" />
|
|
86
|
+
</button>
|
|
87
|
+
</li>
|
|
88
|
+
</ul>
|
|
89
|
+
</div>
|
|
90
|
+
</template>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { resolve } from 'node:path'
|
|
4
|
+
import { parse, compileScript, compileTemplate } from 'vue/compiler-sfc'
|
|
5
|
+
|
|
6
|
+
const COMPONENTS = ['DriveBrowser', 'DriveFolderField', 'DriveImport', 'VersionHistory', 'ProviderOrigin']
|
|
7
|
+
|
|
8
|
+
describe('SFC de Files (Drive y versiones) compilan', () => {
|
|
9
|
+
for (const name of COMPONENTS) {
|
|
10
|
+
it(name, () => {
|
|
11
|
+
const filename = resolve(__dirname, `../${name}.vue`)
|
|
12
|
+
const { descriptor, errors } = parse(readFileSync(filename, 'utf8'), { filename })
|
|
13
|
+
expect(errors).toEqual([])
|
|
14
|
+
|
|
15
|
+
const script = compileScript(descriptor, { id: name })
|
|
16
|
+
const tpl = compileTemplate({
|
|
17
|
+
source: descriptor.template!.content,
|
|
18
|
+
filename,
|
|
19
|
+
id: name,
|
|
20
|
+
compilerOptions: { bindingMetadata: script.bindings },
|
|
21
|
+
})
|
|
22
|
+
expect(tpl.errors).toEqual([])
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
})
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { computed, ref, toValue, watch, type MaybeRefOrGetter } from 'vue'
|
|
2
|
+
import {
|
|
3
|
+
driveEndpoints, rootLocation, enter as enterLoc, goTo as goToLoc, current as currentOf,
|
|
4
|
+
breadcrumb as breadcrumbOf, browseParams, canPickCurrentFolder, locationFromPath,
|
|
5
|
+
type DriveEntry, type DriveLocation, type SharedDrive, type Crumb,
|
|
6
|
+
} from './internal/browser'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Navegador de Google Drive sobre innertia-laravel (Routes::registerDriveImport):
|
|
10
|
+
* GET {base}/drive/browse · GET {base}/drive/items/{id} · POST {base}/drive/folders
|
|
11
|
+
* `base` = prefijo con el que el producto registró las rutas (p. ej. 'platform').
|
|
12
|
+
* `enabled: false` no lista la carpeta (solo se usa `info`/`openAt`), p. ej. en un campo.
|
|
13
|
+
*/
|
|
14
|
+
export function useDriveBrowser(options: MaybeRefOrGetter<{ base: string; foldersOnly?: boolean; enabled?: boolean }>) {
|
|
15
|
+
const api = useApi()
|
|
16
|
+
const queryClient = useQueryClient()
|
|
17
|
+
const opts = computed(() => toValue(options))
|
|
18
|
+
const endpoints = computed(() => driveEndpoints(opts.value.base))
|
|
19
|
+
|
|
20
|
+
const location = ref<DriveLocation>(rootLocation())
|
|
21
|
+
const sharedDrives = ref<SharedDrive[]>([])
|
|
22
|
+
const params = computed(() => browseParams(location.value, !!opts.value.foldersOnly))
|
|
23
|
+
|
|
24
|
+
const query = useQuery({
|
|
25
|
+
queryKey: computed(() => ['drive', 'browse', endpoints.value.browse, params.value]),
|
|
26
|
+
queryFn: async () => {
|
|
27
|
+
const res: any = await api.get(endpoints.value.browse, { params: params.value })
|
|
28
|
+
return { items: (res?.items ?? []) as DriveEntry[], shared_drives: (res?.shared_drives ?? null) as SharedDrive[] | null }
|
|
29
|
+
},
|
|
30
|
+
enabled: computed(() => opts.value.enabled !== false),
|
|
31
|
+
staleTime: 30_000,
|
|
32
|
+
retry: false,
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// Desde data (no desde queryFn): con caché fresca el queryFn no corre al remontar.
|
|
36
|
+
watch(() => query.data.value?.shared_drives, (drives) => {
|
|
37
|
+
if (Array.isArray(drives)) sharedDrives.value = drives
|
|
38
|
+
}, { immediate: true })
|
|
39
|
+
|
|
40
|
+
const createFolder = useMutation({
|
|
41
|
+
mutationFn: (name: string) => api.post(endpoints.value.folders, { name, parent: currentOf(location.value).id }),
|
|
42
|
+
onSuccess: (res: any) => {
|
|
43
|
+
queryClient.invalidateQueries({ queryKey: ['drive', 'browse'] })
|
|
44
|
+
if (res?.item) location.value = enterLoc(location.value, res.item)
|
|
45
|
+
},
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
/** Abre el navegador en un ítem ya guardado (p. ej. la carpeta configurada). */
|
|
49
|
+
async function openAt(id: string) {
|
|
50
|
+
const res: any = await api.get(endpoints.value.item(id))
|
|
51
|
+
location.value = locationFromPath(res.item, res.path ?? [])
|
|
52
|
+
return res as { item: DriveEntry; path: Crumb[] }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
location,
|
|
57
|
+
sharedDrives,
|
|
58
|
+
items: computed(() => query.data.value?.items ?? []),
|
|
59
|
+
isLoading: computed(() => query.isFetching.value),
|
|
60
|
+
error: computed(() => (query.error.value ? ((query.error.value as any)?.data?.message ?? 'No se pudo listar Google Drive.') : null)),
|
|
61
|
+
current: computed(() => currentOf(location.value)),
|
|
62
|
+
breadcrumb: computed(() => breadcrumbOf(location.value)),
|
|
63
|
+
canPickCurrent: computed(() => canPickCurrentFolder(location.value)),
|
|
64
|
+
selectDrive: (drive: SharedDrive | null) => { location.value = rootLocation(drive) },
|
|
65
|
+
enter: (folder: Crumb) => { location.value = enterLoc(location.value, folder) },
|
|
66
|
+
goTo: (depth: number) => { location.value = goToLoc(location.value, depth) },
|
|
67
|
+
openAt,
|
|
68
|
+
info: (id: string) => api.get(endpoints.value.item(id)) as Promise<{ item: DriveEntry; path: Crumb[] }>,
|
|
69
|
+
createFolder,
|
|
70
|
+
refetch: () => query.refetch(),
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
joinPath, driveEndpoints, rootLocation, enter, goTo, current, breadcrumb, browseParams,
|
|
4
|
+
canPickCurrentFolder, locationFromPath, matchesAccept, isSelectable, toggleSelection,
|
|
5
|
+
MAX_SELECTION, type DriveEntry,
|
|
6
|
+
} from '../browser'
|
|
7
|
+
|
|
8
|
+
const entry = (over: Partial<DriveEntry> = {}): DriveEntry => ({
|
|
9
|
+
id: 'x', name: 'x', mime_type: 'application/pdf', size: 1, modified_time: null,
|
|
10
|
+
web_url: null, drive_id: null, is_folder: false, is_native: false, ...over,
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
describe('endpoints', () => {
|
|
14
|
+
it('une prefijos sin barras dobles', () => {
|
|
15
|
+
expect(joinPath('/platform/', 'drive/browse')).toBe('platform/drive/browse')
|
|
16
|
+
expect(joinPath('', 'drive/browse')).toBe('drive/browse')
|
|
17
|
+
})
|
|
18
|
+
it('arma las rutas de Drive e imports', () => {
|
|
19
|
+
const ep = driveEndpoints('platform')
|
|
20
|
+
expect(ep.browse).toBe('platform/drive/browse')
|
|
21
|
+
expect(ep.item('a b')).toBe('platform/drive/items/a%20b')
|
|
22
|
+
expect(ep.folders).toBe('platform/drive/folders')
|
|
23
|
+
expect(ep.imports).toBe('platform/files/imports')
|
|
24
|
+
expect(ep.importShow('u-1')).toBe('platform/files/imports/u-1')
|
|
25
|
+
expect(ep.refresh('f-1')).toBe('platform/files/f-1/refresh')
|
|
26
|
+
})
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
describe('navegación', () => {
|
|
30
|
+
it('parte en Mi unidad y entra/vuelve por migas', () => {
|
|
31
|
+
let loc = rootLocation()
|
|
32
|
+
expect(current(loc)).toEqual({ id: 'root', name: 'Mi unidad' })
|
|
33
|
+
loc = enter(loc, { id: 'A', name: 'Auditoría' })
|
|
34
|
+
loc = enter(loc, { id: 'B', name: '2026' })
|
|
35
|
+
expect(breadcrumb(loc).map(c => c.name)).toEqual(['Mi unidad', 'Auditoría', '2026'])
|
|
36
|
+
expect(current(loc).id).toBe('B')
|
|
37
|
+
expect(goTo(loc, 1).stack.map(c => c.id)).toEqual(['A'])
|
|
38
|
+
expect(goTo(loc, 0).stack).toEqual([])
|
|
39
|
+
})
|
|
40
|
+
it('una unidad compartida es su propia raíz', () => {
|
|
41
|
+
const loc = rootLocation({ id: 'sd', name: 'Equipo' })
|
|
42
|
+
expect(current(loc)).toEqual({ id: 'sd', name: 'Equipo' })
|
|
43
|
+
expect(breadcrumb(loc)[0].name).toBe('Equipo')
|
|
44
|
+
})
|
|
45
|
+
it('arma los params de browse', () => {
|
|
46
|
+
expect(browseParams(rootLocation(), false)).toEqual({})
|
|
47
|
+
expect(browseParams(enter(rootLocation(), { id: 'A', name: 'A' }), true)).toEqual({ parent: 'A', folders_only: 1 })
|
|
48
|
+
expect(browseParams(rootLocation({ id: 'sd', name: 'E' }), false)).toEqual({ drive_id: 'sd' })
|
|
49
|
+
})
|
|
50
|
+
it('la raíz de Mi unidad no se puede elegir como carpeta; una compartida sí', () => {
|
|
51
|
+
expect(canPickCurrentFolder(rootLocation())).toBe(false)
|
|
52
|
+
expect(canPickCurrentFolder(enter(rootLocation(), { id: 'A', name: 'A' }))).toBe(true)
|
|
53
|
+
expect(canPickCurrentFolder(rootLocation({ id: 'sd', name: 'E' }))).toBe(true)
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
describe('locationFromPath', () => {
|
|
58
|
+
it('abre en una carpeta de Mi unidad', () => {
|
|
59
|
+
const loc = locationFromPath({ id: 'C', name: 'C', drive_id: null }, [{ id: 'root', name: 'Mi unidad' }, { id: 'B', name: 'B' }])
|
|
60
|
+
expect(loc.drive).toBeNull()
|
|
61
|
+
expect(loc.stack.map(c => c.id)).toEqual(['B', 'C'])
|
|
62
|
+
})
|
|
63
|
+
it('abre en una carpeta de una unidad compartida', () => {
|
|
64
|
+
const loc = locationFromPath({ id: 'C', name: 'C', drive_id: 'sd' }, [{ id: 'sd', name: 'Equipo' }])
|
|
65
|
+
expect(loc.drive).toEqual({ id: 'sd', name: 'Equipo' })
|
|
66
|
+
expect(loc.stack.map(c => c.id)).toEqual(['C'])
|
|
67
|
+
})
|
|
68
|
+
it('con ruta parcial (sin acceso a la raíz) apila todo bajo Mi unidad', () => {
|
|
69
|
+
const loc = locationFromPath({ id: 'C', name: 'C', drive_id: null }, [{ id: 'X', name: 'X' }])
|
|
70
|
+
expect(loc.drive).toBeNull()
|
|
71
|
+
expect(loc.stack.map(c => c.id)).toEqual(['X', 'C'])
|
|
72
|
+
})
|
|
73
|
+
it('sin ruta queda en la raíz', () => {
|
|
74
|
+
expect(locationFromPath({ id: 'C', name: 'C', drive_id: null }, [])).toEqual({ drive: null, stack: [{ id: 'C', name: 'C' }] })
|
|
75
|
+
})
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
describe('selección', () => {
|
|
79
|
+
it('filtra por accept con comodines', () => {
|
|
80
|
+
expect(matchesAccept(entry({ mime_type: 'image/png' }), ['image/*'])).toBe(true)
|
|
81
|
+
expect(matchesAccept(entry({ mime_type: 'application/pdf' }), ['image/*'])).toBe(false)
|
|
82
|
+
expect(matchesAccept(entry(), [])).toBe(true)
|
|
83
|
+
expect(matchesAccept(entry({ mime_type: 'application/pdf' }), ['application/pdf'])).toBe(true)
|
|
84
|
+
})
|
|
85
|
+
it('las carpetas solo se seleccionan sin filtro accept', () => {
|
|
86
|
+
expect(isSelectable(entry({ is_folder: true }), [])).toBe(true)
|
|
87
|
+
expect(isSelectable(entry({ is_folder: true }), ['image/*'])).toBe(false)
|
|
88
|
+
})
|
|
89
|
+
it('alterna, respeta single y el máximo', () => {
|
|
90
|
+
const a = entry({ id: 'a' }); const b = entry({ id: 'b' })
|
|
91
|
+
expect(toggleSelection([], a, true).map(e => e.id)).toEqual(['a'])
|
|
92
|
+
expect(toggleSelection([a], a, true)).toEqual([])
|
|
93
|
+
expect(toggleSelection([a], b, false).map(e => e.id)).toEqual(['b'])
|
|
94
|
+
const full = Array.from({ length: MAX_SELECTION }, (_, i) => entry({ id: `i${i}` }))
|
|
95
|
+
expect(toggleSelection(full, b, true)).toHaveLength(MAX_SELECTION)
|
|
96
|
+
})
|
|
97
|
+
})
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lógica pura del navegador de Google Drive (sin Nuxt/Vue): endpoints, ubicación,
|
|
3
|
+
* migas, selección. La consumen useDriveBrowser y <Files.DriveBrowser>.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export interface DriveEntry {
|
|
7
|
+
id: string
|
|
8
|
+
name: string
|
|
9
|
+
mime_type: string
|
|
10
|
+
size: number | null
|
|
11
|
+
modified_time: string | null
|
|
12
|
+
web_url: string | null
|
|
13
|
+
drive_id: string | null
|
|
14
|
+
is_folder: boolean
|
|
15
|
+
is_native: boolean
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Crumb { id: string; name: string }
|
|
19
|
+
export interface SharedDrive { id: string; name: string }
|
|
20
|
+
|
|
21
|
+
/** drive null = Mi unidad. stack = carpetas abiertas bajo la raíz de la unidad. */
|
|
22
|
+
export interface DriveLocation { drive: SharedDrive | null; stack: Crumb[] }
|
|
23
|
+
|
|
24
|
+
export const MY_DRIVE = 'Mi unidad'
|
|
25
|
+
|
|
26
|
+
/** Tope de la API (POST files/imports admite hasta 200 ids). */
|
|
27
|
+
export const MAX_SELECTION = 200
|
|
28
|
+
|
|
29
|
+
export function joinPath(base: string, path: string): string {
|
|
30
|
+
const clean = (base ?? '').replace(/^\/+|\/+$/g, '')
|
|
31
|
+
return clean ? `${clean}/${path}` : path
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function driveEndpoints(base: string) {
|
|
35
|
+
return {
|
|
36
|
+
browse: joinPath(base, 'drive/browse'),
|
|
37
|
+
item: (id: string) => joinPath(base, `drive/items/${encodeURIComponent(id)}`),
|
|
38
|
+
folders: joinPath(base, 'drive/folders'),
|
|
39
|
+
imports: joinPath(base, 'files/imports'),
|
|
40
|
+
importShow: (id: string) => joinPath(base, `files/imports/${encodeURIComponent(id)}`),
|
|
41
|
+
refresh: (fileId: string) => joinPath(base, `files/${encodeURIComponent(fileId)}/refresh`),
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function rootLocation(drive: SharedDrive | null = null): DriveLocation {
|
|
46
|
+
return { drive, stack: [] }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function enter(loc: DriveLocation, folder: Crumb): DriveLocation {
|
|
50
|
+
return { ...loc, stack: [...loc.stack, { id: folder.id, name: folder.name }] }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** depth 0 = raíz de la unidad; depth n = deja las primeras n carpetas. */
|
|
54
|
+
export function goTo(loc: DriveLocation, depth: number): DriveLocation {
|
|
55
|
+
return { ...loc, stack: loc.stack.slice(0, Math.max(0, depth)) }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function current(loc: DriveLocation): Crumb {
|
|
59
|
+
return loc.stack.at(-1) ?? { id: loc.drive?.id ?? 'root', name: loc.drive?.name ?? MY_DRIVE }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function breadcrumb(loc: DriveLocation): Crumb[] {
|
|
63
|
+
return [{ id: loc.drive?.id ?? 'root', name: loc.drive?.name ?? MY_DRIVE }, ...loc.stack]
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Query params de GET drive/browse (el backend devuelve shared_drives solo sin parent ni drive_id). */
|
|
67
|
+
export function browseParams(loc: DriveLocation, foldersOnly: boolean): Record<string, string | number> {
|
|
68
|
+
const params: Record<string, string | number> = {}
|
|
69
|
+
if (loc.stack.length) params.parent = current(loc).id
|
|
70
|
+
if (loc.drive) params.drive_id = loc.drive.id
|
|
71
|
+
if (foldersOnly) params.folders_only = 1
|
|
72
|
+
return params
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** La raíz de Mi unidad no es un destino útil; la raíz de una unidad compartida sí. */
|
|
76
|
+
export function canPickCurrentFolder(loc: DriveLocation): boolean {
|
|
77
|
+
return loc.stack.length > 0 || loc.drive !== null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Ubicación para abrir el navegador EN un ítem ya elegido, a partir de GET drive/items/{id}.
|
|
82
|
+
* path excluye el ítem; puede venir parcial (sin acceso a la raíz) → todo bajo Mi unidad.
|
|
83
|
+
*/
|
|
84
|
+
export function locationFromPath(item: Crumb & { drive_id?: string | null }, path: Crumb[]): DriveLocation {
|
|
85
|
+
const self = { id: item.id, name: item.name }
|
|
86
|
+
if (!path.length) return { drive: null, stack: [self] }
|
|
87
|
+
|
|
88
|
+
const [root, ...rest] = path
|
|
89
|
+
if (item.drive_id && root.id === item.drive_id) {
|
|
90
|
+
return { drive: { id: item.drive_id, name: root.name }, stack: [...rest, self] }
|
|
91
|
+
}
|
|
92
|
+
if (root.id === 'root') return { drive: null, stack: [...rest, self] }
|
|
93
|
+
|
|
94
|
+
return { drive: null, stack: [...path, self] }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** accept: mimes exactos o comodines tipo 'image/*'. Vacío = todo. */
|
|
98
|
+
export function matchesAccept(entry: DriveEntry, accept: string[]): boolean {
|
|
99
|
+
if (!accept.length) return true
|
|
100
|
+
return accept.some(a => a.endsWith('/*') ? entry.mime_type.startsWith(a.slice(0, -1)) : entry.mime_type === a)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Con filtro accept las carpetas solo se navegan (no se eligen). */
|
|
104
|
+
export function isSelectable(entry: DriveEntry, accept: string[]): boolean {
|
|
105
|
+
return entry.is_folder ? accept.length === 0 : matchesAccept(entry, accept)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function toggleSelection(list: DriveEntry[], entry: DriveEntry, multiple: boolean): DriveEntry[] {
|
|
109
|
+
if (list.some(e => e.id === entry.id)) return list.filter(e => e.id !== entry.id)
|
|
110
|
+
if (!multiple) return [entry]
|
|
111
|
+
if (list.length >= MAX_SELECTION) return list
|
|
112
|
+
return [...list, entry]
|
|
113
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { computed, toValue, type MaybeRefOrGetter, type Ref } from 'vue'
|
|
2
|
+
import { driveEndpoints } from '../useDriveBrowser/internal/browser'
|
|
3
|
+
import { importPayload, isFinished, type FileImport } from './internal/progress'
|
|
4
|
+
|
|
5
|
+
const POLL_MS = 2000
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Importaciones desde Google Drive (innertia-laravel, Routes::registerDriveImport):
|
|
9
|
+
* POST {base}/files/imports → 202 {data} · GET {base}/files/imports/{id}
|
|
10
|
+
* POST {base}/files/{fileId}/refresh → 202 {data}
|
|
11
|
+
* El trabajo corre en cola: `track(id)` consulta cada 2 s hasta done/failed.
|
|
12
|
+
*/
|
|
13
|
+
export function useFileImports(base: MaybeRefOrGetter<string>) {
|
|
14
|
+
const api = useApi()
|
|
15
|
+
const endpoints = computed(() => driveEndpoints(toValue(base)))
|
|
16
|
+
|
|
17
|
+
const start = useMutation({
|
|
18
|
+
mutationFn: async (payload: Parameters<typeof importPayload>[0]) =>
|
|
19
|
+
((await api.post(endpoints.value.imports, importPayload(payload))) as any).data as FileImport,
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const refresh = useMutation({
|
|
23
|
+
mutationFn: async (fileId: string) =>
|
|
24
|
+
((await api.post(endpoints.value.refresh(fileId))) as any).data as FileImport,
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
/** Sigue un proceso hasta que termina (polling; se detiene solo). */
|
|
28
|
+
function track(importId: Ref<string | null>) {
|
|
29
|
+
return useQuery({
|
|
30
|
+
queryKey: computed(() => ['files', 'imports', importId.value]),
|
|
31
|
+
queryFn: async () => ((await api.get(endpoints.value.importShow(importId.value as string))) as any).data as FileImport,
|
|
32
|
+
enabled: computed(() => !!importId.value),
|
|
33
|
+
// Se detiene al terminar o si la consulta falló (p. ej. 404): no sondear para siempre.
|
|
34
|
+
refetchInterval: (q: any) => (q.state.status === 'error' || isFinished(q.state.data?.status) ? false : POLL_MS),
|
|
35
|
+
retry: 2,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return { start, refresh, track }
|
|
40
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
importPayload, isFinished, processedCount, progressPercent, groupItems, selectionFlags,
|
|
4
|
+
refreshOutcome, itemLabel, RESULT_ORDER, type FileImport,
|
|
5
|
+
} from '../progress'
|
|
6
|
+
|
|
7
|
+
const imp = (over: Partial<FileImport> = {}): FileImport => ({
|
|
8
|
+
id: 'i', kind: 'import', status: 'running', found: 4, imported: 1, updated: 1, unchanged: 0,
|
|
9
|
+
skipped: 1, failed: 0, items: [], error: null, ...over,
|
|
10
|
+
} as FileImport)
|
|
11
|
+
|
|
12
|
+
describe('importPayload', () => {
|
|
13
|
+
it('manda ids únicos y omite opcionales vacíos', () => {
|
|
14
|
+
expect(importPayload({ items: [{ id: 'a' }, { id: 'a' }, { id: 'b' }] as any }))
|
|
15
|
+
.toEqual({ items: ['a', 'b'], native_format: 'office' })
|
|
16
|
+
expect(importPayload({ items: ['a'], directoryId: 'd1', nativeFormat: 'pdf', visibility: 'restricted' }))
|
|
17
|
+
.toEqual({ items: ['a'], target_directory_id: 'd1', native_format: 'pdf', visibility: 'restricted' })
|
|
18
|
+
})
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
describe('estado', () => {
|
|
22
|
+
it('sabe cuándo terminó', () => {
|
|
23
|
+
expect(isFinished('done')).toBe(true)
|
|
24
|
+
expect(isFinished('failed')).toBe(true)
|
|
25
|
+
expect(isFinished('running')).toBe(false)
|
|
26
|
+
expect(isFinished(undefined)).toBe(false)
|
|
27
|
+
})
|
|
28
|
+
it('calcula el progreso acotado a 100', () => {
|
|
29
|
+
expect(processedCount(imp())).toBe(3)
|
|
30
|
+
expect(progressPercent(imp())).toBe(75)
|
|
31
|
+
expect(progressPercent(imp({ found: 0 }))).toBeNull()
|
|
32
|
+
expect(progressPercent(imp({ found: 1, failed: 5 }))).toBe(100)
|
|
33
|
+
})
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
describe('items', () => {
|
|
37
|
+
it('agrupa por resultado en orden estable', () => {
|
|
38
|
+
const g = groupItems([
|
|
39
|
+
{ result: 'failed', name: 'x', external_id: 'x' },
|
|
40
|
+
{ result: 'imported', name: 'a', external_id: 'a' },
|
|
41
|
+
{ result: 'imported', name: 'b', external_id: 'b' },
|
|
42
|
+
] as any)
|
|
43
|
+
expect(g.map(x => [x.result, x.items.length])).toEqual([['imported', 2], ['failed', 1]])
|
|
44
|
+
expect(RESULT_ORDER[0]).toBe('imported')
|
|
45
|
+
})
|
|
46
|
+
it('etiqueta con su ruta', () => {
|
|
47
|
+
expect(itemLabel({ name: 'acta.pdf', path: 'Auditoría/2026' } as any)).toBe('Auditoría/2026/acta.pdf')
|
|
48
|
+
expect(itemLabel({ name: 'acta.pdf', path: '' } as any)).toBe('acta.pdf')
|
|
49
|
+
expect(itemLabel({ name: null, external_id: 'abc' } as any)).toBe('abc')
|
|
50
|
+
})
|
|
51
|
+
it('detecta carpetas y nativos en la selección', () => {
|
|
52
|
+
expect(selectionFlags([{ is_folder: true, is_native: false }, { is_folder: false, is_native: true }] as any))
|
|
53
|
+
.toEqual({ hasFolders: true, hasNatives: true })
|
|
54
|
+
expect(selectionFlags([] as any)).toEqual({ hasFolders: false, hasNatives: false })
|
|
55
|
+
})
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
describe('refreshOutcome', () => {
|
|
59
|
+
it('traduce el resultado de un refresh', () => {
|
|
60
|
+
expect(refreshOutcome(imp({ status: 'done', updated: 1 })).kind).toBe('updated')
|
|
61
|
+
expect(refreshOutcome(imp({ status: 'done', updated: 0, unchanged: 1 })).kind).toBe('unchanged')
|
|
62
|
+
expect(refreshOutcome(imp({ status: 'failed', error: 'Ya no existe' }))).toEqual({ kind: 'failed', message: 'Ya no existe' })
|
|
63
|
+
expect(refreshOutcome(imp({ status: 'failed', error: null })).message).toBe('No se pudo actualizar desde Google Drive.')
|
|
64
|
+
})
|
|
65
|
+
})
|