vkashti-bots / supabase / reservationsHelper.js
reservationsHelper.js
Raw
import { createClient } from '@supabase/supabase-js'
import dotenv from 'dotenv'

dotenv.config()

// Initialize Supabase client
if (!process.env.SUPABASE_URL || !process.env.SUPABASE_ANON_KEY) {
  throw new Error('Missing Supabase environment variables');
}

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_ANON_KEY
)

/* 
  ******************************
  ***** RESERVATION METHODS ****
  ******************************
  The 'reservations' table columns (based on your screenshot):
  - id (int8)
  - created_at (timestamptz)
  - person_name (text)
  - phone (text)
  - from_date (timestamptz)
  - to_date (timestamptz)
  - persons (int4)
  - caparo (int8)
  - description (text)
*/

/**
 * Fetch reservations within a period of days.
 * @param {string} startDate - Start date (in ISO or any comparable format).
 * @param {string} endDate - End date (in ISO or any comparable format).
 * @returns {Promise<{ data?: Array, error?: string }>}
 */
export async function getReservationsForPeriod(startDate, endDate) {
  try {
    console.log('Fetching reservations for period:', startDate, endDate)
    
    if (!startDate || !endDate) {
      throw new Error('Invalid date range provided.')
    }

    // Adjust the logic to handle the start and end of the day
    const startOfDay = new Date(startDate).setHours(0, 0, 0, 0)
    const endOfDay = new Date(endDate).setHours(23, 59, 59, 999)

    const { data, error } = await supabase
      .from('reservations')
      .select('*')
      .gte('from_date', new Date(startOfDay).toISOString())
      .lte('from_date', new Date(endOfDay).toISOString())

    console.log('Data:', data)
    console.log('Error:', error)

    if (error) {
      console.error('Error fetching reservations:', error)
      return { error: 'Error fetching reservations.' }
    }

    return { data }
  } catch (error) {
    console.error('Error in getReservationsForPeriod:', error)
    return { error: 'Unexpected error occurred.' }
  }
}

/**
 * Fetch all reservations.
 * @returns {Promise<{ data?: Array, error?: string }>}
 */
export async function getAllReservations() {
  try {
    const { data, error } = await supabase
      .from('reservations')
      .select('*')

    if (error) {
      console.error('Error fetching reservations:', error)
      return { error: 'Error fetching reservations.' }
    }

    return { data }
  } catch (error) {
    console.error('Error in getAllReservations:', error)
    return { error: 'Unexpected error occurred.' }
  }
}

/**
 * Create a new reservation.
 * @param {Object} reservationData
 * {
 *   person_name: string,
 *   phone: string,
 *   from_date: string (timestamp/ISO),
 *   to_date: string (timestamp/ISO),
 *   persons: number,
 *   caparo: number,
 *   description: string
 * }
 * @returns {Promise<{ success: boolean, error?: string }>}
 */
export async function createReservation(reservationData) {
  try {
    const { error } = await supabase.from('reservations').insert({
      ...reservationData,
      created_at: new Date().toISOString(),
    })

    if (error) {
      console.error('Error creating reservation:', error)
      return { success: false, error: 'Error creating reservation.' }
    }

    return { success: true }
  } catch (error) {
    console.error('Error in createReservation:', error)
    return { success: false, error: 'Unexpected error occurred.' }
  }
}

/**
 * Edit an existing reservation (by ID).
 * @param {number} reservationId - The reservation’s ID.
 * @param {Object} updates - Key/value pairs of columns to update.
 * @returns {Promise<{ success: boolean, error?: string }>}
 */
export async function editReservation(reservationId, updates) {
  try {
    // Example: Only update fields that are explicitly passed in 'updates'
    // (e.g., person_name, phone, from_date, to_date, etc.)
    const { error } = await supabase
      .from('reservations')
      .update(updates)
      .eq('id', reservationId)

    if (error) {
      console.error('Error updating reservation:', error)
      return { success: false, error: 'Error updating reservation.' }
    }

    return { success: true }
  } catch (error) {
    console.error('Error in editReservation:', error)
    return { success: false, error: 'Unexpected error occurred.' }
  }
}

/**
 * Update an existing reservation (by ID).
 * @param {number} reservationId - The reservation’s ID.
 * @param {Object} updates - Key/value pairs of columns to update.
 * @returns {Promise<{ success: boolean, error?: string }>}
 */
export async function updateReservation(reservationId, updates) {
  try {
    const { error } = await supabase
      .from('reservations')
      .update(updates)
      .eq('id', reservationId)

    if (error) {
      console.error('Error updating reservation:', error)
      return { success: false, error: 'Error updating reservation.' }
    }

    return { success: true }
  } catch (error) {
    console.error('Error in updateReservation:', error)
    return { success: false, error: 'Unexpected error occurred.' }
  }
}

/**
 * Delete a reservation by ID.
 * @param {number} reservationId - The reservation’s ID.
 * @returns {Promise<{ success: boolean, error?: string }>}
 */
export async function deleteReservation(reservationId) {
  try {
    const { error } = await supabase
      .from('reservations')
      .delete()
      .eq('id', reservationId)

    if (error) {
      console.error('Error deleting reservation:', error)
      return { success: false, error: 'Error deleting reservation.' }
    }

    return { success: true }
  } catch (error) {
    console.error('Error in deleteReservation:', error)
    return { success: false, error: 'Unexpected error occurred.' }
  }
}