""" Blog Seeder Seeds the database with blog posts All images are from Unsplash (free stock photos) """ import json import sys import re from pathlib import Path from datetime import datetime, timezone, timedelta # Add parent directory to path to import modules sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from sqlalchemy.orm import Session from src.shared.config.database import SessionLocal from src.shared.config.logging_config import get_logger from src.content.models.blog import BlogPost from src.auth.models.user import User # Import all models to ensure relationships are loaded correctly from src.models import * logger = get_logger(__name__) def slugify(text): """Convert text to URL-friendly slug""" text = text.lower() text = re.sub(r'[^\w\s-]', '', text) text = re.sub(r'[-\s]+', '-', text) return text.strip('-') def get_blog_posts_data(author_id: int): """Generate comprehensive blog posts data with Unsplash images""" now = datetime.now(timezone.utc) posts = [ { 'title': '10 Tips for Planning the Perfect Luxury Hotel Stay', 'slug': '10-tips-planning-perfect-luxury-hotel-stay', 'excerpt': 'Discover expert tips to make your luxury hotel experience unforgettable. From booking strategies to maximizing amenities, we share insider secrets.', 'content': '''

Planning a luxury hotel stay requires attention to detail and insider knowledge. Whether you're celebrating a special occasion or simply treating yourself, these tips will help you make the most of your experience.

1. Book in Advance

Luxury hotels often offer early bird discounts and better room availability when you book well in advance. Planning ahead also gives you access to special packages and upgrades.

2. Communicate Your Preferences

Don't hesitate to communicate your preferences when booking. Whether you prefer a high floor, specific room amenities, or have dietary restrictions, hotels are happy to accommodate.

3. Join Loyalty Programs

Most luxury hotels offer loyalty programs with exclusive benefits. Join before your stay to earn points, receive member rates, and enjoy perks like late checkout.

4. Explore Hotel Amenities

Take advantage of all the hotel has to offer - from spa treatments to fine dining. Many luxury hotels have world-class facilities that are worth experiencing.

5. Use Concierge Services

The concierge team is your gateway to the best local experiences. They can secure restaurant reservations, arrange transportation, and provide insider recommendations.

6. Check for Special Packages

Look for special packages that bundle accommodations with dining, spa, or local experiences. These often provide better value than booking separately.

7. Review Cancellation Policies

Understand the cancellation and modification policies before booking. Flexible rates may cost more but provide peace of mind.

8. Pack Appropriately

While luxury hotels provide many amenities, bringing appropriate attire for dining and activities ensures you're prepared for all experiences.

9. Arrive Early or Late

If possible, arrive early or late to avoid peak check-in times. This often results in better service and sometimes room upgrades if available.

10. Leave Reviews

Share your experience through reviews. Hotels value feedback and often reward guests who provide detailed, constructive reviews.

Remember, a luxury hotel stay is about creating memories. Take your time, enjoy every moment, and don't hesitate to ask for what will make your stay perfect.

''', 'featured_image': 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=1200&h=800&fit=crop', 'author_id': author_id, 'published_at': now - timedelta(days=5), 'is_published': True, 'tags': json.dumps(['travel tips', 'luxury travel', 'hotel guide', 'vacation planning']), 'meta_title': '10 Tips for Planning the Perfect Luxury Hotel Stay | Travel Guide', 'meta_description': 'Expert tips for planning an unforgettable luxury hotel stay. Learn booking strategies, how to maximize amenities, and insider secrets.', 'meta_keywords': 'luxury hotel tips, hotel booking guide, travel planning, luxury travel advice', 'sections': None }, { 'title': 'The Art of Fine Dining: A Culinary Journey at Our Hotel', 'slug': 'art-fine-dining-culinary-journey', 'excerpt': 'Explore our award-winning restaurants and discover the culinary philosophy behind our Michelin-starred dining experiences.', 'content': '''

Fine dining is an art form that combines exceptional ingredients, masterful technique, and impeccable service. At our hotel, we've created culinary experiences that celebrate both tradition and innovation.

Our Culinary Philosophy

Our chefs believe in using the finest locally sourced ingredients, supporting sustainable practices, and creating dishes that tell a story. Each plate is a masterpiece, carefully crafted to delight all senses.

Signature Dishes

From our signature truffle risotto to our perfectly aged wagyu beef, every dish on our menu has been thoughtfully created. Our tasting menus offer a journey through flavors, textures, and culinary traditions.

Wine Pairing Excellence

Our sommeliers curate wine pairings that enhance every dish. With an extensive cellar featuring rare vintages and hidden gems, we ensure the perfect complement to your meal.

Private Dining Experiences

For special occasions, our private dining rooms offer intimate settings with personalized menus. Our chefs work closely with guests to create unforgettable culinary experiences.

Join us for a culinary journey that celebrates the art of fine dining and creates memories that last a lifetime.

