@innertia-solutions/innertia-nuxt 0.1.82 → 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.
@@ -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
+ })
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Lógica pura de importaciones desde Drive (sin Nuxt/Vue). La consumen
3
+ * useFileImports, <Files.DriveImport> y <Files.ProviderOrigin>.
4
+ */
5
+
6
+ export type ImportStatus = 'pending' | 'running' | 'done' | 'failed'
7
+ export type ItemResult = 'imported' | 'updated' | 'unchanged' | 'skipped' | 'failed'
8
+
9
+ export interface ImportItem {
10
+ result: ItemResult
11
+ external_id: string | null
12
+ name: string | null
13
+ path?: string
14
+ reason?: string
15
+ file_id?: string
16
+ is_folder?: boolean
17
+ }
18
+
19
+ export interface FileImport {
20
+ id: string
21
+ kind: 'import' | 'refresh'
22
+ status: ImportStatus
23
+ found: number
24
+ imported: number
25
+ updated: number
26
+ unchanged: number
27
+ skipped: number
28
+ failed: number
29
+ items: ImportItem[]
30
+ error: string | null
31
+ file_id?: string | null
32
+ target_directory_id?: string | null
33
+ started_at?: string | null
34
+ finished_at?: string | null
35
+ }
36
+
37
+ export const RESULT_ORDER: ItemResult[] = ['imported', 'updated', 'unchanged', 'skipped', 'failed']
38
+
39
+ export const RESULT_LABELS: Record<ItemResult, string> = {
40
+ imported: 'Importados',
41
+ updated: 'Actualizados',
42
+ unchanged: 'Sin cambios',
43
+ skipped: 'Omitidos',
44
+ failed: 'Con error',
45
+ }
46
+
47
+ export function importPayload(opts: {
48
+ items: Array<string | { id: string }>
49
+ directoryId?: string | null
50
+ nativeFormat?: 'office' | 'pdf'
51
+ visibility?: 'public' | 'auth' | 'restricted' | null
52
+ }) {
53
+ const ids = [...new Set(opts.items.map(i => (typeof i === 'string' ? i : i.id)))]
54
+ const payload: Record<string, unknown> = { items: ids }
55
+ if (opts.directoryId) payload.target_directory_id = opts.directoryId
56
+ payload.native_format = opts.nativeFormat ?? 'office'
57
+ if (opts.visibility) payload.visibility = opts.visibility
58
+ return payload
59
+ }
60
+
61
+ export function isFinished(status: ImportStatus | undefined | null): boolean {
62
+ return status === 'done' || status === 'failed'
63
+ }
64
+
65
+ export function processedCount(imp: Pick<FileImport, 'imported' | 'updated' | 'unchanged' | 'skipped' | 'failed'>): number {
66
+ return imp.imported + imp.updated + imp.unchanged + imp.skipped + imp.failed
67
+ }
68
+
69
+ /** null mientras no se conoce el total (aún recorriendo Drive). */
70
+ export function progressPercent(imp: FileImport): number | null {
71
+ if (!imp.found) return null
72
+ return Math.min(100, Math.round((processedCount(imp) / imp.found) * 100))
73
+ }
74
+
75
+ export function groupItems(items: ImportItem[]): { result: ItemResult; label: string; items: ImportItem[] }[] {
76
+ return RESULT_ORDER
77
+ .map(result => ({ result, label: RESULT_LABELS[result], items: items.filter(i => i.result === result) }))
78
+ .filter(g => g.items.length > 0)
79
+ }
80
+
81
+ export function itemLabel(item: ImportItem): string {
82
+ const name = item.name ?? item.external_id ?? '—'
83
+ return item.path ? `${item.path}/${name}` : name
84
+ }
85
+
86
+ export function selectionFlags(entries: Array<{ is_folder: boolean; is_native: boolean }>) {
87
+ return {
88
+ hasFolders: entries.some(e => e.is_folder),
89
+ hasNatives: entries.some(e => e.is_native),
90
+ }
91
+ }
92
+
93
+ export function refreshOutcome(imp: FileImport): { kind: 'updated' | 'unchanged' | 'failed'; message: string } {
94
+ if (imp.status === 'failed') {
95
+ return { kind: 'failed', message: imp.error || 'No se pudo actualizar desde Google Drive.' }
96
+ }
97
+ return imp.updated > 0
98
+ ? { kind: 'updated', message: 'Actualizado desde Google Drive: se creó una nueva versión.' }
99
+ : { kind: 'unchanged', message: 'Sin cambios: el archivo ya estaba al día con Google Drive.' }
100
+ }
@@ -0,0 +1,34 @@
1
+ import { computed, toValue, type MaybeRefOrGetter } from 'vue'
2
+ import { versionEndpoints, type FileVersionEntry } from './internal/versions'
3
+
4
+ /**
5
+ * Historial de versiones de un archivo (innertia-laravel, Files\Routes::register):
6
+ * GET {filesBase}/{id}/versions · POST …/versions/{n}/restore · POST …/contents (multipart)
7
+ */
8
+ export function useFileVersions(options: MaybeRefOrGetter<{ filesBase: string; fileId: string | null }>) {
9
+ const api = useApi()
10
+ const { upload } = useFile()
11
+ const queryClient = useQueryClient()
12
+ const opts = computed(() => toValue(options))
13
+ const endpoints = computed(() => (opts.value.fileId ? versionEndpoints(opts.value.filesBase, opts.value.fileId) : null))
14
+ const key = computed(() => ['files', 'versions', opts.value.filesBase, opts.value.fileId])
15
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: ['files', 'versions'] })
16
+
17
+ const list = useQuery({
18
+ queryKey: key,
19
+ queryFn: async () => ((await api.get(endpoints.value!.list)) as any).data as FileVersionEntry[],
20
+ enabled: computed(() => !!endpoints.value),
21
+ })
22
+
23
+ const restore = useMutation({
24
+ mutationFn: (version: number) => api.post(endpoints.value!.restore(version)) as Promise<any>,
25
+ onSuccess: invalidate,
26
+ })
27
+
28
+ const replace = useMutation({
29
+ mutationFn: (file: File) => upload(endpoints.value!.contents, file, { field: 'file' }) as Promise<any>,
30
+ onSuccess: invalidate,
31
+ })
32
+
33
+ return { list, restore, replace, invalidate }
34
+ }
@@ -0,0 +1,30 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { versionEndpoints, versionSourceLabel, formatBytes, versionResultMessage } from '../versions'
3
+
4
+ describe('versiones', () => {
5
+ it('arma endpoints bajo el prefijo de Files', () => {
6
+ const ep = versionEndpoints('platform/files', 'f 1')
7
+ expect(ep.list).toBe('platform/files/f%201/versions')
8
+ expect(ep.restore(3)).toBe('platform/files/f%201/versions/3/restore')
9
+ expect(ep.contents).toBe('platform/files/f%201/contents')
10
+ })
11
+ it('etiqueta el origen', () => {
12
+ expect(versionSourceLabel('upload')).toBe('Subida')
13
+ expect(versionSourceLabel('replace')).toBe('Reemplazo')
14
+ expect(versionSourceLabel('provider_import')).toBe('Desde Drive')
15
+ expect(versionSourceLabel('provider_refresh')).toBe('Actualizada desde Drive')
16
+ expect(versionSourceLabel('restore', 2)).toBe('Restaurada desde v2')
17
+ expect(versionSourceLabel('restore', null)).toBe('Restaurada')
18
+ expect(versionSourceLabel('otro' as any)).toBe('Versión')
19
+ })
20
+ it('formatea tamaños', () => {
21
+ expect(formatBytes(512)).toBe('512 B')
22
+ expect(formatBytes(2048)).toBe('2.0 KB')
23
+ expect(formatBytes(5 * 1048576)).toBe('5.0 MB')
24
+ expect(formatBytes(null)).toBe('—')
25
+ })
26
+ it('mensajes de resultado', () => {
27
+ expect(versionResultMessage({ status: 'created', file: { version: 4 } })).toBe('Nueva versión v4 creada.')
28
+ expect(versionResultMessage({ status: 'unchanged', file: { version: 3 } })).toBe('Sin cambios: el contenido es igual a la versión vigente.')
29
+ })
30
+ })
@@ -0,0 +1,52 @@
1
+ /** Lógica pura del historial de versiones (sin Nuxt/Vue). */
2
+ import { joinPath } from '../../useDriveBrowser/internal/browser'
3
+
4
+ export type VersionSource = 'upload' | 'replace' | 'provider_import' | 'provider_refresh' | 'restore'
5
+
6
+ export interface FileVersionEntry {
7
+ version: number
8
+ is_current: boolean
9
+ original_name: string
10
+ mime_type: string | null
11
+ extension: string | null
12
+ size: number
13
+ source: VersionSource
14
+ restored_from_version: number | null
15
+ created_by: string | null
16
+ created_at: string | null
17
+ superseded_at: string | null
18
+ download_url: string | null
19
+ }
20
+
21
+ export function versionEndpoints(filesBase: string, fileId: string) {
22
+ const id = encodeURIComponent(fileId)
23
+ return {
24
+ list: joinPath(filesBase, `${id}/versions`),
25
+ restore: (version: number) => joinPath(filesBase, `${id}/versions/${version}/restore`),
26
+ contents: joinPath(filesBase, `${id}/contents`),
27
+ }
28
+ }
29
+
30
+ export function versionSourceLabel(source: VersionSource, restoredFrom?: number | null): string {
31
+ switch (source) {
32
+ case 'upload': return 'Subida'
33
+ case 'replace': return 'Reemplazo'
34
+ case 'provider_import': return 'Desde Drive'
35
+ case 'provider_refresh': return 'Actualizada desde Drive'
36
+ case 'restore': return restoredFrom ? `Restaurada desde v${restoredFrom}` : 'Restaurada'
37
+ default: return 'Versión'
38
+ }
39
+ }
40
+
41
+ export function formatBytes(bytes: number | null | undefined): string {
42
+ if (bytes === null || bytes === undefined) return '—'
43
+ if (bytes < 1024) return `${bytes} B`
44
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`
45
+ return `${(bytes / 1048576).toFixed(1)} MB`
46
+ }
47
+
48
+ export function versionResultMessage(res: { status: 'created' | 'unchanged'; file: { version: number } }): string {
49
+ return res.status === 'created'
50
+ ? `Nueva versión v${res.file.version} creada.`
51
+ : 'Sin cambios: el contenido es igual a la versión vigente.'
52
+ }
@@ -0,0 +1,112 @@
1
+ # Google Drive y versiones de archivos
2
+
3
+ Componentes para importar desde Google Drive al storage del producto, elegir una carpeta de Drive como configuración, ver el origen de un archivo importado (con "Actualizar") y gestionar el historial de versiones. Se apoyan en `\Innertia\Files` de innertia-laravel.
4
+
5
+ > En los productos los componentes se usan con la notación con punto (`<Files.DriveImport>`, `<Files.VersionHistory>`, …). Dentro de la librería se referencian sin punto (`<FilesDriveBrowser>`).
6
+
7
+ ## Requisitos (backend Laravel)
8
+
9
+ 1. **Proveedor conectado:** Google Drive conectado vía `\Innertia\Files\Routes::registerProviderConnections()` (ver `<Files.ProviderConnectButton>`).
10
+ 2. **Rutas de Drive e importaciones** (opt-in), dentro del grupo autenticado del producto:
11
+
12
+ ```php
13
+ \Innertia\Files\Routes::registerDriveImport('platform');
14
+ ```
15
+
16
+ Con prefijo `platform` quedan:
17
+
18
+ | Método | Ruta | Uso |
19
+ |---|---|---|
20
+ | GET | `platform/drive/browse?parent=&drive_id=&folders_only=` | listar carpeta (`items`, y `shared_drives` en la raíz) |
21
+ | GET | `platform/drive/items/{id}` | metadatos + ruta (`{ item, path }`) |
22
+ | POST | `platform/drive/folders` | crear carpeta (`{ name, parent }`) |
23
+ | POST | `platform/files/imports` | iniciar importación (202, corre en cola) |
24
+ | GET | `platform/files/imports/{id}` | estado del proceso |
25
+ | POST | `platform/files/{id}/refresh` | actualizar un archivo desde Drive (202) |
26
+
27
+ El valor del prop `drive-base` de los componentes es ese mismo prefijo (`'platform'`, o `''` si se registró sin prefijo).
28
+ 3. **Versiones:** `\Innertia\Files\Routes::register('platform/files')` ya expone `GET {id}/versions`, `POST {id}/versions/{n}/restore` y `POST {id}/contents` (multipart, campo `file`). El prop `files-base` es ese prefijo (`'platform/files'`).
29
+ 4. Un worker de cola corriendo: importaciones y refresh son asíncronos; el front consulta el estado cada 2 s hasta `done`/`failed`.
30
+
31
+ ## Componentes
32
+
33
+ ### `<Files.DriveBrowser>`
34
+
35
+ Panel para navegar Mi unidad y las unidades compartidas, con migas y "Nueva carpeta".
36
+
37
+ | Prop | Tipo | Default | |
38
+ |---|---|---|---|
39
+ | `drive-base` | String | `''` | prefijo de las rutas de Drive |
40
+ | `mode` | `'items' \| 'folder'` | `'items'` | `items`: v-model con la selección; `folder`: solo carpetas, emite `pick` |
41
+ | `v-model` | `DriveEntry[]` | `[]` | selección (modo `items`) |
42
+ | `multiple` | Boolean | `true` | selección múltiple (tope 200) |
43
+ | `accept` | String[] | `[]` | mimes o comodines (`'image/*'`); con filtro las carpetas solo se navegan |
44
+ | `start-at` | String | `null` | abre el panel en esa carpeta |
45
+ | `allow-create` | Boolean | `true` | muestra "Nueva carpeta" |
46
+
47
+ Eventos: `update:modelValue`, `pick({ id, name })` (modo `folder`, botón "Usar …"; la raíz de Mi unidad no es elegible).
48
+
49
+ ### `<Files.DriveFolderField>`
50
+
51
+ Campo de formulario "carpeta de Google Drive". `v-model` = id de la carpeta (`''` = ninguna). Muestra nombre, ruta y enlace a Drive, y abre `<Files.DriveBrowser mode="folder">` en un modal.
52
+
53
+ Props: `v-model`, `drive-base`, `title` (título del modal).
54
+
55
+ ### `<Files.DriveImport>`
56
+
57
+ Modal autocontenido: **elegir → opciones → progreso/resumen**. Cerrar no cancela el proceso.
58
+
59
+ | Prop | Tipo | Default | |
60
+ |---|---|---|---|
61
+ | `v-model` | Boolean | `false` | abierto/cerrado |
62
+ | `drive-base` | String | `''` | prefijo de las rutas |
63
+ | `directory-id` | String | `null` | directorio destino |
64
+ | `folders-allowed` | Boolean | `true` | `false` si el producto no usa Directories: bloquea carpetas en la selección |
65
+ | `visibility` | String | `null` | `public \| auth \| restricted` para los archivos creados |
66
+ | `resume-id` | String | `null` | reabre el seguimiento de un import en curso |
67
+
68
+ Eventos: `update:modelValue`, `done(import)` al terminar (`done` o `failed`). Si hay documentos nativos de Google (Docs/Sheets/Slides) ofrece formato Office o PDF.
69
+
70
+ ### `<Files.ProviderOrigin>`
71
+
72
+ Franja "Importado de Google Drive · sincronizado …" con "Abrir en Drive" y "Actualizar" (si `file.can_refresh`). No se muestra si `file.provider` está vacío.
73
+
74
+ Props: `file` (FileResource), `drive-base`. Evento: `changed` cuando el refresh creó una versión nueva (avisa con toast tanto si hubo cambios como si no).
75
+
76
+ ### `<Files.VersionHistory>`
77
+
78
+ Lista de versiones (fuente, fecha, tamaño, vigente) con descarga, "Restaurar" (crea una versión nueva, pide confirmación) y "Subir nueva versión".
79
+
80
+ Props: `files-base` (requerido), `file-id` (requerido), `allow-restore` (true), `allow-upload` (true). Evento: `changed(file)` cuando se creó una versión.
81
+
82
+ ## Composables
83
+
84
+ Auto-importados: `useDriveBrowser({ base, foldersOnly?, enabled? })`, `useFileImports(base)` (`start`, `refresh`, `track(importIdRef)`) y `useFileVersions({ filesBase, fileId })` (`list`, `restore`, `replace`). Los helpers de `internal/` no se auto-importan.
85
+
86
+ ## Ejemplo en un explorador de producto
87
+
88
+ ```vue
89
+ <script setup>
90
+ const showImport = ref(false)
91
+ const selected = ref(null) // archivo en vista previa
92
+ const { data, refetch } = useQuery(/* … listado del directorio actual … */)
93
+ </script>
94
+
95
+ <template>
96
+ <!-- Barra del explorador -->
97
+ <AppButton text="Importar desde Drive" @click="showImport = true" />
98
+ <Files.DriveImport v-model="showImport" drive-base="platform" :directory-id="currentDir?.id" @done="refetch" />
99
+
100
+ <!-- Vista previa -->
101
+ <template v-if="selected">
102
+ <Files.ProviderOrigin :file="selected" drive-base="platform" @changed="refetch" />
103
+ <Files.VersionHistory files-base="platform/files" :file-id="selected.id" @changed="refetch" />
104
+ </template>
105
+ </template>
106
+ ```
107
+
108
+ Configuración (p. ej. carpeta por defecto para exportaciones):
109
+
110
+ ```vue
111
+ <Files.DriveFolderField v-model="form.drive_folder_id" drive-base="platform" />
112
+ ```
package/nuxt.config.ts CHANGED
@@ -29,7 +29,7 @@ export default defineNuxtConfig({
29
29
  { path: './components', pathPrefix: true, prefix: '' },
30
30
  ],
31
31
  imports: {
32
- dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys'],
32
+ dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys', 'composables/useDriveBrowser', 'composables/useFileImports', 'composables/useFileVersions'],
33
33
  presets: [
34
34
  {
35
35
  from: '@tanstack/vue-query',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@innertia-solutions/innertia-nuxt",
3
- "version": "0.1.82",
3
+ "version": "0.1.83",
4
4
  "description": "Innertia Solutions — Nuxt layer unificada: core, auth, multitenancy, theme y app contexts",
5
5
  "keywords": [
6
6
  "nuxt",