@innertia-solutions/innertia-nuxt 0.1.82 → 0.1.84

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,137 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { createRenderer, h, nextTick, ref } from 'vue'
3
+ import Input from '../Input.vue'
4
+ import CurrencyInput from '../CurrencyInput.vue'
5
+
6
+ /*
7
+ * Renderer mínimo (sin DOM): cada nodo guarda su tag y los props/listeners que
8
+ * Vue le aplica. Basta para verificar a qué elemento llegan los $attrs.
9
+ */
10
+ type TestNode = {
11
+ tag: string
12
+ props: Record<string, any>
13
+ children: TestNode[]
14
+ parent: TestNode | null
15
+ text?: string
16
+ value?: any
17
+ /** vModelText registra listeners nativos; aquí basta con aceptarlos. */
18
+ addEventListener: () => void
19
+ }
20
+
21
+ function makeNode(tag: string): TestNode {
22
+ return { tag, props: {}, children: [], parent: null, addEventListener: () => {} }
23
+ }
24
+
25
+ function remove(child: TestNode) {
26
+ const p = child.parent
27
+ if (!p) return
28
+ const i = p.children.indexOf(child)
29
+ if (i > -1) p.children.splice(i, 1)
30
+ child.parent = null
31
+ }
32
+
33
+ const { createApp } = createRenderer<TestNode, TestNode>({
34
+ createElement: tag => makeNode(tag),
35
+ createText: text => ({ ...makeNode('#text'), text }),
36
+ createComment: text => ({ ...makeNode('#comment'), text }),
37
+ setText: (node, text) => { node.text = text },
38
+ setElementText: (node, text) => { node.children = []; node.text = text },
39
+ insert: (child, parent, anchor) => {
40
+ remove(child)
41
+ const i = anchor ? parent.children.indexOf(anchor) : -1
42
+ if (i > -1) parent.children.splice(i, 0, child)
43
+ else parent.children.push(child)
44
+ child.parent = parent
45
+ },
46
+ remove,
47
+ parentNode: node => node.parent,
48
+ nextSibling: (node) => {
49
+ const p = node.parent
50
+ if (!p) return null
51
+ return p.children[p.children.indexOf(node) + 1] ?? null
52
+ },
53
+ patchProp: (el, key, _prev, next) => {
54
+ if (next == null) delete el.props[key]
55
+ else el.props[key] = next
56
+ },
57
+ })
58
+
59
+ function find(node: TestNode, tag: string): TestNode | undefined {
60
+ if (node.tag === tag) return node
61
+ for (const c of node.children) {
62
+ const hit = find(c, tag)
63
+ if (hit) return hit
64
+ }
65
+ }
66
+
67
+ /**
68
+ /** Sin DOM ni SSR: monta la app sobre el renderer de prueba. */
69
+ function mountApp(render: () => any, root: TestNode) {
70
+ createApp({ render }).mount(root)
71
+ }
72
+
73
+ function mount(component: any, props: Record<string, any>) {
74
+ const root = makeNode('root')
75
+ mountApp(() => h(component, props), root)
76
+ const wrapper = root.children.find(c => c.tag === 'div')!
77
+ const input = find(root, 'input')!
78
+ return { root, wrapper, input }
79
+ }
80
+
81
+ /** Vue puede guardar un listener como función o como array (merge de listeners). */
82
+ function call(listener: any, ...args: any[]) {
83
+ if (Array.isArray(listener)) listener.forEach(fn => fn(...args))
84
+ else listener(...args)
85
+ }
86
+
87
+ describe('Forms.Input reenvía $attrs al <input>', () => {
88
+ it('pone maxlength/required/inputmode en el input y no en el div raíz', () => {
89
+ const { wrapper, input } = mount(Input, { maxlength: 20, required: true, inputmode: 'numeric', name: 'code' })
90
+ expect(input.props.maxlength).toBe(20)
91
+ expect(input.props.required).toBe(true)
92
+ expect(input.props.inputmode).toBe('numeric')
93
+ expect(input.props.name).toBe('code')
94
+ expect(wrapper.props.maxlength).toBeUndefined()
95
+ })
96
+
97
+ it('ejecuta @blur y @keydown del consumidor sobre el input', () => {
98
+ const onBlur = vi.fn()
99
+ const onKeydown = vi.fn()
100
+ const { wrapper, input } = mount(Input, { onBlur, onKeydown })
101
+ expect(wrapper.props.onBlur).toBeUndefined()
102
+ call(input.props.onBlur, { type: 'blur' })
103
+ call(input.props.onKeydown, { type: 'keydown' })
104
+ expect(onBlur).toHaveBeenCalledOnce()
105
+ expect(onKeydown).toHaveBeenCalledOnce()
106
+ })
107
+
108
+ it('mantiene class y style en el div raíz', () => {
109
+ const { wrapper, input } = mount(Input, { class: 'col-span-2', style: { width: '10px' } })
110
+ expect(wrapper.props.class).toContain('col-span-2')
111
+ expect(wrapper.props.class).toContain('w-full')
112
+ expect(wrapper.props.style).toMatchObject({ width: '10px' })
113
+ expect(input.props.class).not.toContain('col-span-2')
114
+ expect(input.props.style).toBeUndefined()
115
+ })
116
+
117
+ it('actualiza los attrs reenviados cuando cambian', async () => {
118
+ const max = ref(10)
119
+ const root = makeNode('root')
120
+ mountApp(() => h(Input, { maxlength: max.value }), root)
121
+ expect(find(root, 'input')!.props.maxlength).toBe(10)
122
+ max.value = 30
123
+ await nextTick()
124
+ expect(find(root, 'input')!.props.maxlength).toBe(30)
125
+ })
126
+ })
127
+
128
+ describe('Forms.CurrencyInput reenvía $attrs al <input>', () => {
129
+ it('combina el @blur del consumidor con el blur interno', () => {
130
+ const onBlur = vi.fn()
131
+ const { wrapper, input } = mount(CurrencyInput, { onBlur, maxlength: 15, class: 'mb-2' })
132
+ expect(input.props.maxlength).toBe(15)
133
+ expect(wrapper.props.class).toContain('mb-2')
134
+ call(input.props.onBlur, { type: 'blur' })
135
+ expect(onBlur).toHaveBeenCalledOnce()
136
+ })
137
+ })
@@ -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
+ })
@@ -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
+ }