''', 'featured_image': 'https://images.unsplash.com/photo-1414235077428-338989a2e8c0?w=1200&h=800&fit=crop', 'author_id': author_id, 'published_at': now - timedelta(days=10), 'is_published': True, 'tags': json.dumps(['fine dining', 'culinary', 'restaurant', 'gourmet']), 'meta_title': 'The Art of Fine Dining | Culinary Excellence', 'meta_description': 'Discover our award-winning restaurants and Michelin-starred dining experiences. Explore our culinary philosophy and signature dishes.', 'meta_keywords': 'fine dining, Michelin restaurant, gourmet cuisine, culinary experience', 'sections': None }, { 'title': 'Wellness and Relaxation: Your Guide to Our Spa & Wellness Center', 'slug': 'wellness-relaxation-spa-wellness-center-guide', 'excerpt': 'Discover our world-class spa and wellness center. Learn about our treatments, wellness programs, and how to achieve ultimate relaxation.', 'content': '''

In today's fast-paced world, taking time for wellness and relaxation is essential. Our spa and wellness center offers a sanctuary where you can rejuvenate your mind, body, and spirit.

Our Wellness Philosophy

We believe in holistic wellness that addresses physical, mental, and emotional well-being. Our treatments combine traditional techniques with modern innovations to provide comprehensive care.

Signature Treatments

From our signature deep tissue massages to rejuvenating facials, each treatment is customized to your needs. Our expert therapists use premium products and time-tested techniques.

Wellness Programs

Beyond individual treatments, we offer comprehensive wellness programs including yoga classes, meditation sessions, and personalized fitness consultations.

The Spa Environment

Our spa facilities include steam rooms, saunas, relaxation lounges, and private treatment rooms. Every detail is designed to create a serene, peaceful atmosphere.

Couples Experiences

Share the relaxation experience with our couples treatments. Perfect for romantic getaways or celebrating special moments together.

Whether you're seeking stress relief, muscle recovery, or simply a moment of tranquility, our spa and wellness center provides the perfect escape.

''', 'featured_image': 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=1200&h=800&fit=crop', 'author_id': author_id, 'published_at': now - timedelta(days=15), 'is_published': True, 'tags': json.dumps(['spa', 'wellness', 'relaxation', 'self-care']), 'meta_title': 'Wellness and Relaxation Guide | Spa & Wellness Center', 'meta_description': 'Discover our world-class spa and wellness center. Learn about treatments, wellness programs, and how to achieve ultimate relaxation.', 'meta_keywords': 'spa, wellness, relaxation, massage, hotel spa', 'sections': None }, { 'title': 'Sustainable Luxury: Our Commitment to Environmental Responsibility', 'slug': 'sustainable-luxury-environmental-responsibility', 'excerpt': 'Learn about our sustainability initiatives and how we balance luxury with environmental responsibility. Discover our green practices and commitment to the planet.', 'content': '''

Luxury and sustainability are not mutually exclusive. At our hotel, we've proven that you can enjoy world-class amenities while protecting the environment for future generations.

Our Sustainability Mission

We're committed to reducing our environmental footprint through innovative practices, renewable energy, and responsible sourcing. Our goal is carbon neutrality while maintaining the highest standards of luxury.

Green Building Practices

Our facilities incorporate energy-efficient systems, water conservation measures, and sustainable materials. We continuously invest in technologies that reduce our environmental impact.

Local and Sustainable Sourcing

We prioritize local suppliers and sustainable ingredients in our restaurants. This not only reduces our carbon footprint but also supports local communities and ensures the freshest quality.

Waste Reduction

Through comprehensive recycling programs, composting, and waste reduction initiatives, we've significantly decreased our waste output. Single-use plastics have been eliminated throughout the property.

Guest Participation

We invite guests to join us in our sustainability efforts through optional programs like towel reuse, energy conservation, and supporting local conservation projects.

Together, we can enjoy luxury experiences while protecting our planet. Every small action contributes to a more sustainable future.

''', 'featured_image': 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=1200&h=800&fit=crop', 'author_id': author_id, 'published_at': now - timedelta(days=20), 'is_published': True, 'tags': json.dumps(['sustainability', 'environment', 'green hotel', 'eco-friendly']), 'meta_title': 'Sustainable Luxury | Environmental Responsibility', 'meta_description': 'Learn about our sustainability initiatives and how we balance luxury with environmental responsibility. Discover our green practices.', 'meta_keywords': 'sustainable luxury, green hotel, environmental responsibility, eco-friendly', 'sections': None }, { 'title': 'Celebrating 30 Years of Excellence in Hospitality', 'slug': 'celebrating-30-years-excellence-hospitality', 'excerpt': 'Join us as we celebrate three decades of providing exceptional hospitality. Learn about our journey, milestones, and vision for the future.', 'content': '''

This year marks a significant milestone - 30 years of excellence in hospitality. From our humble beginnings to becoming an internationally recognized destination, our journey has been remarkable.

Our Beginnings

Founded in 1993, we started with a simple vision: to create a sanctuary of luxury and sophistication. What began as a small boutique property has grown into a world-class destination.

Key Milestones

