get_col("SELECT * FROM {$db_restaurants}"); if (count($list) < 3){ $list_rest = ['Madrid', 'New York', 'Paris', 'Hong Kong', 'Beijing', 'Oslo', 'Roma']; foreach($list_rest as $name){ self::restaurant($name); } } $db_bookings = SRR_DB_Bookings::$table_db; $list = $wpdb->get_col("SELECT * FROM {$db_bookings}"); $count_restaurants = count($wpdb->get_col("SELECT * FROM {$db_restaurants}")); // Generate 500 bookings //if (count($list) < 500){ // for ($i = 0; $i < 500; $i++){ // self::booking(rand(1,$count_restaurants)); // } //} } /** * Crea un restaurante con el nombre especificado * * @param string $name Nombre del restaurante */ public static function restaurant($name) { global $wpdb; $wpdb->insert(SRR_DB_Restaurants::$table_db, [ 'name' => $name, 'date_created' => date('Y-m-d h:i:s'), 'date_modified' => date('Y-m-d h:i:s') ]); } /** * Genera múltiples reservas para un restaurante en un rango de fechas * * @param int $count Número de reservas a generar * @param int $restaurant_id ID del restaurante * @param string $date_start Fecha de inicio en formato Y-m-d * @param string $date_end Fecha final en formato Y-m-d * @param int $lunch_id ID del turno de almuerzo (default: 17) * @param int $dinner_id ID del turno de cena (default: 22) * @return array Array con los IDs de las reservas generadas */ public static function generateBookings($count, $restaurant_id, $date_start, $date_end, $lunch_id = 17, $dinner_id = 22) { $booking_ids = []; // Convertir fechas a timestamps para calcular el rango $timestamp_start = strtotime($date_start); $timestamp_end = strtotime($date_end); if ($timestamp_end < $timestamp_start) { // Intercambiar si el orden está invertido $temp = $timestamp_start; $timestamp_start = $timestamp_end; $timestamp_end = $temp; } // Calcular el rango de días $range_in_seconds = $timestamp_end - $timestamp_start; // Asegurarnos de que hay tags disponibles $available_tags = \Alexr\Models\BTag::where('restaurant_id', $restaurant_id)->get(); // Si no hay tags, intentar crear algunos predefinidos if (count($available_tags) == 0) { self::createDefaultTagsIfNeeded($restaurant_id); } // Asegurarnos de que hay tags de cliente disponibles $available_customer_tags = \Alexr\Models\CTag::where('restaurant_id', $restaurant_id)->get(); // Si no hay tags de cliente, intentar crear algunos predefinidos if (count($available_customer_tags) == 0) { self::createDefaultCustomerTagsIfNeeded($restaurant_id); } for ($i = 0; $i < $count; $i++) { // Generar una fecha aleatoria dentro del rango $random_offset = rand(0, $range_in_seconds); $random_date = date('Y-m-d', $timestamp_start + $random_offset); // Crear la reserva con la fecha generada, pasando los IDs de los turnos $booking = self::booking($restaurant_id, $random_date, $lunch_id, $dinner_id); if ($booking) { $booking_ids[] = $booking->id; } } return $booking_ids; } /** * Crea grupos de tags predefinidos si no existen * * @param int $restaurant_id ID del restaurante */ private static function createDefaultTagsIfNeeded($restaurant_id) { // Verificar si ya existen tags $existing_tags = \Alexr\Models\BTag::where('restaurant_id', $restaurant_id)->count(); if ($existing_tags > 0) { return; // Ya existen tags, no hacemos nada } // Crear grupos predefinidos $tag_groups = [ 'VIP' => ['Gold Member', 'Platinum Member', 'Diamond Member'], 'Occasion' => ['Birthday', 'Anniversary', 'Business Meeting', 'Celebration'], 'Preferences' => ['Window Table', 'Quiet Area', 'Outdoor Seating', 'Near Bar'], 'Dietary' => ['Vegetarian', 'Vegan', 'Gluten Free', 'Dairy Free', 'Allergies'], 'Frequency' => ['First Time', 'Regular', 'Weekly', 'Monthly'] ]; foreach ($tag_groups as $group_name => $tags) { // Crear el grupo $group = new \Alexr\Models\BTagGroup([ 'restaurant_id' => $restaurant_id, 'name' => $group_name, 'ordering' => 999, 'color' => '#FFFFFF', 'backcolor' => '#' . substr(md5($group_name), 0, 6), // Color aleatorio basado en el nombre 'is_deletable' => 1, 'is_vip' => ($group_name == 'VIP') ? 1 : 0, 'is_private' => 0, 'notes' => 'Auto-generated group' ]); $group->save(); // Crear los tags para este grupo foreach ($tags as $tag_name) { $tag = new \Alexr\Models\BTag([ 'restaurant_id' => $restaurant_id, 'group_id' => $group->id, 'name' => $tag_name, 'ordering' => 999, 'is_deletable' => 1, 'notes' => 'Auto-generated tag' ]); $tag->save(); } } } /** * Crea grupos de tags de clientes predefinidos si no existen * * @param int $restaurant_id ID del restaurante */ private static function createDefaultCustomerTagsIfNeeded($restaurant_id) { // Verificar si ya existen tags de cliente $existing_customer_tags = \Alexr\Models\CTag::where('restaurant_id', $restaurant_id)->count(); if ($existing_customer_tags > 0) { return; // Ya existen tags, no hacemos nada } // Crear grupos predefinidos para clientes $tag_groups = [ 'Loyalty' => ['Bronze', 'Silver', 'Gold', 'Platinum'], 'Interests' => ['Wine Lover', 'Foodie', 'Cocktail Enthusiast', 'Fine Dining'], 'Spending' => ['High Spender', 'Regular Spender', 'Low Spender'], 'Source' => ['Website', 'Phone', 'Walk-in', 'Social Media', 'Referral'], 'Status' => ['Active', 'Inactive', 'Blacklisted', 'VIP'] ]; foreach ($tag_groups as $group_name => $tags) { // Crear el grupo $group = new \Alexr\Models\CTagGroup([ 'restaurant_id' => $restaurant_id, 'name' => $group_name, 'ordering' => 999, 'color' => '#FFFFFF', 'backcolor' => '#' . substr(md5($group_name . 'c'), 0, 6), // Color aleatorio 'is_deletable' => 1, 'is_vip' => ($group_name == 'Status') ? 1 : 0, 'notes' => 'Auto-generated customer group' ]); $group->save(); // Crear los tags para este grupo foreach ($tags as $tag_name) { $tag = new \Alexr\Models\CTag([ 'restaurant_id' => $restaurant_id, 'group_id' => $group->id, 'name' => $tag_name, 'ordering' => 999, 'is_deletable' => 1, 'notes' => 'Auto-generated customer tag' ]); $tag->save(); } } } /** * Crea una reserva con datos aleatorios * * @param int $restaurant_id ID del restaurante * @param string|null $date Fecha opcional para la reserva (formato Y-m-d) * @param int $lunch_id ID del turno de almuerzo * @param int $dinner_id ID del turno de cena * @return \Alexr\Models\Booking|null La reserva creada o null si falla */ public static function booking($restaurant_id, $date = null, $lunch_id = 17, $dinner_id = 22) { global $wpdb; // Generar nombre aleatorio list($first_name, $last_name) = self::getRandomName(); $name = $first_name . ' ' . $last_name; // Generar horas aleatorias si no se especificó fecha $random_hours_ahead = -rand(24, 720 * 24) * 3600; // Generar email a partir del nombre $email = strtolower(str_replace(' ', '.', $name)) . '@gmail.com'; // Obtener o crear cliente $customer_id = self::get_customer($name, $email, $restaurant_id); // Usar fecha proporcionada o generar una aleatoria if (!$date) { $date = date('Y-m-d', time() + $random_hours_ahead); } // Generar tamaño del grupo (party) según distribución requerida // 85% de las reservas serán de 2 comensales // 15% de las reservas serán de 3-6 comensales $party_distribution = rand(1, 100); if ($party_distribution <= 85) { // 85% de las veces: 2 comensales $party = 2; $duration = 5400; // 1h 30min = 90min = 5400 segundos } else { // 15% de las veces: 3-6 comensales $party = rand(3, 6); $duration = 7200; // 2h = 120min = 7200 segundos } // Determinar si es Lunch o Dinner y ajustar la hora $is_lunch = (rand(0, 1) == 0); $shift_name = $is_lunch ? 'Lunch' : 'Dinner'; $shift_id = $is_lunch ? $lunch_id : $dinner_id; // Usar los IDs proporcionados // Ajustar la hora según el turno - múltiplos de 15 minutos (900 segundos) // Para lunch: entre 12:00 (720 minutos) y 15:00 (900 minutos) // Para dinner: entre 17:00 (1020 minutos) y 22:00 (1320 minutos) if ($is_lunch) { // Generar valores entre 12:00 y 15:00 en intervalos de 15 minutos $minutes_options = []; for ($i = 720; $i <= 900; $i += 15) { $minutes_options[] = $i; } $selected_minutes = $minutes_options[array_rand($minutes_options)]; $time = 60 * $selected_minutes; // Convertir a segundos } else { // Generar valores entre 17:00 y 22:00 en intervalos de 15 minutos $minutes_options = []; for ($i = 1020; $i <= 1320; $i += 15) { $minutes_options[] = $i; } $selected_minutes = $minutes_options[array_rand($minutes_options)]; $time = 60 * $selected_minutes; // Convertir a segundos } // Determinar el estado de la reserva según las probabilidades requeridas // 20% pending, 40% booked, 30% confirmed, 10% cancelled $random_status = rand(1, 100); if ($random_status <= 20) { $status = \Alexr\Enums\BookingStatus::PENDING; } elseif ($random_status <= 60) { // 20+40=60 $status = \Alexr\Enums\BookingStatus::BOOKED; } elseif ($random_status <= 90) { // 60+30=90 $status = \Alexr\Enums\BookingStatus::CONFIRMED; } else { // 90-100 $status = \Alexr\Enums\BookingStatus::CANCELLED; } // Preparar datos de la reserva $args = [ 'restaurant_id' => $restaurant_id, 'customer_id' => $customer_id, 'type' => \Alexr\Enums\BookingType::ONLINE, // inhouse, online 'date' => $date, 'time' => $time, 'party' => $party, 'duration' => $duration, // Duración basada en el tamaño del grupo 'first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, 'dial_code_country' => 'US', 'dial_code' => '1', 'phone' => '6' . rand(100000000, 999999999), 'status' => $status, 'spend' => $party * rand(25, 80), 'notes' => rand(1, 3) == 1 ? 'Customer requested a window table' : (rand(1, 3) == 2 ? 'Celebrating a birthday' : 'No special requests'), 'date_created' => date('Y-m-d H:i:s'), 'date_modified' => date('Y-m-d H:i:s'), 'shift_event_id' => $shift_id, 'shift_event_name' => $shift_name ]; try { // Crear la reserva $booking = new \Alexr\Models\Booking($args); $booking->save(); // Agregar tags aleatorios self::addRandomTags($booking, $restaurant_id); return $booking; } catch (\Exception $e) { // Registrar error si es necesario error_log('Error creating booking: ' . $e->getMessage()); return null; } } /** * Obtiene un cliente existente o crea uno nuevo * * @param string $name Nombre completo * @param string $email Email * @param int $restaurant_id ID del restaurante * @return int ID del cliente */ public static function get_customer($name, $email, $restaurant_id) { global $wpdb; $table_name = SRR_DB_Customers::$table_db; $sql = "SELECT id FROM {$table_name} WHERE email='{$email}' AND restaurant_id='{$restaurant_id}' LIMIT 1"; $id = $wpdb->get_var($sql); // Cliente existe, devolvemos el ID if ($id) { return $id; } // Cliente no existe, lo creamos $visits = rand(1, 40); $spend = $visits * rand(30, 200); $spend_per_visit = intval($spend / $visits); $names = explode(' ', $name); if (is_array($names) && count($names) >= 2) { $f_name = $names[0]; $l_name = $names[1]; } else { $f_name = $name; $l_name = ''; } // Generar fecha de cumpleaños aleatoria (entre 21 y 70 años) $year = date('Y') - rand(21, 70); $month = rand(1, 12); $day = rand(1, 28); // Evita problemas con febrero $birthday = sprintf('%04d-%02d-%02d', $year, $month, $day); $params = [ 'restaurant_id' => $restaurant_id, 'company' => self::$companies[array_rand(self::$companies)], 'email' => $email, 'first_name' => $f_name, 'last_name' => $l_name, 'name' => $name, 'visits' => $visits, 'spend' => $spend, 'spend_per_visit' => $spend_per_visit, 'gender' => rand(1, 10) < 6 ? 'male' : 'female', 'birthday' => $birthday, 'country_code' => 'US', 'dial_code' => '1', 'phone' => '6' . rand(100000000, 999999999), 'date_created' => date('Y-m-d H:i:s'), 'date_modified' => date('Y-m-d H:i:s'), ]; $wpdb->insert($table_name, $params); $id = $wpdb->get_var($sql); // Verificar primero si existen etiquetas de cliente $available_customer_tags = \Alexr\Models\CTag::where('restaurant_id', $restaurant_id)->get(); // Si no hay etiquetas, crear algunas predeterminadas if (count($available_customer_tags) == 0) { self::createDefaultCustomerTagsIfNeeded($restaurant_id); // Obtener las etiquetas recién creadas $available_customer_tags = \Alexr\Models\CTag::where('restaurant_id', $restaurant_id)->get(); } // Asignar etiquetas al cliente si hay disponibles if (count($available_customer_tags) > 0) { self::addRandomTagsToCustomer($id, $restaurant_id); } return $id; } /** * Agrega tags aleatorios a una reserva * * @param \Alexr\Models\Booking $booking La reserva * @param int $restaurant_id ID del restaurante */ private static function addRandomTags($booking, $restaurant_id) { // Obtener tags disponibles para el restaurante usando el modelo BTag $available_tags = \Alexr\Models\BTag::where('restaurant_id', $restaurant_id)->get(); // Si no hay tags disponibles, salir if (count($available_tags) == 0) { return; } // Convertir la colección a array para facilitar la selección aleatoria $available_tag_ids = []; foreach ($available_tags as $tag) { $available_tag_ids[] = $tag->id; } // Seleccionar 1-3 tags aleatorios $num_tags = rand(1, 3); // Asegurarnos de no seleccionar más tags de los disponibles $num_tags = min($num_tags, count($available_tag_ids)); // Seleccionar tags aleatorios $selected_tag_ids = []; $shuffled_tags = $available_tag_ids; shuffle($shuffled_tags); $selected_tag_ids = array_slice($shuffled_tags, 0, $num_tags); // Sincronizar los tags con la reserva if (!empty($selected_tag_ids)) { $booking->tags()->sync($selected_tag_ids); } } /** * Agrega tags aleatorios a un cliente * * @param int $customer_id ID del cliente * @param int $restaurant_id ID del restaurante */ private static function addRandomTagsToCustomer($customer_id, $restaurant_id) { global $wpdb; // Obtener tags disponibles para el restaurante usando el modelo CTag $available_tags = \Alexr\Models\CTag::where('restaurant_id', $restaurant_id)->get(); // Si no hay tags disponibles, salir if (count($available_tags) == 0) { return; } // Convertir la colección a array para facilitar la selección aleatoria $available_tag_ids = []; foreach ($available_tags as $tag) { $available_tag_ids[] = $tag->id; } // Seleccionar 2-3 tags aleatorios $num_tags = rand(0, 2); if ($num_tags == 0) { return; } // Asegurarnos de no seleccionar más tags de los disponibles $num_tags = min($num_tags, count($available_tag_ids)); // Seleccionar tags aleatorios $selected_tag_ids = []; $shuffled_tags = $available_tag_ids; shuffle($shuffled_tags); $selected_tag_ids = array_slice($shuffled_tags, 0, $num_tags); $customer = \Alexr\Models\Customer::find($customer_id); if ($customer) { $customer->tags()->sync($selected_tag_ids); } } }