supabase-local #15
@@ -1,6 +1,19 @@
|
||||
import { google } from 'googleapis';
|
||||
import { getAuthenticatedClient } from '../auth/server.js';
|
||||
import { GoogleSheet } from './types.ts'
|
||||
import { GoogleSheet } from './types.ts';
|
||||
|
||||
// Type for sheet data
|
||||
export interface SheetData {
|
||||
values: string[][];
|
||||
}
|
||||
|
||||
// Server-side Google Sheets API handler
|
||||
export const googleSheetsServer = {
|
||||
getRecentSpreadsheets,
|
||||
getSpreadsheetData,
|
||||
getSpreadsheetInfo,
|
||||
searchSheets
|
||||
};
|
||||
|
||||
/**
|
||||
* Get a list of recent Google Sheets
|
||||
@@ -77,3 +90,38 @@ export async function getSpreadsheetInfo(
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for Google Sheets by name
|
||||
* @param refreshToken - Google refresh token
|
||||
* @param query - Search query
|
||||
* @param limit - Maximum number of sheets to return
|
||||
* @returns List of Google Sheets matching the query
|
||||
*/
|
||||
export async function searchSheets(
|
||||
refreshToken: string,
|
||||
query: string,
|
||||
limit: number = 20
|
||||
): Promise<GoogleSheet[]> {
|
||||
const oauth = getAuthenticatedClient(refreshToken);
|
||||
const drive = google.drive({ version: 'v3', auth: oauth });
|
||||
|
||||
// Create a query to search for spreadsheets with names containing the search term
|
||||
const q = `mimeType='application/vnd.google-apps.spreadsheet' and name contains '${query}'`;
|
||||
|
||||
const response = await drive.files.list({
|
||||
q,
|
||||
orderBy: 'modifiedTime desc',
|
||||
pageSize: limit,
|
||||
fields: 'files(id,name,modifiedTime,webViewLink)'
|
||||
});
|
||||
|
||||
return (
|
||||
response.data.files?.map(file => ({
|
||||
id: file.id!, // eslint-disable-line @typescript-eslint/no-non-null-assertion
|
||||
name: file.name!,
|
||||
modifiedTime: file.modifiedTime!,
|
||||
webViewLink: file.webViewLink!
|
||||
})) || []
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { googleSheetsServer } from '$lib/google/server.ts';
|
||||
import { googleSheetsServer } from '$lib/google/sheets/server.js';
|
||||
|
||||
export const GET: RequestHandler = async ({ params, request }) => {
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { googleSheetsServer } from '$lib/google/server.ts';
|
||||
import { googleSheetsServer } from '$lib/google/sheets/server.js';
|
||||
|
||||
export const GET: RequestHandler = async ({ request }) => {
|
||||
try {
|
||||
|
||||
30
src/routes/private/api/google/sheets/search/+server.ts
Normal file
30
src/routes/private/api/google/sheets/search/+server.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { googleSheetsServer } from '$lib/google/sheets/server.js';
|
||||
|
||||
export const GET: RequestHandler = async ({ url, request }) => {
|
||||
try {
|
||||
// Get search query from URL
|
||||
const query = url.searchParams.get('query');
|
||||
|
||||
if (!query) {
|
||||
throw error(400, 'Search query is required');
|
||||
}
|
||||
|
||||
// Get authorization token from request headers
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
throw error(401, 'Missing or invalid Authorization header');
|
||||
}
|
||||
const refreshToken = authHeader.substring(7); // Remove "Bearer " prefix
|
||||
|
||||
// Search for sheets using the query
|
||||
const sheets = await googleSheetsServer.searchSheets(refreshToken, query);
|
||||
|
||||
// Return the search results
|
||||
return json(sheets);
|
||||
} catch (err) {
|
||||
console.error('Error searching Google Sheets:', err);
|
||||
throw error(500, 'Failed to search Google Sheets');
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import type { GoogleSheet } from '$lib/google/google/types.tsient/types.js';
|
||||
import type { GoogleSheet } from '$lib/google/sheets/types.ts';
|
||||
|
||||
// Props
|
||||
let { sheetsData, errors, loadRecentSheets, selectSheet, toggleSheetList } = $props<{
|
||||
@@ -21,6 +21,72 @@
|
||||
selectSheet: (sheet: GoogleSheet) => Promise<void>;
|
||||
toggleSheetList: () => void;
|
||||
}>();
|
||||
|
||||
// Search functionality
|
||||
let searchQuery = $state('');
|
||||
let isSearching = $state(false);
|
||||
let searchResults = $state<GoogleSheet[]>([]);
|
||||
let searchError = $state('');
|
||||
|
||||
// Debounce function for search
|
||||
function debounce(func: (...args: any[]) => void, wait: number) {
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
return function(...args: any[]) {
|
||||
const later = () => {
|
||||
timeout = null;
|
||||
func(...args);
|
||||
};
|
||||
if (timeout) clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
};
|
||||
}
|
||||
|
||||
// Search for sheets
|
||||
const searchSheets = debounce(async () => {
|
||||
if (!searchQuery.trim()) {
|
||||
searchResults = [];
|
||||
return;
|
||||
}
|
||||
|
||||
isSearching = true;
|
||||
searchError = '';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/private/api/google/sheets/search?query=${encodeURIComponent(searchQuery)}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${localStorage.getItem('google_refresh_token')}`
|
||||
}
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
searchResults = await response.json();
|
||||
} else {
|
||||
searchError = 'Failed to search for sheets';
|
||||
console.error('Search error:', await response.text());
|
||||
}
|
||||
} catch (error) {
|
||||
searchError = 'Error searching for sheets';
|
||||
console.error('Search error:', error);
|
||||
} finally {
|
||||
isSearching = false;
|
||||
}
|
||||
}, 500);
|
||||
|
||||
// Clear search
|
||||
function clearSearch() {
|
||||
searchQuery = '';
|
||||
searchResults = [];
|
||||
searchError = '';
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (searchQuery) {
|
||||
searchSheets();
|
||||
} else {
|
||||
searchResults = [];
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="space-y-6">
|
||||
@@ -69,9 +135,9 @@
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- All sheets (expanded view) -->
|
||||
<!-- All sheets and search (expanded view) -->
|
||||
<div class="flex justify-between items-center mb-2">
|
||||
<h4 class="text-sm font-medium text-gray-700">Available Sheets</h4>
|
||||
<h4 class="text-sm font-medium text-gray-700">Google Sheets</h4>
|
||||
{#if sheetsData.selectedSheet}
|
||||
<button
|
||||
onclick={toggleSheetList}
|
||||
@@ -82,6 +148,90 @@
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Search bar -->
|
||||
<div class="relative mb-4">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={searchQuery}
|
||||
placeholder="Search all your Google Sheets..."
|
||||
class="w-full px-4 py-2 pl-10 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
{#if searchQuery}
|
||||
<button
|
||||
onclick={clearSearch}
|
||||
class="absolute inset-y-0 right-0 pr-3 flex items-center"
|
||||
aria-label="Clear search"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400 hover:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if isSearching}
|
||||
<!-- Loading state -->
|
||||
<div class="space-y-3">
|
||||
{#each Array(3) as _}
|
||||
<div class="p-4 border border-gray-200 rounded animate-pulse">
|
||||
<div class="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
|
||||
<div class="h-3 bg-gray-100 rounded w-1/2"></div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else if searchQuery && searchResults.length === 0 && !searchError}
|
||||
<!-- No search results -->
|
||||
<div class="text-center py-6 border border-gray-200 rounded">
|
||||
<p class="text-gray-500">No sheets found matching "{searchQuery}"</p>
|
||||
</div>
|
||||
{:else if searchError}
|
||||
<!-- Search error -->
|
||||
<div class="text-center py-6 border border-red-200 bg-red-50 rounded">
|
||||
<p class="text-red-600">{searchError}</p>
|
||||
<button
|
||||
onclick={searchSheets}
|
||||
class="mt-2 px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700 transition"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
{:else if searchQuery && searchResults.length > 0}
|
||||
<!-- Search results -->
|
||||
<div class="grid gap-3">
|
||||
{#each searchResults as sheet}
|
||||
<button
|
||||
onclick={() => selectSheet(sheet)}
|
||||
class="p-4 text-left border border-gray-200 rounded hover:border-blue-500 transition {
|
||||
sheetsData.selectedSheet?.id === sheet.id ? 'border-blue-500 bg-blue-50' : ''
|
||||
}"
|
||||
>
|
||||
<div class="font-medium text-gray-900">
|
||||
{#if searchQuery}
|
||||
{#each sheet.name.split(new RegExp(`(${searchQuery})`, 'i')) as part}
|
||||
{#if part.toLowerCase() === searchQuery.toLowerCase()}
|
||||
<span class="bg-yellow-200">{part}</span>
|
||||
{:else}
|
||||
{part}
|
||||
{/if}
|
||||
{/each}
|
||||
{:else}
|
||||
{sheet.name}
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-sm text-gray-500">
|
||||
Modified: {new Date(sheet.modifiedTime).toLocaleDateString('en-GB', {day: '2-digit', month: '2-digit', year: 'numeric'})}
|
||||
</div>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Recent sheets (when not searching) -->
|
||||
<div class="grid gap-3">
|
||||
{#each sheetsData.availableSheets as sheet}
|
||||
<button
|
||||
@@ -92,11 +242,17 @@
|
||||
>
|
||||
<div class="font-medium text-gray-900">{sheet.name}</div>
|
||||
<div class="text-sm text-gray-500">
|
||||
Modified: {new Date(sheet.modifiedTime).toLocaleDateString()}
|
||||
Modified: {new Date(sheet.modifiedTime).toLocaleDateString('en-GB', {day: '2-digit', month: '2-digit', year: 'numeric'})}
|
||||
</div>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{#if sheetsData.availableSheets.length === 0 && !sheetsData.loading}
|
||||
<div class="text-center py-6 border border-gray-200 rounded">
|
||||
<p class="text-gray-500">No recent sheets found. Try searching above.</p>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -134,7 +290,7 @@
|
||||
aria-label={`Select data type for column ${index + 1}`}
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onchange={(e) => {
|
||||
const value = e.target.value;
|
||||
const value = (e.target as HTMLSelectElement).value;
|
||||
if (value === "none") return;
|
||||
|
||||
// Reset previous selection if this column was already mapped
|
||||
@@ -187,6 +343,7 @@
|
||||
sheetsData.columnMapping.confirmation === cellIndex + 1 ? 'font-medium text-amber-700' :
|
||||
'text-gray-700'
|
||||
}
|
||||
title={cell || ''}
|
||||
>
|
||||
{cell || ''}
|
||||
</span>
|
||||
@@ -197,7 +354,17 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="mt-2 text-sm text-gray-500">Showing first 10 rows</p>
|
||||
<div class="flex justify-between mt-2">
|
||||
<p class="text-sm text-gray-500">Showing first 10 rows</p>
|
||||
{#if sheetsData.sheetData[0] && sheetsData.sheetData[0].length > 3}
|
||||
<p class="text-sm text-gray-500">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 inline mr-1" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
Scroll horizontally to see all {sheetsData.sheetData[0].length} columns
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -211,3 +378,5 @@
|
||||
<p class="text-sm text-red-600">{errors.sheetData}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user