-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1179 lines (1089 loc) · 60.9 KB
/
Copy pathserver.ts
File metadata and controls
1179 lines (1089 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express, { Request, Response } from "express";
import path from "path";
import { GoogleGenAI, Type } from "@google/genai";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Initialize Google Gen AI client server-side
function getGeminiClient(): GoogleGenAI | null {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.warn("GEMINI_API_KEY is not set in environment. Using smart catalog engine fallback.");
return null;
}
return new GoogleGenAI({
apiKey,
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
},
},
});
}
// Health check endpoint
app.get("/api/health", (req: Request, res: Response) => {
res.json({
status: "ok",
hasGeminiKey: Boolean(process.env.GEMINI_API_KEY),
time: new Date().toISOString(),
});
});
// Generate party plan endpoint
app.post("/api/planner/generate", async (req: Request, res: Response) => {
try {
const {
occasion,
occasionTitle,
themeDescription,
guestCount = 20,
targetBudget = 10000,
dietary = 'pure_veg',
venue = 'home_living_room',
durationHours = 4,
specialRequests = '',
ecoFriendly = true,
city = 'Bengaluru'
} = req.body;
const ai = getGeminiClient();
if (!ai) {
// Return structured fallback response if no API key
return res.json({
source: 'catalog_engine',
data: generateSmartCatalogPlan({
occasion,
occasionTitle,
themeDescription,
guestCount,
targetBudget,
dietary,
venue,
durationHours,
specialRequests,
ecoFriendly,
city
})
});
}
const systemPrompt = `You are IndianMart's Chief AI Party Planning Concierge in India.
Your mission is to generate a comprehensive, realistic, and budget-conscious grocery & party supply shopping list for Indian hosts.
All prices must be in Indian Rupees (₹ INR).
Always consider:
1. Indian tastes, brands (Haldiram's, Amul, Paper Boat, MTR, Tata Sampann, Rooh Afza, Bikanervala, EcoVeda areca leaf plates).
2. Dietary preferences: ${dietary} (if pure_veg or jain, strictly no meat/egg/onion/garlic where applicable).
3. Guest count: ${guestCount} people. Ensure portion sizes and quantities are mathematically sufficient.
4. Total Budget: ₹${targetBudget}. The total cost of all recommended items should align closely with this target budget (within ±10%).
5. Eco-friendly: ${ecoFriendly ? 'Prioritize biodegradable areca palm leaf plates, wooden cutlery and compostable bags' : 'Standard tableware'}.
6. City/Region: ${city}.
Categories to cover:
- 'food_snacks' (appetizers, samosas, tikka, chips, dips, chaat)
- 'main_course' (biryani trays, gravies, rotis/naans, rice)
- 'beverages' (chai, coolers, soft drinks, mocktails, juices)
- 'sweets_desserts' (mithai, gulab jamun, ice cream, kaju katli)
- 'decor_lighting' (marigold garlands, fairy rice lights, diyas, balloons)
- 'tableware_essentials' (plates, cups, spoons, napkins, trash bags)
- 'games_favors' (housie/tambola, cards, return gifts)
Include realistic item prices in INR, appropriate pack sizes, and smart alternatives where a host could save money.`;
const userPrompt = `Please plan an event shopping list for:
Event: ${occasionTitle || occasion}
Theme: ${themeDescription || 'Festive Indian Gathering'}
Guests: ${guestCount}
Target Budget: ₹${targetBudget}
Dietary: ${dietary}
Venue: ${venue}
Duration: ${durationHours} hours
Special Requests: ${specialRequests || 'None'}
Eco-friendly tableware: ${ecoFriendly ? 'Yes' : 'No'}
City: ${city}`;
const response = await ai.models.generateContent({
model: "gemini-3.7-flash",
contents: userPrompt,
config: {
systemInstruction: systemPrompt,
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
eventName: { type: Type.STRING },
eventSummary: { type: Type.STRING },
budgetAnalysis: {
type: Type.OBJECT,
properties: {
status: { type: Type.STRING, description: "within_budget, over_budget, or under_budget" },
totalCost: { type: Type.NUMBER },
difference: { type: Type.NUMBER },
tip: { type: Type.STRING }
},
required: ["status", "totalCost", "difference", "tip"]
},
items: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
id: { type: Type.STRING },
name: { type: Type.STRING },
brand: { type: Type.STRING },
category: {
type: Type.STRING,
description: "food_snacks, main_course, beverages, sweets_desserts, decor_lighting, tableware_essentials, or games_favors"
},
unitPrice: { type: Type.NUMBER, description: "Price in INR ₹" },
quantity: { type: Type.INTEGER },
unitSize: { type: Type.STRING, description: "e.g. 500g pack, 1L bottle, Pack of 25" },
portionsPerUnit: { type: Type.STRING, description: "e.g. Serves 6-8 guests" },
isEssential: { type: Type.BOOLEAN },
tags: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
alternative: {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
unitPrice: { type: Type.NUMBER },
savingAmount: { type: Type.NUMBER },
reason: { type: Type.STRING }
},
required: ["name", "unitPrice", "savingAmount", "reason"]
}
},
required: ["id", "name", "category", "unitPrice", "quantity", "unitSize", "isEssential", "tags"]
}
},
hostChecklist: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: "5-7 high value preparation checklist tasks for the host"
},
timelineGuide: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
time: { type: Type.STRING, description: "e.g. T-3 Hours, T-1 Hour, 00:00 (Party Start), +2 Hours (Dinner)" },
activity: { type: Type.STRING }
},
required: ["time", "activity"]
}
}
},
required: ["eventName", "eventSummary", "budgetAnalysis", "items", "hostChecklist", "timelineGuide"]
}
}
});
const parsedData = JSON.parse(response.text || "{}");
return res.json({
source: 'gemini_ai',
data: parsedData
});
} catch (error: any) {
console.error("Gemini generation error:", error);
// Fallback to catalog generator
return res.json({
source: 'catalog_fallback',
error: error.message,
data: generateSmartCatalogPlan(req.body)
});
}
});
// Auto-Optimize Budget endpoint
app.post("/api/planner/optimize", async (req: Request, res: Response) => {
try {
const { items, targetBudget, mode = 'balance_exact' } = req.body;
const ai = getGeminiClient();
if (!ai) {
return res.json({
success: true,
source: 'rule_optimizer',
recommendations: optimizeItemsRuleBased(items, targetBudget, mode)
});
}
const currentTotal = items.reduce((acc: number, item: any) => acc + (item.unitPrice * item.quantity), 0);
const prompt = `You are a budget optimization engine for IndianMart India.
The host has a target budget of ₹${targetBudget}.
Current cart total is ₹${currentTotal}.
Mode requested: ${mode} (options: balance_exact, trim_overage, upgrade_premium).
Current items: ${JSON.stringify(items.map((it: any) => ({
id: it.id,
name: it.name,
category: it.category,
unitPrice: it.unitPrice,
quantity: it.quantity,
isEssential: it.isEssential
})))}
Provide optimization advice and suggested quantity modifications or item swaps to bring the cart as close as possible to the target budget (₹${targetBudget}) without compromising core hospitality.`;
const response = await ai.models.generateContent({
model: "gemini-3.7-flash",
contents: prompt,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
optimizationSummary: { type: Type.STRING },
newTotalEstimate: { type: Type.NUMBER },
adjustments: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
itemId: { type: Type.STRING },
itemName: { type: Type.STRING },
recommendedQuantity: { type: Type.INTEGER },
reason: { type: Type.STRING },
suggestedSwap: {
type: Type.OBJECT,
properties: {
swapName: { type: Type.STRING },
swapPrice: { type: Type.NUMBER },
netSavings: { type: Type.NUMBER }
}
}
},
required: ["itemId", "itemName", "recommendedQuantity", "reason"]
}
}
},
required: ["optimizationSummary", "newTotalEstimate", "adjustments"]
}
}
});
const parsed = JSON.parse(response.text || "{}");
return res.json({
success: true,
source: 'gemini_ai',
recommendations: parsed
});
} catch (err: any) {
console.error("Optimizer error:", err);
return res.json({
success: true,
source: 'rule_fallback',
recommendations: optimizeItemsRuleBased(req.body.items, req.body.targetBudget, req.body.mode)
});
}
});
// IndianMart Assistant Chatbot Endpoint
app.post("/api/chat", async (req: Request, res: Response) => {
try {
const {
message,
history = [],
eventContext = {},
cartContext = {}
} = req.body;
if (!message || typeof message !== 'string') {
return res.status(400).json({ error: "Message is required" });
}
const ai = getGeminiClient();
if (!ai) {
// Fallback rule-based response
return res.json({
source: 'smart_fallback',
reply: generateAssistantFallbackReply(message, eventContext, cartContext),
quickReplies: [
"How much food for my guest count?",
"Suggest budget Jain snacks",
"What drinks pair best with Biryani?",
"Add extra gulab jamun to my list"
]
});
}
const systemInstruction = `You are the "IndianMart Assistant", an expert, warm, and highly practical AI retail party concierge for IndianMart India.
You help Indian hosts plan, budget, shop, and execute unforgettable parties and gatherings (Diwali, Bollywood Karaoke, Chai Chaat, Biryani feasts, Birthdays, Housewarmings, Cricket watch parties).
Guidelines:
1. Always speak politely with Indian hospitality context (use terms like "Namaste", "Host", "chai", "mithai", "chaat", "portions").
2. Always calculate and quote currency in Indian Rupees (₹ INR).
3. Offer precise portion estimation formulas when asked (e.g. 150-180g cooked biryani/pulao per adult, 2-3 snack pieces per person, 250ml beverage/mocktail per person, 1.5 pieces of mithai per person, 1 areca palm plate set per person + 15% buffer).
4. Be mindful of dietary constraints (Pure Veg, Jain without onion/garlic/root veg, Halal/Non-veg, Vegan, Eggless).
5. If the user asks for item recommendations or additions, mention realistic Indian retail brands (Haldiram's, Paper Boat, Amul, Tata Sampann, Bikaji, Bikanervala, Rooh Afza, Catch, Britannia, Epigamia, etc.) with approximate ₹ prices.
6. Provide helpful quick response suggestions for the customer to continue the conversation.
Current Customer Context:
- Occasion: ${eventContext.occasionTitle || 'Party'}
- Guest Count: ${eventContext.guestCount || 20} Guests
- City: ${eventContext.city || 'Bengaluru'}
- Dietary: ${eventContext.dietary || 'pure_veg'}
- Target Budget: ₹${eventContext.targetBudget || 10000}
- Current Cart Total: ₹${cartContext.totalSpend || 0} (${cartContext.itemCount || 0} items in list)
Return a structured JSON with:
- "reply": Markdown formatted string with clear, friendly explanation and advice.
- "suggestedItems": (Optional array of items if recommending new products to add to cart, with id, name, brand, category, unitPrice, unitSize, quantity, isEssential, tags).
- "quickReplies": (Array of 3-4 short question strings the user might ask next).`;
// Construct conversation contents
const contents: any[] = [];
// Add recent history (up to last 6 turns)
const recentHistory = history.slice(-6);
for (const msg of recentHistory) {
contents.push({
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: msg.content }]
});
}
// Add current user prompt
contents.push({
role: 'user',
parts: [{ text: message }]
});
const response = await ai.models.generateContent({
model: "gemini-3.7-flash",
contents,
config: {
systemInstruction,
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
reply: { type: Type.STRING },
quickReplies: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
suggestedItems: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
id: { type: Type.STRING },
name: { type: Type.STRING },
brand: { type: Type.STRING },
category: { type: Type.STRING },
unitPrice: { type: Type.NUMBER },
unitSize: { type: Type.STRING },
quantity: { type: Type.INTEGER },
isEssential: { type: Type.BOOLEAN },
tags: {
type: Type.ARRAY,
items: { type: Type.STRING }
}
},
required: ["id", "name", "category", "unitPrice", "unitSize", "quantity"]
}
}
},
required: ["reply"]
}
}
});
const parsed = JSON.parse(response.text || "{}");
return res.json({
source: 'gemini_ai',
reply: parsed.reply || "Namaste! I'm here to help you coordinate your party shopping on IndianMart.",
suggestedItems: parsed.suggestedItems || [],
quickReplies: parsed.quickReplies || [
"How much food for my guest count?",
"Suggest budget Jain snacks",
"What drinks pair best with Biryani?",
"How to balance my budget?"
]
});
} catch (error: any) {
console.error("Chatbot API error:", error);
return res.json({
source: 'fallback_error',
reply: generateAssistantFallbackReply(req.body.message || '', req.body.eventContext, req.body.cartContext),
quickReplies: [
"Estimate food quantities",
"Show party drink options",
"Jain snack suggestions",
"Eco-friendly tableware options"
]
});
}
});
// Hands-Free Voice Command & Conversational Assistant Endpoint
app.post("/api/voice/process", async (req: Request, res: Response) => {
try {
const {
transcript,
activeTab = 'define',
eventDefinition = {},
items = [],
currentTotal = 0,
language = 'en'
} = req.body;
if (!transcript || typeof transcript !== 'string') {
return res.status(400).json({ error: "Speech transcript is required" });
}
const ai = getGeminiClient();
// If Gemini is available, use intelligent conversational and intent reasoning
if (ai) {
const languageInstruction = language === 'hi'
? 'IMPORTANT: Output the "spokenFeedback" in fluent, natural conversational Hindi (हिन्दी) and "toastMessage" in Hindi.'
: language === 'bn'
? 'IMPORTANT: Output the "spokenFeedback" in fluent, natural conversational Bengali (বাংলা) and "toastMessage" in Bengali.'
: 'Output the "spokenFeedback" and "toastMessage" in warm, natural conversational Indian English.';
const systemInstruction = `You are the Voice & Shopping AI Concierge for IndianMart India.
Your job is to understand whatever the user says or asks (in English, Hindi, or Bengali) and respond naturally:
1. If the user asks a question (food portion calculations, snack/sweet ideas, drinks pairings, budget tips, party timeline, delivery info, or greetings), answer their question thoroughly, warmly, and helpfully in "spokenFeedback".
2. If the user gives a command to modify the cart, set event details, navigate, or place an order, include the appropriate action in "actions" AND explain what was done in "spokenFeedback".
3. Always respond strictly in the requested language: ${language === 'hi' ? 'Hindi (हिन्दी)' : language === 'bn' ? 'Bengali (বাংলা)' : 'Indian English'}.
${languageInstruction}
Current App State:
- Active Tab: ${activeTab} ('define', 'review', or 'refine_checkout')
- Occasion: ${eventDefinition.occasionTitle || eventDefinition.occasion || 'Festive Party'}
- Guests: ${eventDefinition.guestCount || 20}
- Target Budget: ₹${eventDefinition.targetBudget || 10000}
- Dietary: ${eventDefinition.dietary || 'pure_veg'}
- Current Cart Total: ₹${currentTotal}
- Current Items in Cart (${items.length}): ${items.map((i: any) => `${i.name} (Qty: ${i.quantity}, ID: ${i.id})`).join(', ')}
Supported Action Types:
1. 'SET_EVENT_FIELD': payload: { field: 'guestCount'|'targetBudget'|'dietary'|'occasion'|'venue'|'city'|'ecoFriendly'|'durationHours', value: any }
2. 'GENERATE_PLAN': payload: {}
3. 'ADD_ITEM': payload: { query: string, quantity: number }
4. 'UPDATE_QUANTITY': payload: { itemName: string, change?: number, exactQuantity?: number }
5. 'REMOVE_ITEM': payload: { itemName: string }
6. 'AUTO_BALANCE': payload: { mode: 'balance_exact'|'trim_overage'|'upgrade_premium' }
7. 'NAVIGATE_TAB': payload: { tab: 'define'|'review'|'refine_checkout' }
8. 'APPLY_COUPON': payload: { couponCode: string }
9. 'SELECT_PAYMENT': payload: { method: 'upi'|'card'|'cod'|'indianmart_pay', upiApp?: 'gpay'|'phonepe'|'paytm'|'cred' }
10. 'SELECT_DELIVERY': payload: { slot: string }
11. 'PLACE_ORDER': payload: {}
12. 'READ_SUMMARY': payload: {}
13. 'ASSISTANT_QUERY': payload: { text: string }
Output Requirement:
- Return valid JSON matching the schema.
- "spokenFeedback": A direct, friendly, informative spoken answer or confirmation in the target language (${language === 'hi' ? 'Hindi' : language === 'bn' ? 'Bengali' : 'English'}).
- "toastMessage": A concise confirmation tag with an emoji.`;
const prompt = `User spoken speech in ${language}: "${transcript}"`;
const response = await ai.models.generateContent({
model: "gemini-3.7-flash",
contents: prompt,
config: {
systemInstruction,
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
spokenFeedback: { type: Type.STRING },
toastMessage: { type: Type.STRING },
actions: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
type: { type: Type.STRING },
payload: {
type: Type.OBJECT,
properties: {
field: { type: Type.STRING },
value: { type: Type.STRING },
numericValue: { type: Type.NUMBER },
query: { type: Type.STRING },
quantity: { type: Type.NUMBER },
itemName: { type: Type.STRING },
change: { type: Type.NUMBER },
exactQuantity: { type: Type.NUMBER },
mode: { type: Type.STRING },
tab: { type: Type.STRING },
couponCode: { type: Type.STRING },
method: { type: Type.STRING },
upiApp: { type: Type.STRING },
slot: { type: Type.STRING },
text: { type: Type.STRING }
}
}
},
required: ["type"]
}
}
},
required: ["spokenFeedback", "toastMessage", "actions"]
}
}
});
const parsed = JSON.parse(response.text || "{}");
return res.json({
success: true,
source: 'gemini_voice',
actions: parsed.actions || [],
spokenFeedback: parsed.spokenFeedback || (language === 'hi' ? "नमस्ते! मैं आपकी पार्टी शॉपिंग में मदद कर सकता हूँ।" : language === 'bn' ? "নমস্কার! আমি আপনার পার্টি শপিংয়ে সাহায্য করতে পারি।" : "Hello! I am here to help coordinate your party shopping."),
toastMessage: parsed.toastMessage || (language === 'hi' ? "वॉयस प्रतिक्रिया" : language === 'bn' ? "ভয়েস প্রতিক্রিয়া" : "Voice response")
});
}
// Rule-based parsing and Q&A fallback if Gemini API is offline
const ruleResult = parseVoiceCommandRuleBased(transcript, activeTab, eventDefinition, items, currentTotal, language);
return res.json({
success: true,
source: 'rule_voice',
...ruleResult
});
} catch (err: any) {
console.error("Voice interpreter error:", err);
// Fallback gracefully
const ruleResult = parseVoiceCommandRuleBased(
req.body.transcript || '',
req.body.activeTab,
req.body.eventDefinition,
req.body.items,
req.body.currentTotal,
req.body.language || 'en'
);
return res.json({
success: true,
source: 'fallback_voice',
...ruleResult
});
}
});
function normalizeIndicNumerals(str: string): string {
const indicDigits: Record<string, string> = {
'०': '0', '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9',
'০': '0', '১': '1', '২': '2', '৩': '3', '৪': '4', '৫': '5', '৬': '6', '৭': '7', '৮': '8', '৯': '9'
};
return str.replace(/[०-९০-৯]/g, d => indicDigits[d] || d);
}
// Conversational and Action Voice Parser with English, Hindi, Bengali support
function parseVoiceCommandRuleBased(
transcript: string,
activeTab: string,
eventDefinition: any = {},
items: any[] = [],
currentTotal: number = 0,
language: string = 'en'
) {
const normalized = normalizeIndicNumerals(transcript);
const lower = normalized.toLowerCase().trim();
const actions: any[] = [];
const guests = eventDefinition.guestCount || 20;
const budget = eventDefinition.targetBudget || 10000;
const city = eventDefinition.city || 'Bengaluru';
let spokenFeedback = "";
let toastMessage = "🎙️ Voice";
// 1. Greetings & Introductions
if (lower.includes('নমস্কার') || lower.includes('হ্যালো') || lower.includes('কেমন আছেন') || lower.includes('হাই') || lower.includes('কি করতে পারো') || lower.includes('সাহায্য') || lower.includes('नमस्ते') || lower.includes('हेलो') || lower.includes('hello') || lower.includes('hi') || lower.includes('hey')) {
if (language === 'bn') {
spokenFeedback = `নমস্কার! আমি আপনার IndianMart ভয়েস অ্যাসিস্ট্যান্ট। ${guests} জন অতিথির জন্য পার্টি শপিং, খাবারের সঠিক পরিমাণ হিসাব, স্ন্যাক্স বা মিষ্টির পরামর্শ, বা বাজেট নিয়ন্ত্রণে সাহায্য করতে পারি। আপনি কি জানতে চান?`;
toastMessage = "👋 নমস্কার!";
} else if (language === 'hi') {
spokenFeedback = `नमस्ते! मैं आपका IndianMart वॉइस असिस्टेंट हूँ। ${guests} मेहमानों के लिए पार्टी प्लानिंग, खाने की मात्रा, स्नैक्स सुझाव या बजट में मदद कर सकता हूँ। बताएं मैं क्या करूँ?`;
toastMessage = "👋 नमस्ते!";
} else {
spokenFeedback = `Namaste! I am your IndianMart Voice Assistant. I can help curate groceries, calculate food portions, or optimize your ₹${budget} budget for ${guests} guests in ${city}.`;
toastMessage = "👋 Namaste!";
}
return { actions, spokenFeedback, toastMessage };
}
// 2. Questions about Food Portions & Quantities (কত খাবার / কত লাগবে / পরিমাণ / portion)
if (lower.includes('কত খাবার') || lower.includes('কত লাগবে') || lower.includes('খাবারের পরিমাণ') || lower.includes('পরিমাণ') || lower.includes('কত মিষ্টি') || lower.includes('কত বিরিয়ানি') || lower.includes('কত সিঙ্গাড়া') || lower.includes('कितना खाना') || lower.includes('कितनी मात्रा') || lower.includes('portion') || lower.includes('how much food') || lower.includes('quantity')) {
// If a new guest count was mentioned in the question, update it too
const guestMatch = lower.match(/(\d+)\s*(guests?|people|persons?|জন|অতিথি|মানুষ|मेहमान|लोग)/i);
let qGuests = guests;
if (guestMatch) {
const parsedNum = parseInt(guestMatch[1], 10);
if (!isNaN(parsedNum) && parsedNum > 0) {
qGuests = parsedNum;
actions.push({ type: 'SET_EVENT_FIELD', payload: { field: 'guestCount', value: parsedNum, numericValue: parsedNum } });
}
}
if (language === 'bn') {
spokenFeedback = `${qGuests} জন অতিথির জন্য খাবারের হিসাব: মেইন কোর্সে প্রায় ${(qGuests * 0.18).toFixed(1)} কেজি বিরিয়ানি, স্ন্যাক্সে ${Math.ceil(qGuests * 2.5)}টি সিঙ্গাড়া ও কাটলেট, এবং মিষ্টিতে ${Math.ceil(qGuests * 1.8)}টি রসগোল্লা বা গোলাপ জাম লাগবে।`;
toastMessage = `🍛 ${qGuests} জনের খাবার হিসাব`;
} else if (language === 'hi') {
spokenFeedback = `${qGuests} मेहमानों के लिए लगभग ${(qGuests * 0.18).toFixed(1)} किलो बिरयानी, ${Math.ceil(qGuests * 2.5)} पीस समोसे और कटलेट, तथा ${Math.ceil(qGuests * 1.8)} पीस गुलाब जामुन पर्याप्त रहेगा।`;
toastMessage = `🍛 ${qGuests} लोगों की मात्रा`;
} else {
spokenFeedback = `For ${qGuests} guests, plan for approx ${(qGuests * 0.18).toFixed(1)} kg Biryani/Pulao, ${Math.ceil(qGuests * 2.5)} snack pieces (samosas/cutlets), and ${Math.ceil(qGuests * 1.8)} pieces of mithai/sweets.`;
toastMessage = `🍛 Portions for ${qGuests}`;
}
return { actions, spokenFeedback, toastMessage };
}
// 3. Questions about Snacks & Food Suggestions (স্ন্যাক্স / নাস্তা / খাবার কি আছে / snacks)
if (lower.includes('স্ন্যাক্স') || lower.includes('নাস্তা') || lower.includes('খাবার কি') || lower.includes('মেনু') || lower.includes('नाश्ता') || lower.includes('खाना') || lower.includes('snacks') || lower.includes('appetizer')) {
if (language === 'bn') {
spokenFeedback = `পার্টির সেরা স্ন্যাক্স হিসেবে হলদিরামের ককটেল সিঙ্গাড়া, পানির টিক্কা, পাপড়ি চাট কিট এবং কাজু বাদাম খুব দারুণ! আপনি চাইলে বলুন, আমি লিস্টে যোগ করে দেব।`;
toastMessage = "🥟 স্ন্যাক্স মেনু পরামর্শ";
} else if (language === 'hi') {
spokenFeedback = `पार्टी के लिए हल्दीराम कॉकटेल समोसा, पनीर टिक्का सीख, पापड़ी चाट किट और रोस्टेड काजू-बादाम सबसे बेहतरीन हैं। क्या मैं इन्हें कार्ट में जोड़ दूँ?`;
toastMessage = "🥟 स्नैक्स सुझाव";
} else {
spokenFeedback = `Top party snack recommendations include Haldiram Cocktail Samosas, Amul Paneer Tikka skewers, Papdi Chaat kits, and roasted cashews. Would you like to add these?`;
toastMessage = "🥟 Snack Ideas";
}
return { actions, spokenFeedback, toastMessage };
}
// 4. Questions about Sweets & Desserts (মিষ্টি / ডেজার্ট / मिठाई / sweets)
if (lower.includes('মিষ্টি') || lower.includes('গোলাপ জাম') || lower.includes('রসমঞ্জরী') || lower.includes('मिठाई') || lower.includes('गुलाब जामुन') || lower.includes('sweet') || lower.includes('dessert') || lower.includes('mithai')) {
if (language === 'bn') {
spokenFeedback = `মিষ্টির জন্য বিকানেরওয়ালা প্রিমিয়াম গুলাব জামুন টিন, বিকাজি কাজু বরফি এবং কেশর পেস্তা কুলফি সেরা! প্রতি অতিথির জন্য প্রায় ২টি করে মিষ্টি রাখুন।`;
toastMessage = "🍯 মিষ্টির পরামর্শ";
} else if (language === 'hi') {
spokenFeedback = `मिठाई में बीकानेरवाला गुलाब जामुन टिन, काजू कतली और केसर पिस्ता कुल्फी सबसे लोकप्रिय हैं। प्रति मेहमान 2 पीस का हिसाब रखें।`;
toastMessage = "🍯 मिठाई सुझाव";
} else {
spokenFeedback = `For dessert, Bikanervala Gulab Jamun family tins, Kaju Katli, and Kesar Pista Kulfi are host favorites. Plan for ~2 pieces per guest.`;
toastMessage = "🍯 Sweets Guide";
}
return { actions, spokenFeedback, toastMessage };
}
// 5. Questions about Drinks & Mocktails (ড্রিংকস / পানীয় / शरबत / drinks)
if (lower.includes('ড্রিংকস') || lower.includes('পানীয়') || lower.includes('শরবত') || lower.includes('ড্রिंक्स') || lower.includes('drinks') || lower.includes('beverage') || lower.includes('mocktail')) {
if (language === 'bn') {
spokenFeedback = `পার্টিতে পেপার বোট আমপানা, রুহ আফজা গোলাপ শরবত এবং কিনলে ক্লাব সোডা দিয়ে রিফ্রেশিং মকটেল পরিবেশন করতে পারেন। প্রতি অতিথির জন্য ২৫০ মিলি হিসাব রাখুন।`;
toastMessage = "🥤 পানীয় পরামর্শ";
} else if (language === 'hi') {
spokenFeedback = `ड्रिंक्स में पेपर बोट आमरस, रूह अफ़ज़ा शरबत और क्लब सोडा मिंट मॉकटेल्स सबसे ताज़गी भरे हैं। प्रति व्यक्ति 250ml का अनुमान रखें।`;
toastMessage = "🥤 ड्रिंक्स सुझाव";
} else {
spokenFeedback = `Great beverage options include Paper Boat coolers, Rooh Afza gulab sharbat, and Kinley Club Soda mocktail mixes. Plan for ~250ml per person.`;
toastMessage = "🥤 Drink Ideas";
}
return { actions, spokenFeedback, toastMessage };
}
// 6. Navigation Commands (চেকআউট / রিভিউ / ইভেন্ট / checkout / review)
if (lower.includes('checkout') || lower.includes('finalize') || lower.includes('step 3') || lower.includes('proceed to checkout') || lower.includes('চেকআউট') || lower.includes('चेकआउट') || (lower.includes('next step') && activeTab === 'review')) {
actions.push({ type: 'NAVIGATE_TAB', payload: { tab: 'refine_checkout' } });
spokenFeedback = language === 'bn' ? "স্মার্ট সেভ এবং চেকআউটে নিয়ে যাচ্ছি।" : language === 'hi' ? "चेकआउट और अंतिम बचत पृष्ठ पर जा रहे हैं।" : "Navigating to smart save and checkout.";
toastMessage = language === 'bn' ? "👉 চেকআউট" : language === 'hi' ? "👉 चेकआउट" : "👉 Checkout";
return { actions, spokenFeedback, toastMessage };
} else if (lower.includes('review') || lower.includes('step 2') || lower.includes('shopping list') || lower.includes('curate') || lower.includes('তালিকা') || lower.includes('লিস্ট') || lower.includes('लिस्ट') || (lower.includes('next step') && activeTab === 'define')) {
actions.push({ type: 'NAVIGATE_TAB', payload: { tab: 'review' } });
spokenFeedback = language === 'bn' ? "আপনার কিউরেট করা শপিং লিস্ট দেখাচ্ছি।" : language === 'hi' ? "आपकी शॉपिंग लिस्ट पर जा रहे हैं।" : "Navigating to your curated shopping list.";
toastMessage = language === 'bn' ? "👉 শপিং লিস্ট" : language === 'hi' ? "👉 शॉपिंग लिस्ट" : "👉 Review List";
return { actions, spokenFeedback, toastMessage };
} else if (lower.includes('define') || lower.includes('step 1') || lower.includes('event details') || lower.includes('go back') || lower.includes('ফিরে যান') || lower.includes('वापस')) {
actions.push({ type: 'NAVIGATE_TAB', payload: { tab: 'define' } });
spokenFeedback = language === 'bn' ? "ইভেন্টের বিবরণে ফিরে যাচ্ছি।" : language === 'hi' ? "इवेंट विवरण पर वापस जा रहे हैं।" : "Navigating to event definition.";
toastMessage = language === 'bn' ? "👉 ইভেন্ট বিবরণ" : language === 'hi' ? "👉 इवेंट विवरण" : "👉 Define Event";
return { actions, spokenFeedback, toastMessage };
}
// 7. Generate Plan (প্ল্যান তৈরি / योजना बनाएं / generate plan)
if (lower.includes('generate plan') || lower.includes('create plan') || lower.includes('create list') || lower.includes('generate shopping list') || lower.includes('প্ল্যান তৈরি') || lower.includes('তৈরি করুন') || lower.includes('योजना बनाएं')) {
actions.push({ type: 'GENERATE_PLAN', payload: {} });
spokenFeedback = language === 'bn' ? "আপনার IndianMart পার্টি প্ল্যান এবং শপিং লিস্ট তৈরি করা হচ্ছে।" : language === 'hi' ? "आपकी IndianMart पार्टी योजना तैयार की जा रही है।" : "Generating your customized IndianMart party plan now.";
toastMessage = language === 'bn' ? "✨ প্ল্যান তৈরি হচ্ছে" : language === 'hi' ? "✨ पार्टी योजना तैयार" : "✨ Generating Plan";
return { actions, spokenFeedback, toastMessage };
}
// 8. Order Placement (অর্ডার করুন / অর্ডার দিন / ऑर्डर दें / place order)
if (lower.includes('place order') || lower.includes('confirm order') || lower.includes('complete order') || lower.includes('buy now') || lower.includes('অর্ডার') || lower.includes('কনফার্ম') || lower.includes('ऑर्डर दें') || lower.includes('खरीदें')) {
actions.push({ type: 'PLACE_ORDER', payload: {} });
spokenFeedback = language === 'bn' ? "IndianMart এক্সপ্রেস ডেলিভারিতে আপনার অর্ডার নিশ্চিত করা হচ্ছে!" : language === 'hi' ? "IndianMart एक्सप्रेस डिलीवरी पर आपका ऑर्डर दिया जा रहा है!" : "Placing your party order on IndianMart express delivery!";
toastMessage = language === 'bn' ? "🎉 অর্ডার সফল!" : language === 'hi' ? "🎉 অর্ডার सफल!" : "🎉 Order Placed!";
return { actions, spokenFeedback, toastMessage };
}
// 9. Budget Status (বাজেট কত / মোট খরচ / कुल कितना / total)
if (lower.includes('total') || lower.includes('budget') || lower.includes('মোট কত') || lower.includes('খরচ কত') || lower.includes('বাজেট') || lower.includes('कुल') || lower.includes('बजट')) {
actions.push({ type: 'READ_SUMMARY', payload: {} });
spokenFeedback = language === 'bn'
? `আপনার বর্তমান মোট খরচ ₹${currentTotal} এবং টার্গেট বাজেট ₹${budget}।`
: language === 'hi'
? `आपका वर्तमान कुल ₹${currentTotal} है और लक्ष्य बजट ₹${budget} है।`
: `Your current total is ₹${currentTotal} against your target budget of ₹${budget}.`;
toastMessage = `💰 Total: ₹${currentTotal}`;
return { actions, spokenFeedback, toastMessage };
}
// 10. Auto Balance (বাজেট ব্যালেন্স / संतुलित / auto balance)
if (lower.includes('auto balance') || lower.includes('balance budget') || lower.includes('fit to budget') || lower.includes('ব্যালেন্স') || lower.includes('সমান') || lower.includes('संतुलित')) {
actions.push({ type: 'AUTO_BALANCE', payload: { mode: 'balance_exact' } });
spokenFeedback = language === 'bn' ? "আপনার শপিং লিস্ট টার্গেট বাজেটের সাথে ব্যালেন্স করা হচ্ছে।" : language === 'hi' ? "आपकी शॉपिंग लिस्ट को बजट के अनुसार संतुलित किया जा रहा है।" : "Auto-balancing your shopping list to match your target budget.";
toastMessage = language === 'bn' ? "⚡ বাজেট ব্যালেন্স" : language === 'hi' ? "⚡ बजट संतुलित" : "⚡ Auto-Balanced";
return { actions, spokenFeedback, toastMessage };
}
// 11. Guest Count Extraction (e.g., "২৫ জন অতিথি", "30 guests", "25 मेहमान")
const guestMatch = lower.match(/(\d+)\s*(guests?|people|persons?|জন|অতিথি|মানুষ|मेहमान|लोग)/i) || lower.match(/(?:guests?|অতিথি|জন|मेहমান)\s*(?:to|is)?\s*(\d+)/i);
if (guestMatch) {
const num = parseInt(guestMatch[1] || guestMatch[2], 10);
if (!isNaN(num) && num > 0) {
actions.push({ type: 'SET_EVENT_FIELD', payload: { field: 'guestCount', value: num, numericValue: num } });
spokenFeedback = language === 'bn' ? `অতিথির সংখ্যা ${num} জন নির্ধারণ করা হয়েছে।` : language === 'hi' ? `मेहमानों की संख्या ${num} सेट की गई।` : `Updated guest count to ${num} people.`;
toastMessage = `👥 Guests: ${num}`;
return { actions, spokenFeedback, toastMessage };
}
}
// 12. Budget Amount Extraction (e.g., "বাজেট ১৫০০০", "budget 12000", "बजट 10000")
const budgetMatch = lower.match(/(?:budget|বাজেট|টাকা|बजट|रुपये)\s*(?:to|is)?\s*(?:₹|rs\.?|rupees|টাকা|रुपये)?\s*(\d+)/i) || lower.match(/(\d+)\s*(?:rupees|budget|inr|টাকা|বাজেট|रुपये)/i);
if (budgetMatch) {
const num = parseInt(budgetMatch[1] || budgetMatch[2], 10);
if (!isNaN(num) && num > 0) {
actions.push({ type: 'SET_EVENT_FIELD', payload: { field: 'targetBudget', value: num, numericValue: num } });
spokenFeedback = language === 'bn' ? `আপনার টার্গেট বাজেট ₹${num} নির্ধারণ করা হয়েছে।` : language === 'hi' ? `आपका लक्ष्य बजट ₹${num} निर्धारित किया गया।` : `Updated your target budget to ₹${num}.`;
toastMessage = `💰 Budget: ₹${num}`;
return { actions, spokenFeedback, toastMessage };
}
}
// 13. Add Item Extraction (e.g., "২ প্যাকেট সিঙ্গাড়া যোগ করুন", "add samosas", "समोसे जोड़ें")
if (lower.includes('যোগ') || lower.includes('जोड़ें') || lower.includes('add') || lower.includes('include') || lower.includes('put') || lower.includes('দাও')) {
let cleanItem = lower
.replace(/^(?:please\s+|can\s+you\s+)?(?:add|include|put|যোগ করুন|যোগ|जोड़ें|ডাল|লাগবে)/i, '')
.replace(/(?:যোগ করুন|যোগ|जोड़ें|add|দাও|দিন|দিয়ে দাও|চাই|লাগবে)$/i, '')
.trim();
let qty = 1;
const qtyMatch = cleanItem.match(/^(\d+)\s*(?:packs?|packets?|pieces?|packs?\s+of\s+|প্যাকেট|পিস|টি|पैकेट|पीस)?\s*/i);
if (qtyMatch) {
qty = parseInt(qtyMatch[1], 10) || 1;
cleanItem = cleanItem.replace(qtyMatch[0], '').trim();
}
if (cleanItem && cleanItem.length >= 2 && !cleanItem.includes('budget') && !cleanItem.includes('guest') && !cleanItem.includes('বাজেট') && !cleanItem.includes('অতিথি') && !cleanItem.includes('জন')) {
actions.push({ type: 'ADD_ITEM', payload: { query: cleanItem, quantity: qty } });
spokenFeedback = language === 'bn'
? `ক্যাটালগ থেকে ${qty > 1 ? qty + 'টি ' : ''}${cleanItem} শপিং লিস্টে যোগ করা হয়েছে।`
: language === 'hi'
? `कैटलॉग से ${qty > 1 ? qty + ' ' : ''}${cleanItem} शॉपिंग लिस्ट में जोड़ दिया गया है।`
: `Added ${qty > 1 ? qty + ' of ' : ''}${cleanItem} to your shopping list.`;
toastMessage = `➕ ${cleanItem}`;
return { actions, spokenFeedback, toastMessage };
}
}
// 14. Remove Item Extraction (e.g., "সিঙ্গাড়া মুছে দিন", "remove samosas", "समोसा हटाएं")
const removeMatch = lower.match(/(?:remove|delete|drop|মুছে দিন|বাদ দিন|হটাও|हटाएं)\s+([a-z0-9\s'-\u0900-\u097F\u0980-\u09FF]+)/i) || lower.match(/([a-z0-9\s'-\u0900-\u097F\u0980-\u09FF]+)\s+(?:মুছে দিন|বাদ দিন|हटाएं|हटाओ)/i);
if (removeMatch && !lower.includes('budget') && !lower.includes('guest')) {
const itemName = removeMatch[1].trim();
actions.push({ type: 'REMOVE_ITEM', payload: { itemName } });
spokenFeedback = language === 'bn' ? `আপনার শপিং লিস্ট থেকে ${itemName} বাদ দেওয়া হয়েছে।` : language === 'hi' ? `आपकी लिस्ट से ${itemName} को हटा दिया गया है।` : `Removed ${itemName} from your list.`;
toastMessage = `🗑️ Removed ${itemName}`;
return { actions, spokenFeedback, toastMessage };
}
// 15. General Conversational Fallback
if (language === 'bn') {
spokenFeedback = `আমি আপনার কথা বুঝতে পেরেছি: "${transcript}"। আপনি আমাকে অতিথি সংখ্যা পরিবর্তন, খাবারের পরিমাণ হিসাব, বাজেট সমন্বয়, বা যেকোনো আইটেম যোগ করার জন্য বলতে পারেন।`;
toastMessage = `🎙️ "${transcript.slice(0, 18)}..."`;
} else if (language === 'hi') {
spokenFeedback = `मैंने सुना: "${transcript}"। आप मुझसे खाने की मात्रा, बजट, स्नैक्स सुझाव या लिस्ट में आइटम जोड़ने के बारे में पूछ सकते हैं।`;
toastMessage = `🎙️ "${transcript.slice(0, 18)}..."`;
} else {
spokenFeedback = `I understood: "${transcript}". You can ask me for portion calculations, food recommendations, budget advice, or to add items to your list.`;
toastMessage = `🎙️ "${transcript.slice(0, 18)}..."`;
}
return { actions, spokenFeedback, toastMessage };
}
function generateAssistantFallbackReply(msg: string, eventContext: any = {}, cartContext: any = {}): string {
const lower = msg.toLowerCase();
const guests = eventContext.guestCount || 20;
const budget = eventContext.targetBudget || 10000;
const city = eventContext.city || 'Bengaluru';
if (lower.includes('portion') || lower.includes('how much') || lower.includes('quantity') || lower.includes('biryani')) {
return `### 🍛 Quantity Guidelines for ${guests} Guests\n\nHere is the IndianMart rule of thumb for Indian catering:\n\n- **Main Course (Biryani/Pulao):** ~150g–180g cooked per person = **${(guests * 0.18).toFixed(1)} kg** total.\n- **Appetizers & Samosas:** 2 to 3 pieces per guest = **${Math.ceil(guests * 2.5)} pieces**.\n- **Mithai / Sweets:** 1.5 to 2 pieces per guest = **${Math.ceil(guests * 1.8)} pieces** (approx ${(guests * 0.05).toFixed(1)} kg).\n- **Beverages / Coolers:** 250ml per person = **${Math.ceil(guests * 0.3)} Liters**.\n- **Areca Palm Tableware:** 1 full dinner set per guest + 20% backup buffer = **${Math.ceil(guests * 1.2)} sets**.\n\nWould you like me to add any specific items to your shopping list?`;
}
if (lower.includes('jain') || lower.includes('vegetarian') || lower.includes('dietary')) {
return `### 🌱 Jain & Pure Veg Friendly Options\n\nFor a 100% Jain-friendly gathering in ${city}:\n\n- **Snacks:** Haldiram's Jain Samosas (made with raw banana instead of potato), roasted Makhana, Khandvi, and Dhokla.\n- **Mains:** Paneer Makhani (No onion, no garlic cashew gravy) + Tata Sampann Jeera Rice.\n- **Beverages:** Paper Boat Aamras & Rooh Afza Gulab Sharbat.\n- **Mithai:** Kesar Pista Kulfi and Bikanervala Kaju Katli.\n\nAll items are labeled with Green Dot & Jain verification on IndianMart!`;
}
if (lower.includes('budget') || lower.includes('save') || lower.includes('reduce') || lower.includes('cheap')) {
return `### 💡 Smart Budget Tips (Target: ₹${budget})\n\n1. **Value Pack Swaps:** Choose 1kg family tins of Gulab Jamun instead of individual sweet boxes (saves ~25%).\n2. **Concentrated Syrups:** Using Rooh Afza or Real mocktail cordials with club soda costs ~₹8/glass vs ₹35/can for ready-to-drink cans.\n3. **Combo Tableware:** 10-inch Areca Palm multi-compartment thalis reduce separate katori bowl expenses by 40%!\n\nYou can also click the **Auto-Balance** button on the Review List to instantly align your list to ₹${budget}.`;
}
if (lower.includes('delivery') || lower.includes('time') || lower.includes('slot') || lower.includes('shipping')) {
return `### 🚚 IndianMart Delivery in ${city}\n\n- **30-Min Express Instant Delivery:** Available 24/7 across ${city} for chilled mocktails, ice, samosas, and fresh sweets.\n- **Party Slot (5 PM - 7 PM):** Scheduled delivery right before your evening gathering.\n- **Free Shipping:** Automatic free delivery on all party orders over ₹999!`;
}
return `Namaste! I am your **IndianMart Assistant**. I'm here to help you curate, portion, and optimize everything for your **${eventContext.occasionTitle || 'Party'}** for **${guests} guests** in ${city}.\n\nFeel free to ask me about:\n- Exact food & beverage portion calculations\n- Jain, vegan, or kid-friendly snack ideas\n- How to fit your ₹${budget} budget\n- Ambiance, lighting, and eco-friendly tableware recommendations`;
}
// Smart local rule-based fallback generator
function generateSmartCatalogPlan(params: any) {
const {
occasion = 'diwali_festive',
occasionTitle = 'Festive Indian Gathering',
themeDescription = 'Celebratory gathering with authentic Indian snacks, sweets, and decor',
guestCount = 20,
targetBudget = 12000,
dietary = 'pure_veg',
ecoFriendly = true
} = params;
// Scale multipliers based on guest count
const guestFactor = Math.max(0.5, guestCount / 20);
const baseItems = [
{
id: 'snack-1',
name: 'Haldiram\'s Cocktail Samosas (Party Pack)',
brand: 'Haldiram\'s',
category: 'food_snacks',
unitPrice: 280,
quantity: Math.max(1, Math.round(2 * guestFactor)),
unitSize: 'Pack of 20 pcs (600g)',
portionsPerUnit: 'Serves 6-8',
isEssential: true,
tags: ['Bestseller', 'Pure Veg', 'Quick Fry'],
alternative: {
name: 'Bikaji Mini Samosa Namkeen',
unitPrice: 160,
savingAmount: 120,
reason: 'Economical dry snack alternative'
}
},
{
id: 'snack-2',
name: 'Haldiram\'s Pani Puri & Papdi Chaat Magic Kit',
brand: 'Haldiram\'s',
category: 'food_snacks',
unitPrice: 220,
quantity: Math.max(1, Math.round(2 * guestFactor)),
unitSize: '50 Puris + Chutney & Boondi kit',
portionsPerUnit: 'Serves 10',
isEssential: true,
tags: ['Crowd Favorite', 'Pure Veg', 'Instant Chaat'],
alternative: {
name: 'Haldiram\'s Bhel Puri Combo Box',
unitPrice: 150,
savingAmount: 70,
reason: 'Faster assembly dry chaat mix'
}
},
{
id: 'snack-3',
name: dietary === 'veg_and_nonveg' ? 'IndianMart Kitchen Chicken Tikka & Paneer Platter' : 'Amul Marinated Paneer Tikka Skewers',
brand: 'Amul / IndianMart',
category: 'food_snacks',
unitPrice: dietary === 'veg_and_nonveg' ? 390 : 340,
quantity: Math.max(1, Math.round(2.5 * guestFactor)),
unitSize: '500g pack (12 skewers)',
portionsPerUnit: 'Serves 4-6',
isEssential: true,
tags: ['High Protein', 'Chef Special'],
},
{
id: 'snack-4',
name: 'Tata Sampann Salted Cashews & California Almonds Combo',
brand: 'Tata Sampann',
category: 'food_snacks',
unitPrice: 480,
quantity: Math.max(1, Math.round(1.5 * guestFactor)),
unitSize: '500g Jar Combo',
portionsPerUnit: 'Nibbles for 15-20',
isEssential: true,
tags: ['Premium Dry Fruits', 'Jain Friendly'],
},
{
id: 'main-1',
name: 'IndianMart Kitchen Dum Biryani Handi Party Tray (with Raita & Salan)',
brand: 'IndianMart Kitchen',
category: 'main_course',
unitPrice: 850,
quantity: Math.max(1, Math.round(2 * guestFactor)),
unitSize: '1.5kg Party Tray',
portionsPerUnit: 'Serves 6-8',
isEssential: true,
tags: ['Party Hero Dish', 'Authentic Dum'],
},
{
id: 'main-2',
name: 'MTR Dal Makhani & Paneer Butter Masala Catering Combo',
brand: 'MTR',
category: 'main_course',
unitPrice: 420,
quantity: Math.max(1, Math.round(2 * guestFactor)),
unitSize: 'Pack of 3 x 300g Pouches',
portionsPerUnit: 'Serves 6-8',
isEssential: true,
tags: ['Ready in 5 Mins', 'Rich Gravy'],
},
{
id: 'main-3',
name: 'Harvest Gold Tandoori Butter Naan & Kulchas',
brand: 'Harvest Gold',
category: 'main_course',
unitPrice: 150,
quantity: Math.max(2, Math.round(3.5 * guestFactor)),
unitSize: 'Pack of 6 pieces',
portionsPerUnit: 'Serves 3-4',
isEssential: true,
tags: ['Soft & Fluffy'],
},
{
id: 'bev-1',
name: 'Hamdard Rooh Afza Herbal Sharbat Bottle',
brand: 'Hamdard',
category: 'beverages',
unitPrice: 185,
quantity: Math.max(1, Math.round(1 * guestFactor)),
unitSize: '750ml Glass Bottle',
portionsPerUnit: 'Makes 25-30 glasses',
isEssential: true,
tags: ['Classic Indian Chiller', 'Crowd Pleaser'],
},
{
id: 'bev-2',
name: 'Thums Up & Limca Carbonated Cans Party Pack',
brand: 'Coca-Cola / Thums Up',
category: 'beverages',
unitPrice: 360,
quantity: Math.max(1, Math.round(2 * guestFactor)),
unitSize: 'Pack of 6 x 300ml Cans',
portionsPerUnit: '12 Servings',
isEssential: true,
tags: ['Party Chiller', 'Chilled Delivery'],
},
{
id: 'sweet-1',
name: 'Haldiram\'s Desi Ghee Gulab Jamun Tin',
brand: 'Haldiram\'s',
category: 'sweets_desserts',
unitPrice: 260,
quantity: Math.max(1, Math.round(2 * guestFactor)),
unitSize: '1kg Tin (16-18 pcs)',
portionsPerUnit: 'Serves 8-10',
isEssential: true,
tags: ['Celebration Must-Have', 'Desi Ghee'],
},
{
id: 'sweet-2',
name: 'Bikanervala Premium Silver Foil Kaju Katli Gift Box',
brand: 'Bikanervala',
category: 'sweets_desserts',
unitPrice: 580,