/* Yamy demo seed generator. node database/seed.mjs -> writes database/seed.sql node database/seed.mjs --db -> also builds database/yamy.db (schema.sql + seed.sql) All names, reviews, orders are sample data. No real people, no real orders. */ import { pbkdf2Sync, randomBytes } from 'node:crypto'; import { writeFileSync, readFileSync, existsSync, unlinkSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; const here = dirname(fileURLToPath(import.meta.url)); let seed = 20261130; const rnd = () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; const pick = a => a[Math.floor(rnd() * a.length)]; const ri = (a, b) => a + Math.floor(rnd() * (b - a + 1)); const money = n => Math.round(n * 100) / 100; const q = s => "'" + String(s).replace(/'/g, "''") + "'"; const iso = d => d.toISOString(); export function hashPassword(pw, iterations = 120000) { const salt = randomBytes(16); const hash = pbkdf2Sync(pw, salt, iterations, 32, 'sha256'); return `pbkdf2$${iterations}$${salt.toString('hex')}$${hash.toString('hex')}`; } const AREA_XY = { Zamalek:[30.0606,31.2197], Maadi:[29.9603,31.2569], Heliopolis:[30.0911,31.3376], 'Nasr City':[30.0511,31.3656], Mohandessin:[30.0561,31.1997], Dokki:[30.0384,31.2118], 'New Cairo':[30.0300,31.4700], 'Sheikh Zayed':[30.0130,30.9800], '6th of October':[29.9285,30.9188], Smouha:[31.2150,29.9500], 'Sidi Gaber':[31.2200,29.9400], Miami:[31.2500,29.9800], Gleem:[31.2400,29.9600], Downtown:[30.0444,31.2357], Giza:[30.0131,31.2089], Haram:[29.9900,31.1700], Shubra:[30.1000,31.2400], Abbassia:[30.0700,31.2800], Rehab:[30.0600,31.4900], Madinaty:[30.0800,31.5700] }; const AREAS = ['Zamalek','Maadi','Heliopolis','Nasr City','Mohandessin','Dokki','New Cairo','Sheikh Zayed','6th of October','Smouha','Sidi Gaber','Miami','Gleem','Downtown','Giza','Haram','Shubra','Abbassia','Rehab','Madinaty']; const REST = [ ['Abu Tarek','أبو طارق','Koshary','Downtown','The original koshary counter since 1950.',4.8,'🍲','#fff1e0',['koshary','cheap','local']], ['Zooba','زوبة','Egyptian','Zamalek','Modern Egyptian street food.',4.6,'🥙','#eaf7ea',['egyptian','street food','healthy']], ['Kebdet El Prince','كبدة الأمير','Grills','Heliopolis','Liver sandwiches and grilled plates.',4.7,'🍖','#ffeaea',['grills','sandwiches']], ['Pizza Milano','بيتزا ميلانو','Pizza','Maadi','Wood-fired pizza and pasta.',4.5,'🍕','#ffe9e2',['pizza','italian','family']], ['Sushi House','سوشي هاوس','Sushi','New Cairo','Sushi rolls, bowls and miso.',4.4,'🍣','#e8f4ff',['sushi','japanese','date night']], ['Shawarma Stop','شاورما ستوب','Shawarma','Mohandessin','Chicken and beef shawarma wraps.',4.6,'🌯','#fff6da',['shawarma','fast','late night']], ['Green Bowl','جرين بول','Healthy','Sheikh Zayed','Salads, bowls and cold-pressed juice.',4.7,'🥗','#eafaf0',['healthy','salads','vegan']], ['Bakes & Brew','بيكس آند برو','Bakery','Dokki','Sourdough, croissants and specialty coffee.',4.5,'🥐','#fdf0e2',['bakery','coffee','breakfast']], ['Felfela','فلفلة','Egyptian','Downtown','Classic foul, taameya and stuffed veg.',4.5,'🫓','#f2f7e6',['egyptian','breakfast','vegetarian']], ['El Abd Pastry','العبد','Desserts','Giza','Basbousa, konafa and oriental sweets.',4.6,'🍰','#ffeef5',['desserts','sweets','gifts']], ['Burger Fuel','برجر فيول','Burgers','Nasr City','Smash burgers and loaded fries.',4.3,'🍔','#fff0e0',['burgers','fast food']], ['Nile Seafood','نيل سي فود','Seafood','Smouha','Grilled fish and shrimp by the kilo.',4.7,'🐟','#e8f7fb',['seafood','grills','family']], ['Tikka Grill','تكا جريل','Grills','Sidi Gaber','Mixed grill platters and kofta.',4.6,'🍢','#ffece0',['grills','family']], ['Cairo Kebab','قاهرة كباب','Grills','Heliopolis','Kebab, kofta and oriental rice.',4.5,'🥩','#ffe9e6',['grills','oriental']], ['Pasta Corner','باستا كورنر','Pasta','Maadi','Fresh pasta and risotto.',4.4,'🍝','#fff2e2',['pasta','italian']], ['Taco Loco','تاكو لوكو','Mexican','Zamalek','Tacos, burritos and nachos.',4.3,'🌮','#fff3d6',['mexican','fast']], ['Bombay Club','بومباي كلوب','Indian','New Cairo','Curries, biryani and naan.',4.5,'🍛','#ffeade',['indian','spicy']], ['Beit El Sitt','بيت الست','Egyptian','Mohandessin','Home-style Egyptian cooking.',4.8,'🍛','#fdeede',['egyptian','home food','family']], ['The Sandwich Co','ذا ساندويتش كو','Sandwiches','Dokki','Cold cuts, clubs and subs.',4.2,'🥪','#eef6ff',['sandwiches','lunch']], ['Chicken Plus','تشيكن بلس','Fried Chicken','Haram','Crispy chicken buckets and wings.',4.4,'🍗','#fff0dc',['chicken','fast food','family']], ['Crepe Avenue','كريب أفينيو','Desserts','Rehab','Sweet and savoury crepes.',4.3,'🥞','#fff1f7',['desserts','crepes']], ['Juice Lab','جوس لاب','Drinks','Madinaty','Fresh juice and smoothies.',4.6,'🥤','#eafaf3',['drinks','healthy']], ['Cafe Greco','كافيه جريكو','Breakfast','Gleem','Alexandria breakfast and coffee.',4.5,'☕','#f7efe6',['breakfast','coffee','seaside']], ['Sobhy Kaber','صبحي كابر','Grills','Abbassia','Famous grilled liver and kofta.',4.6,'🍖','#ffeae2',['grills','local']], ['Mori Sushi','موري سوشي','Sushi','Sheikh Zayed','Omakase sets and sashimi.',4.6,'🍱','#e9f2ff',['sushi','japanese','premium']], ['Zizo Burger','زيزو برجر','Burgers','6th of October','Double patty burgers and shakes.',4.2,'🍔','#fff2e2',['burgers','fast food']], ['Om Hassan','أم حسن','Egyptian','Giza','Koshary and rice pudding.',4.7,'🍚','#fdf3e0',['koshary','cheap','local']], ['Nile Breeze','نايل بريز','Seafood','Miami','Fried and grilled fish plates.',4.4,'🦐','#e8f6fb',['seafood','grills']], ['Saigon Noodles','سايجون نودلز','Asian','New Cairo','Pho, noodles and dumplings.',4.4,'🍜','#fdeee6',['asian','noodles']], ['Falafel King','فلفل كينج','Egyptian','Shubra','Taameya sandwiches all day.',4.5,'🫓','#f0f8e6',['egyptian','cheap','vegetarian']], ['Chili Crab','تشيلي كراب','Seafood','Smouha','Spicy crab and shrimp.',4.3,'🦀','#ffeae2',['seafood','spicy']], ['Bistro 74','بيسترو ٧٤','International','Zamalek','Steaks, salads and wine-free dining.',4.6,'🍽️','#f4f0ff',['international','date night']], ['Pancake House','بان كيك هاوس','Breakfast','Heliopolis','Pancakes, waffles and eggs.',4.4,'🥞','#fff3e0',['breakfast','desserts']], ['Koshary El Tahrir','كشري التحرير','Koshary','Downtown','Fast koshary bowls.',4.3,'🍲','#fdf0dd',['koshary','cheap']], ['Steak & Co','ستيك آند كو','Grills','Maadi','Dry-aged steaks and sides.',4.7,'🥩','#ffe9e9',['grills','premium','date night']], ['Bubble Tea Cairo','بابل تي كايرو','Drinks','Nasr City','Milk tea and fruit teas.',4.2,'🧋','#f7ecff',['drinks','desserts']], ['Mansoura Cheese','منصورة تشيز','Bakery','Mohandessin','Fatayer, manakish and cheese bakes.',4.6,'🥧','#fff6e0',['bakery','breakfast']], ['Healthy Bites','هيلثي بايتس','Healthy','Rehab','Low-calorie meals and protein bowls.',4.5,'🥗','#eafaf0',['healthy','diet']], ['Tandoor House','تندور هاوس','Indian','Madinaty','Tandoori chicken and biryani.',4.4,'🍛','#ffeade',['indian','family']], ['Casa Pasta','كازا باستا','Pasta','Gleem','Baked pasta and lasagna.',4.3,'🍝','#fff2e6',['pasta','family']] ]; const CATS = [['Breakfast','🍳'],['Grills','🍢'],['Pizza','🍕'],['Sushi','🍣'],['Shawarma','🌯'],['Healthy','🥗'],['Desserts','🍰'],['Drinks','🥤'],['Sandwiches','🥪'],['Seafood','🐟'],['Koshary','🍲'],['Bakery','🥐'],['Burgers','🍔'],['Pasta','🍝'],['Chicken','🍗'],['Egyptian','🫓'],['Indian','🍛'],['Asian','🍜'],['Mexican','🌮'],['International','🍽️']]; const POOL = { Breakfast: [['Foul Medames',18],['Taameya Plate',15],['Shakshuka',55],['Egyptian Breakfast Set',85],['Pancakes',60],['Omelette',45],['Croissant',30],['Cappuccino',40]], Grills: [['Kofta Plate',120],['Mixed Grill',220],['Shish Tawook',140],['Grilled Liver',95],['Kebab',150],['Ribs',190],['Grilled Chicken Half',130],['Rice with Nuts',45]], Pizza: [['Margherita',95],['Pepperoni',120],['Four Cheese',135],['Chicken Ranch',130],['Vegetable Pizza',105],['Garlic Bread',35],['Lasagna',140],['Tiramisu',60]], Sushi: [['California Roll',110],['Salmon Nigiri 4pc',95],['Spicy Tuna Roll',130],['Sashimi Set',220],['Miso Soup',35],['Edamame',40],['Dragon Roll',165],['Tempura Shrimp',140]], Shawarma: [['Chicken Shawarma Wrap',55],['Beef Shawarma Wrap',65],['Shawarma Plate',110],['Shawarma Bowl',95],['Fries',25],['Garlic Sauce',10],['Pickles',10],['Extra Bread',5]], Healthy: [['Grilled Chicken Bowl',110],['Falafel Power Bowl',85],['Quinoa Salad',90],['Tuna Salad',95],['Avocado Toast',75],['Green Juice',55],['Protein Smoothie',65],['Hummus Plate',50]], Desserts: [['Basbousa',40],['Konafa with Cream',65],['Rice Pudding',35],['Chocolate Cake',55],['Cheesecake',60],['Crepe Nutella',70],['Ice Cream 2 Scoops',40],['Om Ali',75]], Drinks: [['Fresh Orange Juice',35],['Mango Juice',45],['Lemon Mint',30],['Turkish Coffee',30],['Iced Latte',50],['Milk Tea',40],['Sparkling Water',15],['Cola Can',18]], Sandwiches: [['Club Sandwich',75],['Turkey Sub',65],['Cheese Sandwich',40],['Tuna Sandwich',55],['Chicken Caesar Wrap',70],['Halloumi Sandwich',60],['Beef Sub',80],['Chips',20]], Seafood: [['Grilled Sea Bass',190],['Fried Shrimp',165],['Shrimp Kofta',180],['Seafood Soup',95],['Grilled Squid',150],['Rice with Shrimp',130],['Tahini Sauce',20],['Salad',30]], Koshary: [['Koshary Small',25],['Koshary Medium',35],['Koshary Large',45],['Extra Lentils',10],['Extra Pasta',10],['Extra Sauce',5],['Rice Pudding',30],['Sweet Vermicelli',25]], Bakery: [['Sourdough Loaf',45],['Cheese Fatayer',30],['Spinach Pie',35],['Croissant',28],['Cinnamon Roll',38],['Manakish Zaatar',40],['Baguette',25],['Butter Cookie',15]], Burgers: [['Classic Burger',85],['Double Cheese Burger',120],['Chicken Burger',95],['Veggie Burger',80],['Loaded Fries',55],['Onion Rings',40],['Milkshake',55],['Coleslaw',20]], Pasta: [['Penne Arrabbiata',95],['Alfredo Pasta',110],['Beef Lasagna',140],['Seafood Pasta',175],['Mac and Cheese',85],['Risotto',130],['Caesar Salad',70],['Focaccia',30]], Chicken: [['Fried Chicken 4pc',120],['Chicken Bucket 8pc',220],['Spicy Wings 6pc',95],['Chicken Strips',85],['Coleslaw',25],['Fries',30],['Dinner Roll',12],['Gravy',15]], Egyptian: [['Stuffed Vine Leaves',75],['Mahshi Plate',110],['Molokhia with Rabbit',160],['Fatta',140],['Hawawshi',60],['Liver Sandwich',45],['Alexandrian Sausage',85],['Rice with Milk',35]], Indian: [['Butter Chicken',145],['Chicken Biryani',130],['Vegetable Curry',95],['Naan Bread',20],['Samosa 3pc',45],['Tandoori Chicken',160],['Dal Tadka',85],['Mango Lassi',40]], Asian: [['Beef Pho',120],['Chicken Noodles',105],['Dumplings 6pc',85],['Fried Rice',95],['Spring Rolls',55],['Pad Thai',115],['Ramen',135],['Green Tea',25]], Mexican: [['Beef Taco 3pc',95],['Chicken Burrito',110],['Nachos',70],['Quesadilla',85],['Guacamole',45],['Churros',50],['Elote',40],['Horchata',45]], International: [['Ribeye Steak',320],['Grilled Salmon',260],['Chicken Caesar',140],['Mushroom Soup',70],['Beef Burger',150],['Cheesecake',75],['House Salad',80],['Sparkling Water',30]] }; const CUISINE_CAT = { Koshary:'Koshary', Egyptian:'Egyptian', Grills:'Grills', Pizza:'Pizza', Sushi:'Sushi', Shawarma:'Shawarma', Healthy:'Healthy', Bakery:'Bakery', Desserts:'Desserts', Burgers:'Burgers', Seafood:'Seafood', Pasta:'Pasta', Mexican:'Mexican', Indian:'Indian', Sandwiches:'Sandwiches', 'Fried Chicken':'Chicken', Drinks:'Drinks', Breakfast:'Breakfast', Asian:'Asian', International:'International' }; const FIRST = ['Mazen','Nour','Youssef','Salma','Omar','Farida','Karim','Habiba','Ahmed','Menna','Tarek','Dina','Hassan','Aya','Mostafa','Reem','Ali','Mariam','Sherif','Laila','Adel','Yasmin','Hany','Rana','Ibrahim','Sara','Khaled','Nada','Amr','Heba']; const LAST = ['Ibrahim','Hassan','El Sayed','Fahmy','Mostafa','Adel','Kamal','Rashad','Fouad','Sabry','Nabil','Zaki','Gaber','Shaker','Hegazy']; const COURIER = ['Mohamed Salah','Ahmed Fathy','Youssef Amin','Bassem Nabil','Kareem Adel','Islam Hany','Ramzy Tawfik','Sayed Ali','Hossam Gaber','Mahmoud Reda']; const REVIEW = ['Arrived hot and fast.','Portions are generous, will order again.','Tasty but a bit late.','Best in the area, honestly.','Good value for the price.','Packaging could be better.','Exactly what I wanted tonight.','A little salty for me but fine.','Courier was very polite.','Solid every single time.']; const out = []; const P = s => out.push(s); /* users */ const NOW = new Date('2026-11-30T21:00:00Z'); const users = []; const demoUser = { name: 'Mazen Demo', email: 'mazen@yamy.demo', phone: '+201000000001', role: 'user', pw: 'demo1234' }; const demoAdmin = { name: 'Yamy Admin', email: 'admin@yamy.demo', phone: '+201000000002', role: 'admin', pw: 'admin1234' }; users.push({ ...demoUser, created_at: iso(new Date(NOW - 40 * 864e5)) }); users.push({ ...demoAdmin, created_at: iso(new Date(NOW - 60 * 864e5)) }); for (let i = 0; i < 198; i++) { const name = pick(FIRST) + ' ' + pick(LAST); users.push({ name, email: `user${i + 1}@yamy.demo`, phone: '+2010' + String(10000000 + i).slice(-8), role: i < 2 ? 'admin' : 'user', pw: 'demo1234', created_at: iso(new Date(NOW - ri(1, 200) * 864e5)) }); } users.forEach(u => P(`INSERT INTO users (name,email,phone,password_hash,role,status,created_at) VALUES (${q(u.name)},${q(u.email)},${q(u.phone)},${q(hashPassword(u.pw))},${q(u.role)},'active',${q(u.created_at)});`)); /* addresses for first 60 users */ for (let i = 1; i <= 60; i++) { P(`INSERT INTO addresses (user_id,label,line,area,notes) VALUES (${i},'Home',${q(`${ri(2, 60)} ${pick(['Brazil St','Road 9','El Nasr St','Makram Ebeid','Gameat El Dowal','Tahrir St'])}, Apt ${ri(1, 40)}`)},${q(pick(AREAS))},${q(pick(['Ring the bell twice','Call on arrival','Leave with the doorman']))});`); } /* couriers */ COURIER.forEach((n, i) => P(`INSERT INTO couriers (name,phone,vehicle,rating,status,lat,lon) VALUES (${q(n)},${q('+2011' + String(20000000 + i).slice(-8))},${q(pick(['motorcycle', 'motorcycle', 'bicycle', 'car']))},${money(4.3 + rnd() * 0.6)},${q(pick(['available', 'busy', 'available', 'offline']))},${money(30.03 + rnd() * 0.08)},${money(31.2 + rnd() * 0.12)});`)); /* categories */ CATS.forEach(([n, e]) => P(`INSERT INTO categories (name,emoji) VALUES (${q(n)},${q(e)});`)); /* restaurants + menu */ let menuCount = 0, itemId = 0; const restItems = []; REST.forEach((r, i) => { const [name, ar, cuisine, area, desc, rating, emoji, tint, tags] = r; const open = i === 7 ? 0 : 1; const base = AREA_XY[area] || [30.0444, 31.2357]; const lat = money(base[0] + (rnd() - 0.5) * 0.02), lng = money(base[1] + (rnd() - 0.5) * 0.02); P(`INSERT INTO restaurants (name,name_ar,cuisine,area,description,rating,reviews_count,eta_min,delivery_fee,min_order,emoji,tint,tags,is_open,lat,lng,created_at) VALUES (${q(name)},${q(ar)},${q(cuisine)},${q(area)},${q(desc)},${rating},${ri(40, 900)},${ri(20, 45)},${pick([0, 10, 15, 15, 20, 25])},${pick([50, 60, 75, 100])},${q(emoji)},${q(tint)},${q(JSON.stringify(tags))},${open},${lat},${lng},${q(iso(new Date(NOW - ri(100, 900) * 864e5)))})`); const rid = i + 1; const cat = CUISINE_CAT[cuisine] || 'International'; const pool = POOL[cat] || POOL.International; const items = []; const count = 8 + (i % 3 === 0 ? 2 : 0); for (let k = 0; k < count; k++) { const base = pool[k % pool.length]; const nm = k >= pool.length ? base[0] + ' (Large)' : base[0]; const price = money(k >= pool.length ? base[1] * 1.5 : base[1] * (0.9 + rnd() * 0.25)); itemId++; menuCount++; items.push({ id: itemId, name: nm, price }); P(`INSERT INTO menu_items (restaurant_id,category,name,name_ar,description,price,emoji,is_available,is_popular) VALUES (${rid},${q(cat)},${q(nm)},NULL,${q(pick(['Freshly prepared to order.','House favourite.','Served hot with our signature sauce.','Made with local ingredients.','A regular’s pick.']))},${price},${q(emoji)},1,${k < 2 ? 1 : 0});`); } restItems.push(items); }); /* promos */ const PROMOS = [ ['YAMY10', 'percent', 10, 0, '10% off the subtotal', 1, 1200], ['FREE', 'free_delivery', 0, 120, 'Free delivery over EGP 120', 1, 800], ['WELCOME25', 'flat', 25, 100, 'EGP 25 off your first order', 1, 400], ['RAMADAN15', 'percent', 15, 150, '15% off iftar orders', 0, 300], ['NILE50', 'flat', 50, 300, 'EGP 50 off orders over 300', 1, 200] ]; PROMOS.forEach(([c, k, v, m, d, a, u]) => P(`INSERT INTO promos (code,kind,value,min_subtotal,description,is_active,uses,max_uses) VALUES (${q(c)},${q(k)},${v},${m},${q(d)},${a},${u},2000);`)); /* orders: 620 historical + 12 live today */ const STATUSES = ['placed', 'confirmed', 'preparing', 'picked', 'on_the_way', 'near', 'delivered']; const orderIds = []; function addOrder(o) { orderIds.push(o.id); P(`INSERT INTO orders (id,user_id,restaurant_id,restaurant_name,courier_id,customer_name,phone,address,note,payment_method,card_last4,subtotal,delivery_fee,discount,total,promo_code,status,eta_min,delivery_lat,delivery_lng,created_at) VALUES (${q(o.id)},${o.user_id},${o.restaurant_id},${q(o.restaurant_name)},${o.courier_id},${q(o.customer_name)},${q(o.phone)},${q(o.address)},${o.note ? q(o.note) : 'NULL'},${q(o.payment_method)},${o.card_last4 ? q(o.card_last4) : 'NULL'},${o.subtotal},${o.delivery_fee},${o.discount},${o.total},${o.promo_code ? q(o.promo_code) : 'NULL'},${q(o.status)},${o.eta_min},${money(30.02 + rnd() * 0.08)},${money(31.18 + rnd() * 0.1)},${q(o.created_at)});`); o.items.forEach(it => P(`INSERT INTO order_items (order_id,menu_item_id,name,price,qty) VALUES (${q(o.id)},${it.id},${q(it.name)},${it.price},${it.qty});`)); o.events.forEach(e => P(`INSERT INTO order_events (order_id,status,ts,note) VALUES (${q(o.id)},${q(e.status)},${q(e.ts)},NULL);`)); } const B36 = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; function newId() { let s = ''; for (let i = 0; i < 6; i++) s += B36[Math.floor(rnd() * B36.length)]; return 'ZD-' + s; } const usedIds = new Set(); function uniqId() { let id; do { id = newId(); } while (usedIds.has(id)); usedIds.add(id); return id; } const STAGE_MIN = [0, 1, 8, 16, 22, 30, 33]; for (let i = 0; i < 620; i++) { const ridx = ri(0, REST.length - 1); const items = []; const n = ri(1, 4); for (let k = 0; k < n; k++) { const it = pick(restItems[ridx]); if (!items.find(x => x.id === it.id)) items.push({ ...it, qty: ri(1, 2) }); } const subtotal = money(items.reduce((s, it) => s + it.price * it.qty, 0)); const fee = pick([0, 10, 15, 20, 25]); const promo = rnd() < 0.2 ? pick(['YAMY10', 'FREE', 'WELCOME25']) : null; const discount = promo === 'YAMY10' ? money(subtotal * 0.1) : promo === 'WELCOME25' ? 25 : promo === 'FREE' ? fee : 0; const created = new Date(NOW - ri(1, 90) * 864e5 - ri(0, 80000) * 1000); const status = rnd() < 0.06 ? 'canceled' : 'delivered'; const events = [{ status: 'placed', ts: iso(created) }, { status: 'confirmed', ts: iso(new Date(+created + 60e3)) }, { status: 'preparing', ts: iso(new Date(+created + 8 * 60e3)) }, { status: 'picked', ts: iso(new Date(+created + 16 * 60e3)) }, { status: 'on_the_way', ts: iso(new Date(+created + 22 * 60e3)) }, { status: 'near', ts: iso(new Date(+created + 30 * 60e3)) }, { status: status === 'delivered' ? 'delivered' : 'canceled', ts: iso(new Date(+created + 33 * 60e3)) }]; addOrder({ id: uniqId(), user_id: rnd() < 0.8 ? ri(3, 200) : null, restaurant_id: ridx + 1, restaurant_name: REST[ridx][0], courier_id: ri(1, 10), customer_name: pick(FIRST) + ' ' + pick(LAST), phone: '+2010' + String(10000000 + ri(1, 9999999)).slice(-8), address: `${ri(1, 90)} ${pick(['El Nasr St', 'Road 9', 'Tahrir St', '90th St'])}`, note: rnd() < 0.2 ? pick(['No onions', 'Extra sauce', 'Call on arrival']) : null, payment_method: rnd() < 0.6 ? 'cash' : 'visa', card_last4: rnd() < 0.6 ? null : '4242', subtotal, delivery_fee: fee, discount, total: money(subtotal + fee - discount), promo_code: promo, status, eta_min: ri(20, 45), created_at: iso(created), items, events }); } /* live orders today at different stages, for the admin board */ const liveStages = ['placed', 'confirmed', 'preparing', 'picked', 'on_the_way', 'near']; liveStages.forEach((st, i) => { const ridx = i + 2; const items = [pick(restItems[ridx])].map(it => ({ ...it, qty: 1 })); const subtotal = money(items.reduce((s, it) => s + it.price * it.qty, 0)); const fee = 15; const created = new Date(NOW - (STAGE_MIN[liveStages.indexOf(st)] + 2) * 60e3); const events = STAGE_MIN.map((m, k) => ({ status: STATUSES[k], ts: iso(new Date(+created + m * 60e3)) })).filter(e => new Date(e.ts) <= NOW); addOrder({ id: uniqId(), user_id: 1, restaurant_id: ridx + 1, restaurant_name: REST[ridx][0], courier_id: (i % 10) + 1, customer_name: 'Mazen Demo', phone: '+201000000001', address: '14 Brazil St, Zamalek', note: null, payment_method: i % 2 ? 'cash' : 'visa', card_last4: i % 2 ? null : '4242', subtotal, delivery_fee: fee, discount: 0, total: money(subtotal + fee), promo_code: null, status: st, eta_min: 30, created_at: iso(created), items, events }); }); /* reviews */ for (let i = 0; i < 1300; i++) { const ridx = ri(0, REST.length - 1); const created = new Date(NOW - ri(0, 120) * 864e5); const rating = rnd() < 0.62 ? 5 : rnd() < 0.75 ? 4 : rnd() < 0.9 ? 3 : ri(1, 2); P(`INSERT INTO reviews (restaurant_id,user_id,order_id,rating,comment,created_at) VALUES (${ridx + 1},${rnd() < 0.9 ? ri(1, 200) : 'NULL'},${q(pick(orderIds))},${rating},${q(pick(REVIEW))},${q(iso(created))});`); } /* chat log samples */ [['How long is delivery?', 'Delivery is 20-45 minutes depending on the restaurant.'], ['Is there a promo?', 'Use YAMY10 for 10% off, or FREE for free delivery over EGP 120.']].forEach(([u, b], i) => { P(`INSERT INTO chat_messages (user_id,session_id,role,text,ts) VALUES (1,'seed-session','user',${q(u)},${q(iso(new Date(NOW - (10 - i) * 60e3)))});`); P(`INSERT INTO chat_messages (user_id,session_id,role,text,ts) VALUES (1,'seed-session','bot',${q(b)},${q(iso(new Date(NOW - (10 - i) * 60e3 + 2000)))});`); }); writeFileSync(join(here, 'seed.sql'), out.join('\n') + '\n'); console.log('seed.sql written:', out.length, 'statements |', users.length, 'users,', REST.length, 'restaurants,', menuCount, 'menu items,', orderIds.length, 'orders, 1300 reviews'); if (process.argv.includes('--db')) { const { DatabaseSync } = await import('node:sqlite'); const dbPath = join(here, 'yamy.db'); if (existsSync(dbPath)) unlinkSync(dbPath); const db = new DatabaseSync(dbPath); // schema.sql has multi-line CREATE statements: exec it whole. seed.sql is one statement per line. db.exec(readFileSync(join(here, 'schema.sql'), 'utf8')); const stmts = readFileSync(join(here, 'seed.sql'), 'utf8').split('\n').map(l => l.trim()).filter(Boolean); db.exec('BEGIN'); for (const st of stmts) db.exec(st); db.exec('COMMIT'); const one = s => db.prepare(s).get(); console.log('yamy.db built:', one('SELECT COUNT(*) c FROM orders').c, 'orders,', one('SELECT COUNT(*) c FROM users').c, 'users,', one('SELECT COUNT(*) c FROM menu_items').c, 'items'); }