Mango.Nop.Plugins/Nop.Plugin.Misc.AIPlugin/Areas/Admin/Views/VoiceOrder/Create.cshtml

1752 lines
52 KiB
Plaintext

@{
Layout = "_AdminLayout";
ViewBag.PageTitle = "Voice Order Creation";
}
<!-- Mobile-optimized Voice Order Creation -->
<div class="voice-order-mobile">
<!-- Fixed Header with Progress -->
<div class="mobile-header">
<div class="header-content">
<h1><i class="fas fa-microphone-alt"></i> Voice Order</h1>
<div class="progress-dots">
<div id="dot1" class="dot active"></div>
<div id="dot2" class="dot"></div>
</div>
</div>
</div>
<!-- Main Content Area (scrollable) -->
<div class="mobile-content">
<!-- Step 1: Partner Selection -->
<div id="step1" class="step-container active">
<!-- Step Title -->
<div class="step-title">
<span class="step-number">1</span>
<h2>Select Partner</h2>
</div>
<!-- Voice Button (Primary Action) -->
<div class="voice-button-container">
<button id="recordPartnerBtn" class="voice-btn">
<div class="pulse-ring"></div>
<i class="fas fa-microphone"></i>
</button>
<button id="stopPartnerBtn" class="voice-btn recording" style="display: none;">
<i class="fas fa-stop"></i>
</button>
<p class="voice-hint">Tap to speak - auto-stops on silence</p>
</div>
<!-- Recording Status -->
<div id="partnerRecordingStatus" class="status-indicator" style="display: none;">
<div class="spinner"></div>
<span id="partnerStatusText">Listening...</span>
</div>
<!-- OR Divider -->
<div class="divider-or">or</div>
<!-- Text Input (Secondary Option) -->
<div class="input-container">
<input type="text"
id="manualPartnerInput"
class="mobile-input"
placeholder="Type partner name..."
onkeypress="if(event.key === 'Enter') submitManualPartner()">
<button class="search-btn" onclick="submitManualPartner()">
<i class="fas fa-search"></i>
</button>
</div>
<!-- Transcription Result -->
<div id="partnerTranscribedCard" class="result-card" style="display: none;">
<div class="result-label">You said:</div>
<div id="partnerTranscribedText" class="result-text"></div>
</div>
<!-- Partner List -->
<div id="partnerMatchesCard" class="matches-container" style="display: none;">
<div class="matches-label">
<i class="fas fa-users"></i> Select partner:
</div>
<div id="partnerButtons" class="button-list"></div>
</div>
<!-- Selected Partner -->
<div id="selectedPartnerCard" class="selected-card" style="display: none;">
<div class="selected-header">
<i class="fas fa-check-circle"></i> Selected
</div>
<div class="selected-content">
<h3 id="selectedPartnerName"></h3>
<button id="changePartnerBtn" class="btn-text" onclick="resetPartnerSelection()">
<i class="fas fa-undo"></i> Change
</button>
</div>
<button id="proceedToProductsBtn" class="btn-primary-mobile">
Continue to Products <i class="fas fa-arrow-right"></i>
</button>
</div>
</div>
<!-- Step 2: Product Selection -->
<div id="step2" class="step-container" style="display: none;">
<!-- Partner Summary Bar -->
<div class="partner-summary">
<i class="fas fa-user-circle"></i>
<span id="partnerSummary"></span>
</div>
<!-- Step Title -->
<div class="step-title">
<span class="step-number">2</span>
<h2>Add Products</h2>
</div>
<!-- Voice Button -->
<div class="voice-button-container">
<button id="recordProductBtn" class="voice-btn">
<div class="pulse-ring"></div>
<i class="fas fa-microphone"></i>
</button>
<button id="stopProductBtn" class="voice-btn recording" style="display: none;">
<i class="fas fa-stop"></i>
</button>
<p class="voice-hint">Say: "Narancs 100, Alma 50"</p>
</div>
<!-- Recording Status -->
<div id="productRecordingStatus" class="status-indicator" style="display: none;">
<div class="spinner"></div>
<span id="productStatusText">Listening...</span>
</div>
<!-- OR Divider -->
<div class="divider-or">or</div>
<!-- Text Input -->
<div class="input-container">
<input type="text"
id="manualProductInput"
class="mobile-input"
placeholder="Type products: narancs 100, alma 50"
onkeypress="if(event.key === 'Enter') submitManualProducts()">
<button class="search-btn" onclick="submitManualProducts()">
<i class="fas fa-search"></i>
</button>
</div>
<!-- Transcription Result -->
<div id="productTranscribedCard" class="result-card" style="display: none;">
<div class="result-label">You said:</div>
<div id="productTranscribedText" class="result-text"></div>
</div>
<!-- Product Matches -->
<div id="productMatchesCard" class="matches-container" style="display: none;">
<div class="matches-label">
<i class="fas fa-boxes"></i> Tap to add:
</div>
<div id="productButtons" class="button-list"></div>
</div>
<!-- Order Items -->
<div id="orderItemsCard" class="order-summary" style="display: none;">
<div class="order-header">
<h3><i class="fas fa-shopping-cart"></i> Order Items</h3>
</div>
<div class="order-items" id="orderItemsList"></div>
<div class="order-total">
<span>Total:</span>
<strong id="orderTotalDisplay">0.00 Ft</strong>
</div>
<button id="addMoreBtn" class="btn-secondary-mobile" onclick="addMoreProducts()">
<i class="fas fa-plus"></i> Add More Products
</button>
<button id="finishOrderBtn" class="btn-primary-mobile" onclick="finishOrder()">
<i class="fas fa-check"></i> Create Order
</button>
</div>
</div>
<!-- Success Screen -->
<div id="successCard" class="step-container success-screen" style="display: none;">
<div class="success-icon">
<i class="fas fa-check-circle"></i>
</div>
<h2>Order Created!</h2>
<p class="success-order-id">Order #<span id="createdOrderId"></span></p>
<button id="viewOrderBtn" class="btn-primary-mobile">
<i class="fas fa-eye"></i> View Order
</button>
<button class="btn-text" onclick="resetWizard()">
<i class="fas fa-plus"></i> Create Another Order
</button>
</div>
</div>
</div>
<script>
// State management
let currentStep = 1;
let selectedPartnerId = null;
let selectedPartnerName = "";
let orderItems = [];
let orderTotal = 0;
let mediaRecorder = null;
let audioChunks = [];
// VAD (Voice Activity Detection) state
let audioContext = null;
let analyser = null;
let volumeCheckInterval = null;
let recordingStartTime = null;
let isRecording = false;
let baselineNoiseLevel = -60; // Will be calibrated at start
let volumeHistory = []; // Track volume over time
// VAD Configuration
const VAD_CONFIG = {
silenceThreshold: -50, // dB threshold for silence (will be adjusted dynamically)
silenceDuration: 1500, // 1.5 seconds of silence triggers auto-stop
minRecordingTime: 800, // Minimum 0.8 seconds before allowing auto-stop
volumeCheckInterval: 100, // Check volume every 100ms
calibrationTime: 500, // First 500ms used to calibrate noise floor
noiseGateOffset: 15, // dB above noise floor to trigger speech detection
volumeHistorySize: 10 // Keep last 10 volume samples
};
$(document).ready(function() {
// Single click to start - auto-stops on silence
$('#recordPartnerBtn').click(() => startRecording('partner'));
$('#recordProductBtn').click(() => startRecording('product'));
// Optional manual stop
$('#stopPartnerBtn').click(() => stopRecording('partner', false));
$('#stopProductBtn').click(() => stopRecording('product', false));
$('#proceedToProductsBtn').click(proceedToStep2);
checkMicrophoneAvailability();
});
async function checkMicrophoneAvailability() {
console.log('[VoiceOrder] Checking microphone availability...');
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
showWarningBanner('Your browser does not support audio recording. Please use Chrome, Firefox, or Safari.');
return;
}
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const audioInputs = devices.filter(device => device.kind === 'audioinput');
if (audioInputs.length === 0) {
showWarningBanner('No microphone detected. Please connect a microphone to use voice recording.');
}
} catch (error) {
console.error('[VoiceOrder] Error enumerating devices:', error);
}
}
function showWarningBanner(message) {
const banner = $(`
<div class="permission-warning">
<i class="fas fa-exclamation-triangle"></i>
<span>${message}</span>
</div>
`);
$('.mobile-content').prepend(banner);
}
function getSupportedMimeType() {
const mimeTypes = [
'audio/webm',
'audio/webm;codecs=opus',
'audio/ogg;codecs=opus',
'audio/mp4'
];
for (const mimeType of mimeTypes) {
if (MediaRecorder.isTypeSupported(mimeType)) {
return mimeType;
}
}
return 'audio/webm';
}
async function startRecording(type) {
console.log('[VoiceOrder] Starting recording with VAD for:', type);
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
alert('Your browser does not support audio recording.');
return;
}
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
console.log('[VoiceOrder] Got media stream');
// Setup Web Audio API for volume detection
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
const source = audioContext.createMediaStreamSource(stream);
source.connect(analyser);
analyser.fftSize = 512;
const supportedMimeType = getSupportedMimeType();
mediaRecorder = new MediaRecorder(stream, {
mimeType: supportedMimeType
});
audioChunks = [];
recordingStartTime = Date.now();
isRecording = true;
mediaRecorder.addEventListener('dataavailable', event => {
audioChunks.push(event.data);
});
mediaRecorder.addEventListener('stop', () => {
const audioBlob = new Blob(audioChunks, { type: supportedMimeType });
if (audioBlob.size === 0) {
alert('No audio captured. Please try again.');
resetRecordingUI(type);
return;
}
processAudio(audioBlob, type);
stream.getTracks().forEach(track => track.stop());
if (audioContext) {
audioContext.close();
audioContext = null;
}
analyser = null;
isRecording = false;
});
mediaRecorder.start();
console.log('[VoiceOrder] Recording started');
// Update UI
if (type === 'partner') {
$('#recordPartnerBtn').hide();
$('#stopPartnerBtn').show();
showStatus('partnerRecordingStatus', 'Listening... (speak now)');
} else {
$('#recordProductBtn').hide();
$('#stopProductBtn').show();
showStatus('productRecordingStatus', 'Listening... (speak now)');
}
// Start voice activity detection
startVoiceActivityDetection(type);
} catch (error) {
console.error('[VoiceOrder] Recording error:', error);
let errorMessage = 'Could not start recording: ';
if (error.name === 'NotAllowedError') {
errorMessage += 'Microphone permission denied. Please allow microphone access.';
} else if (error.name === 'NotFoundError') {
errorMessage += 'No microphone found.';
} else {
errorMessage += error.message;
}
alert(errorMessage);
resetRecordingUI(type);
}
}
function startVoiceActivityDetection(type) {
console.log('[VoiceOrder] Starting voice activity detection with noise calibration');
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
if (volumeCheckInterval) clearInterval(volumeCheckInterval);
let consecutiveSilentChecks = 0;
const silentChecksNeeded = Math.ceil(VAD_CONFIG.silenceDuration / VAD_CONFIG.volumeCheckInterval);
let isCalibrated = false;
let calibrationSamples = [];
volumeHistory = [];
volumeCheckInterval = setInterval(() => {
if (!isRecording || !analyser) {
clearInterval(volumeCheckInterval);
return;
}
analyser.getByteFrequencyData(dataArray);
let sum = 0;
for (let i = 0; i < bufferLength; i++) {
sum += dataArray[i];
}
const average = sum / bufferLength;
const volume = 20 * Math.log10(average / 255);
const recordingDuration = Date.now() - recordingStartTime;
// CALIBRATION PHASE: First 500ms - measure background noise
if (!isCalibrated && recordingDuration < VAD_CONFIG.calibrationTime) {
calibrationSamples.push(volume);
updateVolumeIndicator(volume, type, false, 'Calibrating noise floor...');
console.log('[VAD] Calibration sample:', volume.toFixed(2), 'dB');
return;
}
// Finish calibration
if (!isCalibrated && calibrationSamples.length > 0) {
// Calculate baseline as average of calibration samples
const sum = calibrationSamples.reduce((a, b) => a + b, 0);
baselineNoiseLevel = sum / calibrationSamples.length;
// Set dynamic threshold: noise floor + offset
const dynamicThreshold = baselineNoiseLevel + VAD_CONFIG.noiseGateOffset;
console.log('[VAD] Calibration complete:');
console.log('[VAD] - Baseline noise:', baselineNoiseLevel.toFixed(2), 'dB');
console.log('[VAD] - Dynamic threshold:', dynamicThreshold.toFixed(2), 'dB');
isCalibrated = true;
}
// Track volume history
volumeHistory.push(volume);
if (volumeHistory.length > VAD_CONFIG.volumeHistorySize) {
volumeHistory.shift();
}
// Calculate rolling average to smooth out spikes
const avgVolume = volumeHistory.reduce((a, b) => a + b, 0) / volumeHistory.length;
// Dynamic threshold based on calibrated noise floor
const dynamicThreshold = baselineNoiseLevel + VAD_CONFIG.noiseGateOffset;
console.log('[VAD] Volume:', volume.toFixed(2), 'dB | Avg:', avgVolume.toFixed(2), 'dB | Threshold:', dynamicThreshold.toFixed(2), 'dB | Baseline:', baselineNoiseLevel.toFixed(2), 'dB');
updateVolumeIndicator(volume, type, true, null);
// Don't check for silence yet if still in minimum recording time
if (recordingDuration < VAD_CONFIG.minRecordingTime) {
return;
}
// Check if silent (using dynamic threshold and rolling average)
if (avgVolume < dynamicThreshold) {
consecutiveSilentChecks++;
console.log('[VAD] Silent check:', consecutiveSilentChecks, '/', silentChecksNeeded);
if (consecutiveSilentChecks >= silentChecksNeeded) {
console.log('[VAD] Silence detected - auto-stopping');
clearInterval(volumeCheckInterval);
stopRecording(type, true);
}
} else {
// Reset silence counter when sound detected above threshold
if (consecutiveSilentChecks > 0) {
console.log('[VAD] Sound detected, resetting silence counter');
}
consecutiveSilentChecks = 0;
}
}, VAD_CONFIG.volumeCheckInterval);
}
function updateVolumeIndicator(volume, type, showIndicator = true, customMessage = null) {
const statusId = type === 'partner' ? 'partnerRecordingStatus' : 'productRecordingStatus';
const statusEl = $('#' + statusId);
// Use dynamic threshold if calibrated, otherwise use baseline
const threshold = baselineNoiseLevel + VAD_CONFIG.noiseGateOffset;
const volumeAboveThreshold = volume - threshold;
// Normalize volume relative to threshold (0-100 scale)
// 0dB above threshold = 0%, 30dB above threshold = 100%
const normalizedVolume = Math.max(0, Math.min(100, ((volumeAboveThreshold + 10) / 40) * 100));
let statusText = customMessage || 'Listening...';
let barClass = 'volume-bar-silent';
if (showIndicator && !customMessage) {
if (normalizedVolume > 60) {
statusText = 'Listening... 🔊 (loud and clear!)';
barClass = 'volume-bar-high';
} else if (normalizedVolume > 30) {
statusText = 'Listening... 🔉 (speaking detected)';
barClass = 'volume-bar-medium';
} else if (normalizedVolume > 10) {
statusText = 'Listening... 🔈 (speak louder)';
barClass = 'volume-bar-low';
} else {
statusText = 'Listening... (waiting for voice...)';
barClass = 'volume-bar-silent';
}
}
statusEl.find('span').text(statusText);
if (statusEl.find('.volume-bar').length === 0) {
statusEl.append('<div class="volume-bar-container"><div class="volume-bar"></div></div>');
}
statusEl.find('.volume-bar')
.removeClass('volume-bar-low volume-bar-medium volume-bar-high volume-bar-silent')
.addClass(barClass)
.css('width', normalizedVolume + '%');
}
function stopRecording(type, autoStopped = false) {
console.log('[VoiceOrder] Stopping recording', autoStopped ? '(auto)' : '(manual)');
if (volumeCheckInterval) {
clearInterval(volumeCheckInterval);
volumeCheckInterval = null;
}
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
const statusId = type === 'partner' ? 'partnerRecordingStatus' : 'productRecordingStatus';
if (autoStopped) {
showStatus(statusId, 'Processing... (silence detected)');
} else {
showStatus(statusId, 'Processing...');
}
mediaRecorder.stop();
}
}
async function processAudio(audioBlob, type) {
const formData = new FormData();
formData.append('audioFile', audioBlob, 'recording.webm');
formData.append('__RequestVerificationToken', $('input[name="__RequestVerificationToken"]').val());
try {
const endpoint = type === 'partner'
? '@Url.Action("TranscribeForPartner", "VoiceOrder")'
: '@Url.Action("TranscribeForProducts", "VoiceOrder")';
const response = await fetch(endpoint, {
method: 'POST',
body: formData
});
const result = await response.json();
resetRecordingUI(type);
if (result.success) {
if (type === 'partner') {
handlePartnerTranscription(result);
} else {
handleProductTranscription(result);
}
} else {
alert('Error: ' + result.message);
}
} catch (error) {
resetRecordingUI(type);
console.error('Error processing audio:', error);
alert('Error processing audio: ' + error.message);
}
}
function handlePartnerTranscription(result) {
$('#partnerTranscribedText').text(result.transcription);
$('#partnerTranscribedCard').show();
displayPartnerMatches(result.partners);
}
function displayPartnerMatches(partners) {
const container = $('#partnerButtons');
container.empty();
if (partners.length === 0) {
container.append('<p class="no-results">No partners found</p>');
$('#partnerMatchesCard').show();
return;
}
partners.forEach(partner => {
const btn = $('<button>')
.addClass('list-item-btn')
.html(`
<div class="item-content">
<i class="fas fa-building"></i>
<span>${partner.label}</span>
</div>
<i class="fas fa-chevron-right"></i>
`)
.click(() => selectPartner(partner));
container.append(btn);
});
$('#partnerMatchesCard').show();
}
function selectPartner(partner) {
selectedPartnerId = partner.value;
selectedPartnerName = partner.label;
$('#selectedPartnerName').text(partner.label);
$('#partnerMatchesCard').hide();
$('#selectedPartnerCard').show();
}
function resetPartnerSelection() {
selectedPartnerId = null;
selectedPartnerName = "";
$('#partnerTranscribedCard').hide();
$('#partnerMatchesCard').hide();
$('#selectedPartnerCard').hide();
$('#recordPartnerBtn').show();
$('#manualPartnerInput').val('');
}
async function submitManualPartner() {
const text = $('#manualPartnerInput').val().trim();
if (!text) {
alert('Please enter a partner name');
return;
}
showStatus('partnerRecordingStatus', 'Searching...');
try {
const response = await fetch('@Url.Action("SearchPartnerByText", "VoiceOrder")', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
},
body: new URLSearchParams({
text: text,
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
})
});
const result = await response.json();
$('#partnerRecordingStatus').hide();
if (result.success) {
handlePartnerTranscription(result);
} else {
alert('Error: ' + result.message);
}
} catch (error) {
$('#partnerRecordingStatus').hide();
console.error('Error:', error);
alert('Error: ' + error.message);
}
}
function proceedToStep2() {
currentStep = 2;
$('#dot1').removeClass('active').addClass('completed');
$('#dot2').addClass('active');
$('#step1').removeClass('active').hide();
$('#step2').addClass('active').show();
$('#partnerSummary').text(selectedPartnerName);
$('.mobile-content').scrollTop(0);
}
function handleProductTranscription(result) {
$('#productTranscribedText').text(result.transcription);
$('#productTranscribedCard').show();
displayProductMatches(result.products);
}
function displayProductMatches(products) {
const container = $('#productButtons');
container.empty();
if (products.length === 0) {
container.append('<p class="no-results">No products found</p>');
$('#productMatchesCard').show();
return;
}
const grouped = {};
products.forEach(p => {
const term = p.searchTerm || 'other';
if (!grouped[term]) grouped[term] = [];
grouped[term].push(p);
});
Object.keys(grouped).forEach(term => {
if (Object.keys(grouped).length > 1) {
container.append(`<div class="group-label">${term}</div>`);
}
grouped[term].forEach(product => {
const hasStockWarning = product.isQuantityReduced;
const warningBadge = hasStockWarning
? `<span class="stock-warning-badge">⚠️ Only ${product.quantity} available (you said ${product.requestedQuantity})</span>`
: '';
const productCard = $('<div>')
.addClass('product-card-wrapper')
.addClass(hasStockWarning ? 'has-warning' : '');
const productButton = $('<button>')
.addClass('product-item-btn')
.addClass(hasStockWarning ? 'stock-warning' : '')
.attr('type', 'button')
.html(`
<div class="product-info">
<div class="product-name">
<i class="fas fa-box"></i>
<strong>${product.name}</strong>
</div>
${warningBadge}
<div class="product-details">
<span class="qty-badge ${hasStockWarning ? 'qty-reduced' : ''}">${product.quantity}</span>
<span class="stock ${product.stockQuantity < 50 ? 'stock-low' : ''}">Stock: ${product.stockQuantity}</span>
</div>
</div>
<i class="fas fa-plus-circle"></i>
`);
const priceEditor = $('<div>')
.addClass('price-editor')
.html(`
<label class="price-label">
<i class="fas fa-tag"></i> Price:
</label>
<input type="number"
class="price-input"
value="${product.price.toFixed(0)}"
min="0"
step="1"
onclick="event.stopPropagation()">
<span class="price-unit">Ft</span>
`);
productButton.click(() => {
const customPrice = parseFloat(priceEditor.find('.price-input').val()) || product.price;
addProductToOrder({...product, price: customPrice});
});
productCard.append(productButton);
productCard.append(priceEditor);
container.append(productCard);
});
});
$('#productMatchesCard').show();
}
function addProductToOrder(product) {
orderItems.push({
id: product.id,
name: product.name,
quantity: product.quantity,
price: product.price
});
updateOrderItemsDisplay();
$('#productMatchesCard').hide();
$('#productTranscribedCard').hide();
$('#recordProductBtn').show();
$('#manualProductInput').val('');
}
function updateOrderItemsDisplay() {
const container = $('#orderItemsList');
container.empty();
orderTotal = 0;
orderItems.forEach((item, index) => {
const itemTotal = item.quantity * item.price;
orderTotal += itemTotal;
const itemEl = $(`
<div class="order-item">
<div class="order-item-header">
<span class="item-name">${item.name}</span>
<button class="btn-icon-delete" onclick="removeItem(${index})">
<i class="fas fa-trash"></i>
</button>
</div>
<div class="order-item-details">
<input type="number"
class="qty-input"
value="${item.quantity}"
min="1"
onchange="updateQuantity(${index}, this.value)">
<span class="item-price">${item.price.toFixed(0)} Ft/unit</span>
<strong class="item-total">${itemTotal.toFixed(0)} Ft</strong>
</div>
</div>
`);
container.append(itemEl);
});
$('#orderTotalDisplay').text(orderTotal.toFixed(0) + ' Ft');
$('#orderItemsCard').show();
}
window.updateQuantity = function(index, newQuantity) {
orderItems[index].quantity = parseInt(newQuantity);
updateOrderItemsDisplay();
};
window.removeItem = function(index) {
orderItems.splice(index, 1);
updateOrderItemsDisplay();
if (orderItems.length === 0) {
$('#orderItemsCard').hide();
}
};
function addMoreProducts() {
$('#productTranscribedCard').hide();
$('#productMatchesCard').hide();
$('#recordProductBtn').show();
$('#manualProductInput').val('');
}
async function submitManualProducts() {
const text = $('#manualProductInput').val().trim();
if (!text) {
alert('Please enter some products');
return;
}
showStatus('productRecordingStatus', 'Processing...');
try {
const response = await fetch('@Url.Action("ParseManualProductText", "VoiceOrder")', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
},
body: new URLSearchParams({
text: text,
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
})
});
const result = await response.json();
$('#productRecordingStatus').hide();
if (result.success) {
handleProductTranscription(result);
} else {
alert('Error: ' + result.message);
}
} catch (error) {
$('#productRecordingStatus').hide();
console.error('Error:', error);
alert('Error: ' + error.message);
}
}
async function finishOrder() {
if (!selectedPartnerId || orderItems.length === 0) {
alert('Please select a partner and add products');
return;
}
$('#finishOrderBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Creating...');
try {
const response = await fetch('@Url.Action("Create", "CustomOrder")', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
},
body: new URLSearchParams({
customerId: selectedPartnerId,
orderProductsJson: JSON.stringify(orderItems),
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
})
});
if (response.redirected) {
const url = new URL(response.url);
const orderId = url.searchParams.get('id');
if (orderId) {
showSuccess(orderId);
} else {
window.location.href = response.url;
}
} else {
alert('Error creating order');
$('#finishOrderBtn').prop('disabled', false).html('<i class="fas fa-check"></i> Create Order');
}
} catch (error) {
console.error('Error:', error);
alert('Error: ' + error.message);
$('#finishOrderBtn').prop('disabled', false).html('<i class="fas fa-check"></i> Create Order');
}
}
function showSuccess(orderId) {
$('#step2').hide();
$('#successCard').show();
$('#createdOrderId').text(orderId);
$('#viewOrderBtn').attr('href', '@Url.Action("Edit", "Order")?id=' + orderId);
$('.mobile-content').scrollTop(0);
}
function resetWizard() {
currentStep = 1;
selectedPartnerId = null;
selectedPartnerName = "";
orderItems = [];
orderTotal = 0;
$('#dot1').removeClass('completed').addClass('active');
$('#dot2').removeClass('active completed');
$('#successCard').hide();
$('#step2').hide();
$('#step1').show().addClass('active');
$('#partnerTranscribedCard, #partnerMatchesCard, #selectedPartnerCard, #productTranscribedCard, #productMatchesCard, #orderItemsCard').hide();
$('#recordPartnerBtn').show();
$('#manualPartnerInput, #manualProductInput').val('');
$('.mobile-content').scrollTop(0);
}
function showStatus(elementId, message) {
$(`#${elementId}`).find('span').text(message);
$(`#${elementId}`).show();
}
function resetRecordingUI(type) {
if (type === 'partner') {
$('#partnerRecordingStatus').hide();
$('#recordPartnerBtn').show();
$('#stopPartnerBtn').hide();
} else {
$('#productRecordingStatus').hide();
$('#recordProductBtn').show();
$('#stopProductBtn').hide();
}
}
</script>
<style>
.voice-order-mobile {
background: #f5f7fa;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
.mobile-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1rem;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
z-index: 100;
}
.header-content h1 {
margin: 0 0 0.5rem 0;
font-size: 1.5rem;
font-weight: 600;
}
.progress-dots {
display: flex;
gap: 0.5rem;
justify-content: center;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: rgba(255,255,255,0.3);
transition: all 0.3s;
}
.dot.active {
width: 24px;
border-radius: 4px;
background: white;
}
.dot.completed {
background: #4ade80;
}
.mobile-content {
overflow-y: auto;
-webkit-overflow-scrolling: touch;
padding: 1rem;
}
.step-container {
display: none;
animation: slideIn 0.3s ease-out;
}
.step-container.active {
display: block;
}
@@keyframes slideIn {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.step-title {
text-align: center;
margin-bottom: 2rem;
}
.step-number {
display: inline-block;
width: 32px;
height: 32px;
line-height: 32px;
background: #667eea;
color: white;
border-radius: 50%;
font-weight: 600;
margin-bottom: 0.5rem;
}
.step-title h2 {
font-size: 1.5rem;
font-weight: 600;
color: #1f2937;
margin: 0.5rem 0 0 0;
}
.voice-button-container {
text-align: center;
margin: 2rem 0;
}
.voice-btn {
position: relative;
width: 120px;
height: 120px;
border-radius: 50%;
border: none;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
font-size: 2.5rem;
box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
cursor: pointer;
transition: all 0.3s;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
}
.voice-btn:active {
transform: scale(0.95);
}
.voice-btn.recording {
background: #ef4444;
animation: pulse 1.5s infinite;
}
@@keyframes pulse {
0%, 100% {
box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
}
50% {
box-shadow: 0 0 0 20px rgba(239, 68, 68, 0);
}
}
.pulse-ring {
position: absolute;
width: 140px;
height: 140px;
border-radius: 50%;
border: 3px solid #667eea;
opacity: 0;
animation: pulseRing 2s infinite;
}
@@keyframes pulseRing {
0% {
transform: scale(0.9);
opacity: 0.5;
}
100% {
transform: scale(1.3);
opacity: 0;
}
}
.voice-hint {
margin-top: 1rem;
color: #6b7280;
font-size: 0.9rem;
}
.status-indicator {
text-align: center;
padding: 1rem;
background: white;
border-radius: 12px;
margin: 1rem 0;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.status-indicator span {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
}
.spinner {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid #e5e7eb;
border-top-color: #667eea;
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin-right: 0.5rem;
vertical-align: middle;
}
@@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Volume Bar for VAD */
.volume-bar-container {
width: 100%;
height: 8px;
background: #e5e7eb;
border-radius: 4px;
margin-top: 0.75rem;
overflow: hidden;
}
.volume-bar {
height: 100%;
transition: width 0.1s ease-out, background-color 0.3s;
border-radius: 4px;
}
.volume-bar-silent {
background: #9ca3af;
width: 0%;
}
.volume-bar-low {
background: linear-gradient(90deg, #fbbf24 0%, #f59e0b 100%);
}
.volume-bar-medium {
background: linear-gradient(90deg, #10b981 0%, #059669 100%);
}
.volume-bar-high {
background: linear-gradient(90deg, #3b82f6 0%, #2563eb 100%);
animation: pulse-volume 0.5s infinite;
}
@@keyframes pulse-volume {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
.divider-or {
text-align: center;
color: #9ca3af;
font-size: 0.875rem;
margin: 1.5rem 0;
position: relative;
}
.divider-or:before, .divider-or:after {
content: '';
position: absolute;
top: 50%;
width: 40%;
height: 1px;
background: #e5e7eb;
}
.divider-or:before {
left: 0;
}
.divider-or:after {
right: 0;
}
.input-container {
display: flex;
gap: 0.5rem;
margin: 1rem 0 2rem 0;
}
.mobile-input {
flex: 1;
padding: 1rem;
border: 2px solid #e5e7eb;
border-radius: 12px;
font-size: 1rem;
transition: border-color 0.2s;
}
.mobile-input:focus {
outline: none;
border-color: #667eea;
}
.search-btn {
width: 50px;
height: 50px;
border: none;
border-radius: 12px;
background: #667eea;
color: white;
font-size: 1.2rem;
cursor: pointer;
transition: all 0.2s;
}
.search-btn:active {
transform: scale(0.95);
}
.result-card {
background: white;
border-radius: 12px;
padding: 1rem;
margin: 1rem 0;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.result-label {
font-size: 0.75rem;
color: #6b7280;
text-transform: uppercase;
font-weight: 600;
margin-bottom: 0.5rem;
}
.result-text {
font-size: 1.125rem;
color: #1f2937;
}
.matches-container {
margin: 1.5rem 0;
}
.matches-label {
font-size: 0.875rem;
color: #6b7280;
font-weight: 600;
margin-bottom: 1rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.button-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.product-card-wrapper {
background: white;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.product-card-wrapper.has-warning {
box-shadow: 0 2px 8px rgba(245, 158, 11, 0.2);
}
.list-item-btn {
width: 100%;
padding: 1rem;
border: 2px solid #e5e7eb;
border-radius: 12px;
background: white;
text-align: left;
cursor: pointer;
transition: all 0.2s;
display: flex;
justify-content: space-between;
align-items: center;
}
.list-item-btn:active {
transform: scale(0.98);
border-color: #667eea;
}
.item-content {
display: flex;
align-items: center;
gap: 0.75rem;
flex: 1;
}
.item-content i {
color: #667eea;
font-size: 1.25rem;
}
.item-content span {
font-size: 0.95rem;
color: #1f2937;
}
.product-item-btn {
width: 100%;
padding: 1rem;
border: 2px solid #e5e7eb;
border-radius: 12px 12px 0 0;
background: white;
cursor: pointer;
transition: all 0.2s;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: none;
}
.product-item-btn.stock-warning {
border-color: #f59e0b;
background: #fffbeb;
}
.product-item-btn:active {
transform: scale(0.98);
}
.price-editor {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1rem;
background: #f9fafb;
border: 2px solid #e5e7eb;
border-top: 1px solid #e5e7eb;
border-radius: 0 0 12px 12px;
}
.product-card-wrapper.has-warning .price-editor {
background: #fffbeb;
border-color: #f59e0b;
}
.price-label {
font-size: 0.875rem;
color: #6b7280;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.25rem;
margin: 0;
}
.price-label i {
color: #667eea;
}
.price-input {
flex: 1;
padding: 0.5rem 0.75rem;
border: 2px solid #e5e7eb;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
color: #1f2937;
background: white;
text-align: right;
max-width: 120px;
transition: border-color 0.2s;
}
.price-input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.price-unit {
font-size: 0.875rem;
color: #6b7280;
font-weight: 600;
}
.stock-warning-badge {
display: block;
background: #fef3c7;
color: #92400e;
padding: 0.25rem 0.5rem;
border-radius: 6px;
font-size: 0.75rem;
font-weight: 600;
margin: 0.5rem 0;
border: 1px solid #f59e0b;
}
.product-info {
flex: 1;
text-align: left;
}
.product-name {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.5rem;
}
.product-name i {
color: #667eea;
}
.product-name strong {
font-size: 1rem;
color: #1f2937;
}
.product-details {
display: flex;
gap: 0.75rem;
font-size: 0.875rem;
color: #6b7280;
}
.qty-badge {
background: #667eea;
color: white;
padding: 0.125rem 0.5rem;
border-radius: 6px;
font-weight: 600;
}
.qty-badge.qty-reduced {
background: #f59e0b;
animation: pulse-warning 2s infinite;
}
@@keyframes pulse-warning {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
.stock {
color: #10b981;
}
.stock.stock-low {
color: #f59e0b;
font-weight: 600;
}
.group-label {
font-size: 0.75rem;
color: #667eea;
font-weight: 600;
text-transform: uppercase;
margin: 1rem 0 0.5rem 0;
}
.selected-card {
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
color: white;
border-radius: 16px;
padding: 1.5rem;
margin: 1.5rem 0;
box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}
.selected-header {
font-size: 0.75rem;
text-transform: uppercase;
font-weight: 600;
margin-bottom: 0.5rem;
opacity: 0.9;
}
.selected-content h3 {
font-size: 1.25rem;
margin: 0 0 1rem 0;
}
.btn-text {
background: transparent;
border: none;
color: white;
font-size: 0.875rem;
cursor: pointer;
margin-bottom: 1rem;
text-decoration: underline;
}
.btn-primary-mobile {
width: 100%;
padding: 1rem;
border: none;
border-radius: 12px;
background: #667eea;
color: white;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
margin-top: 1rem;
}
.btn-primary-mobile:active {
transform: scale(0.98);
}
.btn-primary-mobile:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-secondary-mobile {
width: 100%;
padding: 1rem;
border: 2px solid #e5e7eb;
border-radius: 12px;
background: white;
color: #667eea;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
margin-top: 1rem;
}
.btn-secondary-mobile:active {
transform: scale(0.98);
}
.partner-summary {
background: white;
padding: 0.75rem 1rem;
border-radius: 12px;
margin-bottom: 1.5rem;
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.9rem;
color: #1f2937;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.partner-summary i {
color: #667eea;
}
.order-summary {
background: white;
border-radius: 16px;
padding: 1.5rem;
margin: 2rem 0;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.order-header {
margin-bottom: 1rem;
}
.order-header h3 {
font-size: 1.25rem;
margin: 0;
display: flex;
align-items: center;
gap: 0.5rem;
}
.order-items {
display: flex;
flex-direction: column;
gap: 1rem;
margin-bottom: 1rem;
}
.order-item {
background: #f9fafb;
border-radius: 12px;
padding: 1rem;
}
.order-item-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.75rem;
}
.item-name {
font-weight: 600;
color: #1f2937;
}
.btn-icon-delete {
background: transparent;
border: none;
color: #ef4444;
cursor: pointer;
padding: 0.25rem;
}
.order-item-details {
display: flex;
align-items: center;
gap: 0.75rem;
font-size: 0.875rem;
}
.qty-input {
width: 60px;
padding: 0.5rem;
border: 2px solid #e5e7eb;
border-radius: 8px;
text-align: center;
font-weight: 600;
}
.item-price {
color: #6b7280;
}
.item-total {
margin-left: auto;
color: #1f2937;
font-size: 1rem;
}
.order-total {
display: flex;
justify-content: space-between;
padding: 1rem 0;
border-top: 2px solid #e5e7eb;
font-size: 1.25rem;
font-weight: 600;
}
.success-screen {
text-align: center;
padding: 2rem 0;
}
.success-icon {
font-size: 5rem;
color: #10b981;
margin: 2rem 0;
animation: scaleIn 0.5s ease-out;
}
@@keyframes scaleIn {
from {
transform: scale(0);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
.success-screen h2 {
font-size: 2rem;
margin: 1rem 0;
color: #1f2937;
}
.success-order-id {
font-size: 1.125rem;
color: #6b7280;
margin-bottom: 2rem;
}
.no-results {
text-align: center;
color: #6b7280;
padding: 2rem;
}
.permission-warning {
background: #fef3c7;
border: 2px solid #f59e0b;
border-radius: 12px;
padding: 1rem;
margin-bottom: 1rem;
display: flex;
align-items: center;
gap: 0.75rem;
color: #92400e;
font-size: 0.9rem;
}
.permission-warning i {
font-size: 1.5rem;
color: #f59e0b;
flex-shrink: 0;
}
@@media (max-width: 375px) {
.voice-btn {
width: 100px;
height: 100px;
font-size: 2rem;
}
}
@@media screen and (max-width: 768px) {
input, select, textarea {
font-size: 16px;
}
}
</style>
@Html.AntiForgeryToken()