-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
797 lines (693 loc) · 35.8 KB
/
index.html
File metadata and controls
797 lines (693 loc) · 35.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Order Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/LeaVerou/awesomplete@master/awesomplete.css">
<script src="https://cdn.jsdelivr.net/gh/LeaVerou/awesomplete@master/awesomplete.min.js"></script>
</head>
<body class="bg-gray-100">
<div class="container mx-auto px-4 py-8">
<!-- Header -->
<div class="mb-8">
<h1 class="text-3xl font-bold text-gray-800">Order Form</h1>
<p class="text-gray-600">Select items from <a id="inventoryLink" href="#" target="_blank" class="text-blue-600 hover:text-blue-800 underline">our inventory</a></p>
</div>
<!-- Configuration Section -->
<div id="configSection" class="bg-white p-6 rounded-lg shadow-md mb-8">
<h2 class="text-xl font-semibold mb-4">Configuration</h2>
<div class="space-y-4">
<div>
<label class="block text-gray-700 mb-2">Inventory Sheet URL</label>
<input type="text" id="csvUrl" class="w-full p-2 border rounded"
placeholder="Enter CSV URL, Google Sheets URL, or ?sheetId=YOUR_SHEET_ID">
</div>
<div>
<label class="block text-gray-700 mb-2">Google Form URL</label>
<input type="text" id="googleFormUrl" class="w-full p-2 border rounded"
placeholder="Enter Google Form URL (https://forms.gle/...)">
</div>
<button id="loadInventory"
class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
Load Inventory
</button>
</div>
</div>
<!-- Tabs -->
<div class="bg-white rounded-lg shadow-md">
<!-- Tab Navigation -->
<div class="border-b border-gray-200">
<nav class="-mb-px flex space-x-8">
<button id="selectItemsTab" class="border-b-2 border-blue-500 py-4 px-1 text-blue-600 font-medium text-sm whitespace-nowrap">
Select Items
</button>
<button id="checkoutTab" class="border-b-2 border-transparent py-4 px-1 text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium text-sm whitespace-nowrap">
Checkout
</button>
</nav>
</div>
<!-- Tab Content -->
<!-- Select Items Tab -->
<div id="selectItemsContent" class="p-6">
<div id="loading" class="hidden">
<div class="flex items-center justify-center p-4">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
<span class="ml-2">Loading inventory...</span>
</div>
</div>
<!-- Search Filter -->
<div class="mb-6" id="searchContainer" style="display: none;">
<div class="relative max-w-md">
<input type="text"
id="productSearch"
class="w-full p-3 pr-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
placeholder="Search products...">
<button id="clearSearch"
class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 p-1 hidden">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
</button>
</div>
</div>
<div id="categories" class="space-y-6 mb-8"></div>
<div class="border-t pt-6 text-center">
<button id="proceedToCheckout"
class="bg-blue-500 text-white px-6 py-3 rounded-lg hover:bg-blue-600 text-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed"
disabled>
Proceed to Checkout
</button>
</div>
</div>
<!-- Checkout Tab -->
<div id="checkoutContent" class="p-6 hidden">
<!-- Customer Information -->
<div class="mb-8">
<h2 class="text-xl font-semibold mb-4">Customer Information</h2>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label class="block text-gray-700 mb-2">Name *</label>
<input type="text" id="customerName" class="w-full p-2 border rounded" required>
</div>
<div>
<label class="block text-gray-700 mb-2">Address</label>
<input type="text" id="customerEmail" class="w-full p-2 border rounded">
</div>
<div>
<label class="block text-gray-700 mb-2">Phone</label>
<input type="tel" id="customerPhone" class="w-full p-2 border rounded">
</div>
</div>
</div>
<!-- Order Summary -->
<div class="mb-8">
<h2 class="text-xl font-semibold mb-4">Order Summary</h2>
<div class="overflow-x-auto">
<table class="w-full border-collapse border border-gray-300">
<thead>
<tr class="bg-gray-100">
<th class="border border-gray-300 px-4 py-2 text-left">Category</th>
<th class="border border-gray-300 px-4 py-2 text-left">Product</th>
<th class="border border-gray-300 px-4 py-2 text-left">Quantity</th>
<th class="border border-gray-300 px-4 py-2 text-left">Unit Price</th>
<th class="border border-gray-300 px-4 py-2 text-left">Total</th>
</tr>
</thead>
<tbody id="checkoutTableBody">
</tbody>
</table>
</div>
</div>
<!-- Order Total -->
<div class="text-right mb-8">
<div class="text-2xl font-bold">
Total: ₹<span id="orderTotal">0</span>
</div>
</div>
<!-- Submit Button -->
<div class="text-center">
<button id="submitOrder"
class="bg-green-500 text-white px-6 py-3 rounded-lg hover:bg-green-600 text-lg font-medium">
Submit Order
</button>
</div>
</div>
</div>
</div>
<script>
// Add these functions at the beginning of your script
function getSheetIdFromUrl(url) {
// Handle direct sheetId parameter
if (url.startsWith('?sheetId=')) {
return url.replace('?sheetId=', '');
}
// Handle Google Sheets edit URL (https://docs.google.com/spreadsheets/d/SHEET_ID/edit...)
let matches = url.match(/spreadsheets\/d\/([a-zA-Z0-9-_]+)/);
if (matches) {
return matches[1];
}
// Handle published Google Sheets CSV URL (spreadsheets/d/e/SHEET_ID)
matches = url.match(/spreadsheets\/d\/e\/([-\w]+)/);
return matches ? matches[1] : null;
}
function updateUrlWithSheetId(sheetId) {
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('sheetId', sheetId);
window.history.pushState({}, '', newUrl);
}
// Modify the document ready function
$(document).ready(function() {
let inventory = [];
let currentOrders = [];
let awesomplete = null;
let allProducts = [];
// Tab switching functionality
function switchToTab(tabName) {
if (tabName === 'selectItems') {
$('#selectItemsTab').addClass('border-blue-500 text-blue-600').removeClass('border-transparent text-gray-500');
$('#checkoutTab').addClass('border-transparent text-gray-500').removeClass('border-blue-500 text-blue-600');
$('#selectItemsContent').show();
$('#checkoutContent').hide();
} else if (tabName === 'checkout') {
$('#selectItemsTab').addClass('border-transparent text-gray-500').removeClass('border-blue-500 text-blue-600');
$('#checkoutTab').addClass('border-blue-500 text-blue-600').removeClass('border-transparent text-gray-500');
$('#selectItemsContent').hide();
$('#checkoutContent').show();
updateCheckoutTable();
}
}
// Tab click handlers
$('#selectItemsTab').click(function() {
switchToTab('selectItems');
});
$('#checkoutTab').click(function() {
switchToTab('checkout');
});
// Proceed to checkout functionality
$('#proceedToCheckout').click(function() {
switchToTab('checkout');
});
// Function to update checkout table
function updateCheckoutTable() {
const orders = [];
let totalAmount = 0;
$('.order-quantity').each(function() {
const quantity = $(this).val();
if (quantity && quantity > 0) {
const $input = $(this);
const product = $input.data('product');
const cost = parseFloat($input.data('cost'));
const unit = $input.data('unit');
// Find the category for this product
const category = $input.closest('.category-section').find('h3').text();
const itemTotal = cost * parseFloat(quantity);
totalAmount += itemTotal;
orders.push({
category: category,
product: product,
unit: unit,
cost: cost,
quantity: quantity,
total: itemTotal
});
}
});
currentOrders = orders;
// Update checkout table
const $tableBody = $('#checkoutTableBody');
$tableBody.empty();
orders.forEach(order => {
const row = `
<tr>
<td class="border border-gray-300 px-4 py-2">${order.category}</td>
<td class="border border-gray-300 px-4 py-2">${order.product}</td>
<td class="border border-gray-300 px-4 py-2">${order.quantity} ${order.unit}</td>
<td class="border border-gray-300 px-4 py-2">₹${order.cost}</td>
<td class="border border-gray-300 px-4 py-2">₹${order.total}</td>
</tr>
`;
$tableBody.append(row);
});
$('#orderTotal').text(totalAmount);
}
// Function to update proceed button state
function updateProceedButton() {
let hasItems = false;
$('.order-quantity').each(function() {
if ($(this).val() > 0) {
hasItems = true;
return false; // break
}
});
$('#proceedToCheckout').prop('disabled', !hasItems);
}
// Extract loading logic into a separate function
function loadInventoryFromUrl(inputUrl) {
$('#loading').removeClass('hidden');
// Convert Google Sheets URL to CSV export URL if needed
let csvUrl = inputUrl;
const sheetId = getSheetIdFromUrl(inputUrl);
// If we got a sheet ID from a Google Sheets URL, convert to CSV export URL
if (sheetId && inputUrl.includes('docs.google.com')) {
csvUrl = `https://docs.google.com/spreadsheets/d/${sheetId}/export?format=csv`;
}
$.get(csvUrl, function(data) {
try {
inventory = parseCSV(data);
displayInventory(inventory);
$('#loading').addClass('hidden');
} catch (e) {
$('#loading').addClass('hidden');
alert('Error parsing CSV data: ' + e.message);
}
}).fail(function(error) {
$('#loading').addClass('hidden');
alert('Error loading inventory: ' + error.statusText);
});
}
// Functions to save and load customer info
function saveCustomerInfo() {
const customerInfo = {
name: $('#customerName').val(),
email: $('#customerEmail').val(),
phone: $('#customerPhone').val()
};
localStorage.setItem('customerInfo', JSON.stringify(customerInfo));
}
function loadCustomerInfo() {
const savedInfo = localStorage.getItem('customerInfo');
if (savedInfo) {
try {
const customerInfo = JSON.parse(savedInfo);
$('#customerName').val(customerInfo.name || '');
$('#customerEmail').val(customerInfo.email || '');
$('#customerPhone').val(customerInfo.phone || '');
} catch (e) {
console.error('Error loading customer info:', e);
}
}
}
// Check URL parameters first
const urlParams = new URLSearchParams(window.location.search);
const sheetId = urlParams.get('sheetId');
const formUrl = urlParams.get('formUrl');
let csvUrlToLoad = null;
if (sheetId) {
csvUrlToLoad = `https://docs.google.com/spreadsheets/d/${sheetId}/export?format=csv`;
$('#csvUrl').val(csvUrlToLoad);
} else {
// Fall back to localStorage
const lastUsedUrl = localStorage.getItem('lastUsedCsvUrl');
if (lastUsedUrl) {
$('#csvUrl').val(lastUsedUrl);
csvUrlToLoad = lastUsedUrl;
// Update inventory link with saved URL
const savedSheetId = getSheetIdFromUrl(lastUsedUrl);
if (savedSheetId) {
updateInventoryLink(savedSheetId, lastUsedUrl);
}
}
}
if (formUrl) {
$('#googleFormUrl').val(decodeURIComponent(formUrl));
} else {
// Fall back to localStorage
const lastUsedFormUrl = localStorage.getItem('lastUsedFormUrl');
if (lastUsedFormUrl) {
$('#googleFormUrl').val(lastUsedFormUrl);
}
}
// Load saved customer info
loadCustomerInfo();
// Update inventory link if we have a sheet ID
function updateInventoryLink(sheetId, originalUrl) {
const $inventoryLink = $('#inventoryLink');
if (sheetId) {
// If we have the original Google Sheets URL, use it; otherwise construct one
if (originalUrl && originalUrl.includes('docs.google.com')) {
$inventoryLink.attr('href', originalUrl);
} else {
$inventoryLink.attr('href', `https://docs.google.com/spreadsheets/d/${sheetId}/edit`);
}
} else {
$inventoryLink.removeAttr('href').css('cursor', 'default').removeClass('text-blue-600 hover:text-blue-800').addClass('text-gray-600');
}
}
// Check if we have valid configuration from URL params
const hasValidConfig = sheetId && (formUrl || localStorage.getItem('lastUsedFormUrl'));
// Update inventory link
updateInventoryLink(sheetId, null);
// Hide configuration section if we have valid URL params
if (hasValidConfig) {
$('#configSection').hide();
}
// Auto-load inventory if both URLs are available
if (csvUrlToLoad && (formUrl || localStorage.getItem('lastUsedFormUrl'))) {
loadInventoryFromUrl(csvUrlToLoad);
}
// Add event handlers to save customer info when fields change
$('#customerName, #customerEmail, #customerPhone').on('input blur', function() {
saveCustomerInfo();
});
// Modify the load inventory click handler
$('#loadInventory').click(function() {
const csvUrl = $('#csvUrl').val();
const googleFormUrl = $('#googleFormUrl').val();
const sheetId = getSheetIdFromUrl(csvUrl);
// Update URL with both parameters
const newUrl = new URL(window.location.href);
if (sheetId) {
newUrl.searchParams.set('sheetId', sheetId);
localStorage.setItem('lastUsedCsvUrl', csvUrl);
}
if (googleFormUrl) {
newUrl.searchParams.set('formUrl', encodeURIComponent(googleFormUrl));
localStorage.setItem('lastUsedFormUrl', googleFormUrl);
}
window.history.pushState({}, '', newUrl);
// Update inventory link
updateInventoryLink(sheetId, csvUrl);
loadInventoryFromUrl(csvUrl);
});
// Update the parseCSV function to handle comma-separated values
function parseCSV(csv) {
const lines = csv.split('\n');
const result = [];
const headers = lines[0].split(',').map(h => h.trim());
for(let i = 1; i < lines.length; i++) {
if(!lines[i]) continue;
const obj = {};
const currentline = lines[i].split(',');
for(let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j] ? currentline[j].trim() : '';
}
result.push(obj);
}
return result;
}
// Initialize autocomplete search
function initializeSearch() {
allProducts = inventory.map(item => ({
label: `${item.Product} - ${item.Category}`,
value: item.Product,
item: item
}));
const searchInput = document.getElementById('productSearch');
awesomplete = new Awesomplete(searchInput, {
list: allProducts.map(p => p.label),
minChars: 1,
maxItems: 8,
autoFirst: true
});
// Show search container
$('#searchContainer').show();
// Handle search input
$('#productSearch').on('input', function() {
const searchTerm = $(this).val().toLowerCase().trim();
$('#clearSearch').toggle(searchTerm.length > 0);
filterProducts(searchTerm);
});
// Handle autocomplete selection
searchInput.addEventListener('awesomplete-selectcomplete', function(e) {
const selectedProduct = allProducts.find(p => p.label === e.text);
if (selectedProduct) {
scrollToProduct(selectedProduct.item.Product);
}
});
}
// Filter products based on search term
function filterProducts(searchTerm) {
if (!searchTerm) {
$('.category-section, .item-container').show();
return;
}
$('.item-container').each(function() {
const $item = $(this);
const productName = $item.find('h4').text().toLowerCase();
const categoryName = $item.closest('.category-section').find('h3').text().toLowerCase();
if (productName.includes(searchTerm) || categoryName.includes(searchTerm)) {
$item.show();
} else {
$item.hide();
}
});
// Hide empty categories
$('.category-section').each(function() {
const $category = $(this);
const visibleItems = $category.find('.item-container:visible').length;
$category.toggle(visibleItems > 0);
});
}
// Scroll to specific product
function scrollToProduct(productName) {
$('.item-container').each(function() {
const $item = $(this);
const itemProductName = $item.find('h4').text();
if (itemProductName === productName) {
$item[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
$item.addClass('ring-2 ring-blue-500');
setTimeout(() => $item.removeClass('ring-2 ring-blue-500'), 2000);
return false; // break
}
});
}
// Clear search functionality
$('#clearSearch').click(function() {
$('#productSearch').val('').trigger('input').focus();
});
// Display inventory grouped by category
function displayInventory(inventory) {
const $categories = $('#categories');
$categories.empty();
const groupedInventory = groupByCategory(inventory);
Object.keys(groupedInventory).forEach(category => {
const $category = $(`
<div class="category-section">
<h3 class="text-lg font-semibold mb-3">${category}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-4"></div>
</div>
`);
groupedInventory[category].forEach(item => {
const imageHtml = item.Image ? `<img src="${item.Image}" alt="${item.Product}" class="w-full h-32 object-cover rounded mb-3" onerror="this.style.display='none'">` : '';
const $item = $(`
<div class="border p-4 rounded item-container">
${imageHtml}
<h4 class="font-medium">${item.Product}</h4>
<p class="text-gray-600">₹${item.Cost}/${item.Unit}</p>
<div class="mt-2 flex items-center space-x-2 controls-container">
<input type="number"
class="order-quantity w-20 p-1 border rounded"
min="${item['Min Unit']}"
max="${item['Available Units']}"
step="${item['Min Unit']}"
value="0"
data-product="${item.Product}"
data-cost="${item.Cost}"
data-min-unit="${item['Min Unit']}"
data-unit="${item.Unit}">
<button class="add-btn bg-green-500 text-white px-2 py-1 rounded hover:bg-green-600">
Add
</button>
<button class="remove-btn bg-red-500 text-white px-2 py-1 rounded hover:bg-red-600 hidden">
Remove
</button>
</div>
<div class="mt-2">
<span class="order-count" style="display: none;">Quantity: <span class="count">0</span></span>
<div class="total-price" style="display: none;" class="text-sm text-gray-600"></div>
</div>
</div>
`);
// Add click handlers
$item.find('.add-btn').click(function(e) {
e.preventDefault();
const $container = $(this).closest('.controls-container');
const $input = $container.find('.order-quantity');
const minUnit = parseFloat($input.data('min-unit'));
const currentVal = parseFloat($input.val()) || 0;
const newVal = currentVal + minUnit;
if (newVal <= parseFloat($input.attr('max'))) {
$input.val(newVal);
updateItemDisplay($input);
}
});
$item.find('.remove-btn').click(function() {
const $input = $(this).closest('div').find('.order-quantity');
const minUnit = parseFloat($input.data('min-unit'));
const currentVal = parseFloat($input.val()) || 0;
const newVal = currentVal - minUnit;
if (newVal >= 0) {
$input.val(newVal);
updateItemDisplay($input);
}
});
// Add input change handler
$item.find('.order-quantity').on('input', function() {
updateItemDisplay($(this));
});
$category.find('.grid').append($item);
});
$categories.append($category);
});
// Initialize search after displaying inventory
initializeSearch();
}
// Group inventory items by category
function groupByCategory(inventory) {
return inventory.reduce((acc, item) => {
if (!acc[item.Category]) {
acc[item.Category] = [];
}
acc[item.Category].push(item);
return acc;
}, {});
}
// Add this function outside the forEach loop but inside displayInventory
function updateItemDisplay($input) {
const quantity = parseFloat($input.val()) || 0;
const $itemContainer = $input.closest('.item-container');
const $removeBtn = $itemContainer.find('.remove-btn');
const $orderCount = $itemContainer.find('.order-count');
const $totalPrice = $itemContainer.find('.total-price');
if (quantity > 0) {
$removeBtn.removeClass('hidden');
$orderCount.show();
$totalPrice.show();
const unitData = $input.data('unit');
// Extract just the unit name (e.g., "kg" from "1kg")
const unitName = unitData.replace(/^\d+(\.\d+)?/, '');
$orderCount.find('.count').text(`${quantity} ${unitName}`);
const cost = parseFloat($input.data('cost'));
const totalPrice = cost * quantity;
$totalPrice.text(`Rs. ${totalPrice}`);
} else {
$removeBtn.addClass('hidden');
$orderCount.hide();
$totalPrice.hide();
}
// Update proceed button state
updateProceedButton();
}
// Handle order submission
$('#submitOrder').click(function() {
const googleFormUrl = $('#googleFormUrl').val();
const customerName = $('#customerName').val();
const customerEmail = $('#customerEmail').val();
const customerPhone = $('#customerPhone').val();
// Validate required fields
if (!customerName.trim()) {
$('#customerName').focus();
$('#customerName').addClass('border-red-500');
return;
} else {
$('#customerName').removeClass('border-red-500');
}
if (!googleFormUrl.trim()) {
switchToTab('selectItems');
if (!$('#configSection').is(':hidden')) {
$('#googleFormUrl').focus();
$('#googleFormUrl').addClass('border-red-500');
}
return;
} else {
$('#googleFormUrl').removeClass('border-red-500');
}
if (currentOrders.length === 0) {
switchToTab('selectItems');
return;
}
// Calculate total amount
const totalAmount = currentOrders.reduce((sum, order) => sum + order.total, 0);
// Format order details for Google Form
let orderDetails = 'ORDER DETAILS:\n\n';
currentOrders.forEach(order => {
orderDetails += `${order.category} - ${order.product}\n`;
orderDetails += `Quantity: ${order.quantity} ${order.unit}\n`;
orderDetails += `Unit Price: ₹${order.cost}\n`;
orderDetails += `Total: ₹${order.total}\n\n`;
});
orderDetails += `GRAND TOTAL: ₹${totalAmount}`;
// Submit to Google Form directly
submitToGoogleForm(googleFormUrl, {
customerName: customerName,
customerEmail: customerEmail,
customerPhone: customerPhone,
orderDetails: orderDetails,
totalAmount: totalAmount
});
});
// Function to submit data to Google Form
function submitToGoogleForm(formUrl, data) {
// Disable submit button temporarily
$('#submitOrder').prop('disabled', true).text('Submitting...');
// Convert regular form URL to submission URL
let submitUrl = formUrl;
if (submitUrl.includes('/viewform')) {
submitUrl = submitUrl.replace('/viewform', '/formResponse');
} else if (submitUrl.includes('forms.gle')) {
// For shortened URLs, we'll open the form in a new window with pre-filled data
const message = `Please manually fill this information in the Google Form:\n\n` +
`Name: ${data.customerName}\n` +
`Email: ${data.customerEmail}\n` +
`Phone: ${data.customerPhone}\n\n` +
`${data.orderDetails}`;
window.open(formUrl, '_blank');
// Copy the order details to clipboard for easy pasting
navigator.clipboard.writeText(message).then(() => {
// Show success message
$('#submitOrder').text('Order Submitted!').addClass('bg-green-600');
setTimeout(() => {
$('#submitOrder').prop('disabled', false).text('Submit Order').removeClass('bg-green-600');
}, 3000);
}).catch(() => {
$('#submitOrder').prop('disabled', false).text('Submit Order');
});
return;
}
// Create a hidden form to submit data
const $form = $('<form>', {
method: 'POST',
action: submitUrl,
target: '_blank',
style: 'display: none;'
});
// Add form fields with actual entry IDs from your Google Form
$form.append($('<input>', {
name: 'entry.1736322773', // Customer Name field
value: data.customerName
}));
$form.append($('<input>', {
name: 'entry.466504772', // Email field
value: data.customerEmail
}));
$form.append($('<input>', {
name: 'entry.61154094', // Phone field
value: data.customerPhone
}));
$form.append($('<input>', {
name: 'entry.1424632357', // Order Details field
value: data.orderDetails,
type: 'hidden'
}));
$form.append($('<input>', {
name: 'entry.604833501', // Total Amount field
value: data.totalAmount
}));
// Append form to body and submit
$('body').append($form);
$form.submit();
// Show success message
$('#submitOrder').text('Order Submitted!').addClass('bg-green-600');
// Remove the form after submission
setTimeout(() => {
$form.remove();
$('#submitOrder').prop('disabled', false).text('Submit Order').removeClass('bg-green-600');
}, 3000);
}
});
</script>
</body>
</html>