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

interface OrderItem {
  article_id: number;
  article_name: string;
  actual_price?: number | null;
  quantity: number;
}

interface OrderData {
  cart: OrderItem[];
  orderNote: string;
  totalPrice: number;
  tableName?: string | null;
}

// Function to generate a random order code (4 characters)
function generateOrderCode(): string {
  const characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Removed similar looking characters
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

// 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 {
    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: OrderData = await req.json();

    // Validate required fields
    const { cart, orderNote, totalPrice, tableName } = data;

    if (!cart || !Array.isArray(cart) || cart.length === 0) {
      return NextResponse.json(
        { message: 'Bad request: Missing or invalid cart data.' },
        { status: 400 }
      );
    }

    // Generate a unique order code
    const orderCode = generateOrderCode();

    // Format the message for Discord - simplified version
    const itemsList = cart.map(item => 
      `${item.quantity}x ${item.article_name} ${item.actual_price ? `${item.actual_price.toFixed(2)}лв` : ''}`
    ).join('\n');

    // Include table name in the header if available
    const tableInfo = tableName ? `📍 ${tableName} | ` : '';
    
    // 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'
      : '';
    
    const messageContent = [
      employeeTags,
      `${tableInfo}📋 **КОД: ${orderCode}**`,
      '',
      itemsList,
      '',
      orderNote ? `_${orderNote}_` : ''
    ].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: 'Orders 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 order to Discord.' },
        { status: 500 }
      );
    }

    // Return success along with the order code
    return NextResponse.json({ 
      message: 'Order submitted successfully',
      orderCode 
    }, { status: 200 });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json({ message: 'Server error.' }, { status: 500 });
  }
}