vkashti / app / api / bill / route.ts
route.ts
Raw
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/utils/supabase/server';

interface BillRequestData {
  tableName?: string | null;
  tableId?: string | null;
  paymentMethod: 'cash' | 'card';
}

// Function to fetch currently working employees with their Discord IDs
async function fetchCurrentlyWorkingEmployees() {
  const supabase = createClient();
  const now = new Date().toISOString();
  
  // First get the user_ids of employees currently working
  const { data: scheduleData, error: scheduleError } = await supabase
    .from('schedules')
    .select('user_id')
    .lte('start_time', now)
    .gte('end_time', now);
  
  if (scheduleError) {
    console.error('Error fetching schedules:', scheduleError.message);
    return [];
  }
  
  if (!scheduleData || scheduleData.length === 0) {
    return [];
  }
  
  // Get discord_ids from profiles table for the working employees
  const userIds = scheduleData
    .map(schedule => schedule.user_id)
    .filter(Boolean) as string[];
  
  const { data: profilesData, error: profilesError } = await supabase
    .from('profiles')
    .select('discord_id')
    .in('user_id', userIds)
    .not('discord_id', 'is', null);
  
  if (profilesError) {
    console.error('Error fetching profiles:', profilesError.message);
    return [];
  }
  
  // Return only the discord_ids (filtering out null values)
  return profilesData
    .map(profile => profile.discord_id)
    .filter(Boolean);
}

export async function POST(req: NextRequest) {
  try {
    // We're using the same webhook as orders
    const webhookUrl = process.env.DISCORD_ORDERS_WEBHOOK_URL;

    // Handle the case where webhookUrl is not set
    if (!webhookUrl) {
      console.error('Discord orders webhook URL is not set in environment variables.');
      return NextResponse.json(
        { message: 'Server error: Discord webhook URL is not configured.' },
        { status: 500 }
      );
    }

    const data: BillRequestData = await req.json();

    // Validate table information
    const { tableName, tableId, paymentMethod } = data;

    if (!tableName || !tableId) {
      return NextResponse.json(
        { message: 'Bad request: Missing table information.' },
        { status: 400 }
      );
    }

    // Get currently working employees to tag them
    const workingEmployeeDiscordIds = await fetchCurrentlyWorkingEmployees();
    
    // Create the employee tags if there are any
    const employeeTags = workingEmployeeDiscordIds.length > 0 
      ? workingEmployeeDiscordIds.map(id => `<@${id}>`).join(' ') + '\n\n'
      : '';

    // Format payment method for display
    const paymentMethodDisplay = paymentMethod === 'cash' ? '💵 В БРОЙ' : '💳 КАРТА';
    
    // Prepare the message content
    const messageContent = [
      employeeTags,
      `### 🧾 **ИСКАНЕ ЗА СМЕТКА**`,
      ``,
      `📍 **Маса:** ${tableName}`,
      `💰 **Начин на плащане:** ${paymentMethodDisplay}`,
    ].filter(Boolean).join('\n');

    // Send the message to Discord via the webhook
    const discordResponse = await fetch(webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        content: messageContent,
        username: 'Bill Request Bot',
        avatar_url: 'https://www.vkashti.bar/logo.png'
      })
    });

    if (!discordResponse.ok) {
      console.error(
        'Failed to send message to Discord webhook:',
        discordResponse.statusText
      );
      return NextResponse.json(
        { message: 'Error sending bill request to Discord.' },
        { status: 500 }
      );
    }

    // Return success
    return NextResponse.json({ 
      message: 'Bill request submitted successfully'
    }, { status: 200 });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json({ message: 'Server error.' }, { status: 500 });
  }
}