handle thumbnails (manual)
This commit is contained in:
@@ -65,6 +65,40 @@ export async function getUserProperties(): Promise<ActionResult<Property[]>> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific property by ID for the current user
|
||||
*/
|
||||
export async function getPropertyById(propertyId: string): Promise<ActionResult<Property | null>> {
|
||||
try {
|
||||
const session = await getSession()
|
||||
|
||||
if (!session?.user) {
|
||||
return { success: false, error: 'Not authenticated', data: null }
|
||||
}
|
||||
|
||||
const supabase = await createServerSupabaseClient()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('properties')
|
||||
.select(`*, address:properties_addresses(*)`)
|
||||
.eq('id', propertyId)
|
||||
.eq('owner_id', session.user.id)
|
||||
.single<Property>()
|
||||
|
||||
if (error) {
|
||||
return { success: false, error: error.message, data: null }
|
||||
}
|
||||
|
||||
return { success: true, data: data as Property }
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch property',
|
||||
data: null,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the active property for the current session
|
||||
*/
|
||||
@@ -891,3 +925,84 @@ export async function togglePropertyLike(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a thumbnail image to Supabase Storage and update the property
|
||||
*/
|
||||
export async function uploadPropertyThumbnail(
|
||||
propertyId: string,
|
||||
blob: Blob
|
||||
): Promise<{ success: true; data: { thumbnail_url: string } } | { success: false; error: string }> {
|
||||
try {
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Not authenticated' }
|
||||
}
|
||||
|
||||
// Validate file size (max 10MB)
|
||||
const MAX_SIZE = 10 * 1024 * 1024
|
||||
if (blob.size > MAX_SIZE) {
|
||||
return { success: false, error: `Image too large (${(blob.size / 1024 / 1024).toFixed(1)}MB). Maximum size is 10MB.` }
|
||||
}
|
||||
|
||||
const supabase = await createServerSupabaseClient()
|
||||
|
||||
// Verify the user owns this property
|
||||
const { data: property, error: propertyError } = await supabase
|
||||
.from('properties')
|
||||
.select('owner_id')
|
||||
.eq('id', propertyId)
|
||||
.single()
|
||||
|
||||
if (propertyError || !property) {
|
||||
return { success: false, error: 'Property not found' }
|
||||
}
|
||||
|
||||
if ((property as any).owner_id !== session.user.id) {
|
||||
return { success: false, error: 'Not authorized to update this property' }
|
||||
}
|
||||
|
||||
// Generate a unique filename
|
||||
const timestamp = Date.now()
|
||||
const filename = `${propertyId}/${timestamp}.png`
|
||||
|
||||
// Upload to Supabase Storage
|
||||
const { data: uploadData, error: uploadError } = await supabase.storage
|
||||
.from('property-thumbnails')
|
||||
.upload(filename, blob, {
|
||||
contentType: 'image/png',
|
||||
upsert: false,
|
||||
})
|
||||
|
||||
if (uploadError) {
|
||||
return { success: false, error: `Upload failed: ${uploadError.message}` }
|
||||
}
|
||||
|
||||
// Get the public URL
|
||||
const { data: urlData } = supabase.storage
|
||||
.from('property-thumbnails')
|
||||
.getPublicUrl(uploadData.path)
|
||||
|
||||
const thumbnailUrl = urlData.publicUrl
|
||||
|
||||
// Update the property with the new thumbnail URL
|
||||
const { error: updateError } = await (supabase
|
||||
.from('properties') as any)
|
||||
.update({ thumbnail_url: thumbnailUrl })
|
||||
.eq('id', propertyId)
|
||||
|
||||
if (updateError) {
|
||||
return { success: false, error: `Failed to update property: ${updateError.message}` }
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { thumbnail_url: thumbnailUrl },
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to upload thumbnail',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
getActiveProperty,
|
||||
getUserProperties,
|
||||
setActiveProperty as setActivePropertyAction,
|
||||
} from './actions'
|
||||
import type { Property } from './types'
|
||||
|
||||
interface UsePropertiesReturn {
|
||||
properties: Property[]
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
refetch: () => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch and manage user properties
|
||||
*/
|
||||
export function useProperties(): UsePropertiesReturn {
|
||||
const [properties, setProperties] = useState<Property[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const fetchProperties = useCallback(async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
const result = await getUserProperties()
|
||||
|
||||
if (result.success) {
|
||||
setProperties(result.data || [])
|
||||
} else {
|
||||
setError(result.error || 'Failed to fetch properties')
|
||||
setProperties([])
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An unexpected error occurred')
|
||||
setProperties([])
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchProperties()
|
||||
}, [fetchProperties])
|
||||
|
||||
return {
|
||||
properties,
|
||||
isLoading,
|
||||
error,
|
||||
refetch: fetchProperties,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch a single property by ID
|
||||
*/
|
||||
export function useProperty(propertyId: string | undefined) {
|
||||
const [property, setProperty] = useState<Property | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!propertyId) {
|
||||
setProperty(null)
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const fetchProperty = async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
const result = await getUserProperties()
|
||||
|
||||
if (result.success) {
|
||||
const found = result.data?.find((p) => p.id === propertyId)
|
||||
if (found) {
|
||||
setProperty(found)
|
||||
} else {
|
||||
setError('Property not found')
|
||||
setProperty(null)
|
||||
}
|
||||
} else {
|
||||
setError(result.error || 'Failed to fetch property')
|
||||
setProperty(null)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An unexpected error occurred')
|
||||
setProperty(null)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
fetchProperty()
|
||||
}, [propertyId])
|
||||
|
||||
return {
|
||||
property,
|
||||
isLoading,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to manage the active property for the current session
|
||||
*/
|
||||
export function useActiveProperty() {
|
||||
const [activeProperty, setActivePropertyState] = useState<Property | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isPending, setIsPending] = useState(false)
|
||||
const isInitialFetchRef = useRef(true)
|
||||
|
||||
const fetchActiveProperty = useCallback(async (allowAutoSelect = false) => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
const result = await getActiveProperty()
|
||||
|
||||
if (result.success) {
|
||||
setActivePropertyState(result.data || null)
|
||||
|
||||
// If no active property is set, automatically set the first property as active
|
||||
// Only do this on initial mount to avoid interfering with property selection/creation
|
||||
if (!result.data && allowAutoSelect) {
|
||||
console.log('[useActiveProperty] No active property, checking if we should auto-select')
|
||||
const propertiesResult = await getUserProperties()
|
||||
|
||||
if (
|
||||
propertiesResult.success &&
|
||||
propertiesResult.data &&
|
||||
propertiesResult.data.length > 0
|
||||
) {
|
||||
console.log('[useActiveProperty] Found properties, auto-selecting first one')
|
||||
const firstProperty = propertiesResult.data[0]
|
||||
if (firstProperty) {
|
||||
const setActiveResult = await setActivePropertyAction(firstProperty.id)
|
||||
|
||||
if (setActiveResult.success) {
|
||||
console.log('[useActiveProperty] Auto-selected property:', firstProperty.name)
|
||||
setActivePropertyState(firstProperty)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (!result.data && !allowAutoSelect) {
|
||||
console.log('[useActiveProperty] No active property but auto-select is disabled')
|
||||
}
|
||||
} else {
|
||||
setError(result.error || 'Failed to fetch active property')
|
||||
setActivePropertyState(null)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An unexpected error occurred')
|
||||
setActivePropertyState(null)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const changeActiveProperty = useCallback(
|
||||
async (propertyId: string | null) => {
|
||||
try {
|
||||
setIsPending(true)
|
||||
setIsLoading(true)
|
||||
const result = await setActivePropertyAction(propertyId)
|
||||
|
||||
if (result.success) {
|
||||
if (propertyId) {
|
||||
// Fetch the property data and set it immediately
|
||||
console.log('[useActiveProperty] Fetching property data for ID:', propertyId)
|
||||
const propertiesResult = await getUserProperties()
|
||||
|
||||
if (propertiesResult.success && propertiesResult.data) {
|
||||
const selectedProperty = propertiesResult.data.find(p => p.id === propertyId)
|
||||
if (selectedProperty) {
|
||||
console.log('[useActiveProperty] Found property, setting as active:', selectedProperty.name)
|
||||
console.log('[useActiveProperty] Current isLoading state:', isLoading)
|
||||
setActivePropertyState(selectedProperty)
|
||||
setIsLoading(false)
|
||||
console.log('[useActiveProperty] Set isLoading to false')
|
||||
} else {
|
||||
console.error('[useActiveProperty] Property not found in user properties')
|
||||
// Fall back to refetch
|
||||
await fetchActiveProperty(false)
|
||||
}
|
||||
} else {
|
||||
console.error('[useActiveProperty] Failed to fetch properties')
|
||||
// Fall back to refetch
|
||||
await fetchActiveProperty(false)
|
||||
}
|
||||
} else {
|
||||
setActivePropertyState(null)
|
||||
setIsLoading(false)
|
||||
}
|
||||
} else {
|
||||
console.error(result.error || 'Failed to update active property')
|
||||
setIsLoading(false)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'An unexpected error occurred')
|
||||
setIsLoading(false)
|
||||
} finally {
|
||||
setIsPending(false)
|
||||
}
|
||||
},
|
||||
[fetchActiveProperty],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// Only allow auto-select on the initial mount
|
||||
const allowAutoSelect = isInitialFetchRef.current
|
||||
if (isInitialFetchRef.current) {
|
||||
isInitialFetchRef.current = false
|
||||
}
|
||||
fetchActiveProperty(allowAutoSelect)
|
||||
}, [fetchActiveProperty])
|
||||
|
||||
return {
|
||||
activeProperty,
|
||||
isLoading,
|
||||
error,
|
||||
setActiveProperty: changeActiveProperty,
|
||||
isPending,
|
||||
refetch: fetchActiveProperty,
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import type { Property } from './types'
|
||||
import {
|
||||
getActiveProperty,
|
||||
getUserProperties,
|
||||
setActiveProperty as setActivePropertyAction,
|
||||
getPropertyById,
|
||||
} from './actions'
|
||||
|
||||
interface PropertyStore {
|
||||
@@ -65,44 +65,16 @@ export const usePropertyStore = create<PropertyStore>((set, get) => ({
|
||||
}
|
||||
},
|
||||
|
||||
// Set active property
|
||||
// Set active property by fetching it directly by ID (URL-based, no session update)
|
||||
setActiveProperty: async (propertyId: string) => {
|
||||
set({ isLoading: true })
|
||||
|
||||
// Update database
|
||||
const result = await setActivePropertyAction(propertyId)
|
||||
const result = await getPropertyById(propertyId)
|
||||
|
||||
if (result.success) {
|
||||
// Fetch properties to get the full property object
|
||||
const propertiesResult = await getUserProperties()
|
||||
|
||||
if (propertiesResult.success && propertiesResult.data) {
|
||||
const selectedProperty = propertiesResult.data.find(p => p.id === propertyId)
|
||||
|
||||
if (selectedProperty) {
|
||||
set({
|
||||
activeProperty: selectedProperty,
|
||||
properties: propertiesResult.data,
|
||||
isLoading: false,
|
||||
error: null
|
||||
})
|
||||
} else {
|
||||
set({
|
||||
isLoading: false,
|
||||
error: 'Property not found'
|
||||
})
|
||||
}
|
||||
} else {
|
||||
set({
|
||||
isLoading: false,
|
||||
error: 'Failed to fetch properties'
|
||||
})
|
||||
}
|
||||
if (result.success && result.data) {
|
||||
set({ activeProperty: result.data, isLoading: false, error: null })
|
||||
} else {
|
||||
set({
|
||||
isLoading: false,
|
||||
error: result.error || 'Failed to set active property'
|
||||
})
|
||||
set({ isLoading: false, error: result.error || 'Property not found' })
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user