Over three decades, we've achieved numerous milestones - from our first five-star rating to receiving international awards. Each achievement represents our commitment to excellence.

Our Team

None of this would be possible without our dedicated team. Their passion, professionalism, and commitment to service excellence have been the foundation of our success.

Looking Forward

As we celebrate this milestone, we're also looking to the future. We continue to innovate, invest in our facilities, and enhance our services to exceed guest expectations.

Thank You

To all our guests, partners, and team members - thank you for being part of our journey. Here's to the next 30 years of creating unforgettable experiences.

Join us in celebrating this special anniversary with special packages and events throughout the year.

''', 'featured_image': 'https://images.unsplash.com/photo-1520250497591-112f2f40a3f4?w=1200&h=800&fit=crop', 'author_id': author_id, 'published_at': now - timedelta(days=25), 'is_published': True, 'tags': json.dumps(['anniversary', 'hotel history', 'milestone', 'celebration']), 'meta_title': 'Celebrating 30 Years of Excellence | Hotel Anniversary', 'meta_description': 'Join us as we celebrate three decades of providing exceptional hospitality. Learn about our journey, milestones, and vision for the future.', 'meta_keywords': 'hotel anniversary, 30 years, hospitality excellence, milestone', 'sections': None }, { 'title': 'The Ultimate Business Traveler\'s Guide to Our Hotel', 'slug': 'ultimate-business-traveler-guide', 'excerpt': 'Discover how our hotel caters to business travelers with state-of-the-art facilities, convenient services, and amenities designed for productivity and comfort.', 'content': '''

Business travel doesn't have to mean sacrificing comfort or productivity. Our hotel is designed specifically to meet the needs of modern business travelers.

Business Facilities

Our fully equipped business center provides everything you need - from high-speed internet to meeting rooms with state-of-the-art AV equipment. Work seamlessly from anywhere in the hotel.

Convenient Services

Express check-in and checkout, 24/7 concierge service, and flexible meeting arrangements ensure your business needs are met efficiently. We understand that time is valuable.

Comfortable Accommodations

Our rooms feature dedicated workspaces, ergonomic furniture, and premium amenities. After a long day of meetings, relax in comfort and recharge for tomorrow.

Networking Opportunities

Our restaurants and lounges provide perfect settings for business networking. Whether hosting clients or connecting with colleagues, we provide the ideal atmosphere.

Wellness for Business Travelers

Maintain your wellness routine with our fitness center, spa services, and healthy dining options. We help you stay balanced even when traveling for business.

Experience business travel redefined - where productivity meets luxury, and comfort enhances performance.

''', 'featured_image': 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=1200&h=800&fit=crop', 'author_id': author_id, 'published_at': now - timedelta(days=30), 'is_published': True, 'tags': json.dumps(['business travel', 'corporate', 'productivity', 'meetings']), 'meta_title': 'Business Traveler\'s Guide | Corporate Accommodation', 'meta_description': 'Discover how our hotel caters to business travelers with state-of-the-art facilities, convenient services, and productivity-focused amenities.', 'meta_keywords': 'business travel, corporate hotel, business facilities, meeting rooms', 'sections': None } ] return posts def seed_blog_posts(db: Session, clear_existing: bool = False): """Seed blog posts into the database""" try: # Get admin user as author admin_user = db.query(User).filter(User.email == 'admin@hotel.com').first() if not admin_user: logger.error('Admin user not found. Please run user seeder first.') raise ValueError('Admin user not found. Please run user seeder first.') if clear_existing: logger.info('Clearing existing blog posts...') db.query(BlogPost).delete() db.commit() logger.info('Existing blog posts cleared.') posts_data = get_blog_posts_data(admin_user.id) now = datetime.now(timezone.utc) created_count = 0 updated_count = 0 for post_data in posts_data: # Generate slug if not provided if not post_data.get('slug'): post_data['slug'] = slugify(post_data['title']) existing = db.query(BlogPost).filter(BlogPost.slug == post_data['slug']).first() if existing: logger.debug(f"Blog post '{post_data['title']}' already exists. Updating...") for key, value in post_data.items(): setattr(existing, key, value) existing.updated_at = now updated_count += 1 else: logger.debug(f"Creating blog post: {post_data['title']}") post = BlogPost(**post_data) db.add(post) created_count += 1 db.commit() logger.info(f'Successfully seeded blog posts! Created: {created_count}, Updated: {updated_count}, Total: {len(posts_data)}') except Exception as e: db.rollback() logger.error(f'Error seeding blog posts: {str(e)}', exc_info=True) raise def main(): import argparse parser = argparse.ArgumentParser(description='Seed blog posts') parser.add_argument( '--clear', action='store_true', help='Clear existing blog posts before seeding' ) args = parser.parse_args() db = SessionLocal() try: seed_blog_posts(db, clear_existing=args.clear) except Exception as e: logger.error(f'Failed to seed blog posts: {str(e)}', exc_info=True) sys.exit(1) finally: db.close() if __name__ == '__main__': main()