/* Import Menu from Image (pos_setup.php)
* 1. menuImportExtract(): upload photo(s) -> menu_import_extract.php -> rows in #miGrid
* 2. user corrects rows in the grid (click a cell to edit, Remove link per row)
* 3. menuImportSave(): rows -> menu_import_save.php -> res_category / res_item
*/
var miGridReady = false;
var miEditIndex;
var miExistingCategories = [];
function miEsc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
});
}
function miPagePosNo() {
return $('#pos_no').val() || $('#mi_pos_no').val();
}
/* The P.O.S chosen in the dialog; falls back to the page's P.O.S until the list has loaded. */
function miPosNo() {
var v = '';
try { v = $('#mi_pos').combobox('getValue'); } catch (e) { }
return v || miPagePosNo();
}
function miLoadMenus() {
$('#mi_res_menu').combobox({
url: 'getResCategories.php?res_menu&pos_no=' + miPosNo(),
valueField: 'id',
textField: 'menu',
editable: false,
panelHeight: 'auto',
onLoadSuccess: function () {
if (!$('#mi_res_menu').combobox('getValue')) {
$('#mi_res_menu').combobox('setValue', 1);
}
}
});
}
var miSavedItems = [];
/* A question with named buttons (EasyUI's confirm only offers OK / Cancel).
* choices = [{ text: 'Button label', handler: fn }, ...]; a choice without a handler just closes the box. */
function miChoice(title, html, choices) {
var box = $('
').html(html).appendTo('body');
var close = function () { box.dialog('destroy'); };
box.dialog({
title: title,
modal: true,
closable: true,
width: 460,
height: 'auto',
top: 120,
onClose: function () { box.dialog('destroy'); },
buttons: choices.map(function (c) {
return {
text: c.text,
iconCls: c.iconCls || '',
handler: function () {
close();
if (typeof c.handler === 'function') { c.handler(); }
}
};
})
});
}
/* res_category.accomp_status, the same two tick boxes as the New Category dialog */
var miAccompChoices = [
{ v: 0, l: '' },
{ v: 1, l: 'Items are accompaniments' },
{ v: 2, l: 'Sold with accompaniments' }
];
function miAccompLabel(v) {
var n = parseInt(v, 10) || 0;
for (var i = 0; i < miAccompChoices.length; i++) {
if (miAccompChoices[i].v === n) { return miAccompChoices[i].l; }
}
return '';
}
/* Step indicator shared by the import dialog (#miSteps1) and the ingredients dialog (#miSteps2).
* current = step now in progress (1-3); doneUpTo = highest step already completed. */
var miStepLabels = ['Upload the menu / price list', 'Check items & save to P.O.S', 'Suggest ingredients / inputs', 'Check inputs & save to store'];
function miRenderSteps(containerId, current, doneUpTo) {
var html = '';
miStepLabels.forEach(function (label, i) {
var n = i + 1;
var cls = n <= (doneUpTo || 0) ? 'is-done' : (n === current ? 'is-active' : '');
var mark = n <= (doneUpTo || 0) ? '✓' : n;
html += '' + mark + '' + miEsc(label) + '';
});
var remaining = miStepLabels.length - Math.max(current, doneUpTo || 0);
var of = current > miStepLabels.length || (doneUpTo || 0) >= miStepLabels.length
? 'All steps complete'
: 'Step ' + current + ' of ' + miStepLabels.length + (remaining > 0 ? ' (' + remaining + ' remaining)' : '');
html += '' + of + '';
$('#' + containerId).html(html).show();
}
function openDlgMenuImport() {
$('#dlgMenuImport').dialog('open');
miRenderSteps('miSteps1', 1, 0);
miInitGrid();
try { $('#dlgMenuImport').dialog('resize'); } catch (e) { } // auto-height dialog: fit the grid without a scrollbar
$('#miGrid').datagrid('loadData', []);
$('#miStatus').text('');
$('#mi_files').val('');
miSavedItems = [];
$('#miSuggestBtn').hide();
$('#mi_pos').combobox({
url: 'getPos.php',
valueField: 'pos_no',
textField: 'description',
editable: false,
panelHeight: 200,
onLoadSuccess: function () {
$('#mi_pos').combobox('setValue', miPagePosNo());
miLoadMenus();
},
onSelect: function () {
miLoadMenus();
var rows = $('#miGrid').datagrid('getRows');
if (rows.length) {
$('#miStatus').text('P.O.S changed: the items in the list will be saved into ' + $('#mi_pos').combobox('getText') + '.');
}
}
});
$('#mi_res_menu').combobox({
url: 'getResCategories.php?res_menu&pos_no=' + miPosNo(),
valueField: 'id',
textField: 'menu',
editable: false,
panelHeight: 'auto',
onLoadSuccess: function () {
if (!$('#mi_res_menu').combobox('getValue')) {
$('#mi_res_menu').combobox('setValue', 1);
}
}
});
miLoadSettings();
}
/* ---------------------------------------------------------------- grid */
function miInitGrid() {
if (miGridReady) {
return;
}
miGridReady = true;
$('#miGrid').datagrid({
width: 946,
height: 400,
singleSelect: true,
fitColumns: true,
rownumbers: true,
nowrap: false,
columns: [[
{
field: 'category', title: 'Category', width: 150,
editor: { type: 'combobox', options: { valueField: 'name', textField: 'name', editable: true, panelHeight: 'auto', data: [] } },
formatter: function (v, row) {
var isNew = v && miExistingCategories.indexOf(String(v).trim().toLowerCase()) === -1;
return miEsc(v) + (isNew ? ' (new)' : '');
}
},
{
field: 'name', title: 'Item name', width: 200,
editor: { type: 'validatebox', options: { required: true, validType: 'length[1,45]' } },
formatter: function (v) { return miEsc(v); }
},
{
field: 'price', title: 'Price', width: 90, align: 'right',
editor: { type: 'numberbox', options: { precision: 2, min: 0 } },
formatter: function (v) { return (v == null || v === '') ? '' : Number(v).toLocaleString(); }
},
{
field: 'description', title: 'Description', width: 200, editor: 'text',
formatter: function (v) { return miEsc(v); }
},
{
field: 'accomp', title: 'Accompaniment', width: 150,
editor: { type: 'combobox', options: { valueField: 'v', textField: 'l', editable: false, panelHeight: 'auto', data: miAccompChoices } },
formatter: function (v) { return miEsc(miAccompLabel(v)); }
},
{
field: 'status', title: 'Check', width: 140,
formatter: function (v) { return miEsc(v); }
},
{
field: 'remove', title: ' ', width: 60, align: 'center',
formatter: function (v, row, index) {
return 'Remove';
}
}
]],
onClickCell: miOnClickCell,
onAfterEdit: function (index, row) {
$('#miGrid').datagrid('refreshRow', index);
}
});
}
function miOnClickCell(index, field) {
if (field === 'remove') {
return;
}
if (miEditIndex !== index) {
if (miEndEditing()) {
$('#miGrid').datagrid('selectRow', index).datagrid('beginEdit', index);
miEditIndex = index;
var ed = $('#miGrid').datagrid('getEditor', { index: index, field: field });
if (ed) {
$(ed.target).focus();
}
} else {
$('#miGrid').datagrid('selectRow', miEditIndex);
}
}
}
function miEndEditing() {
if (miEditIndex === undefined) {
return true;
}
if ($('#miGrid').datagrid('validateRow', miEditIndex)) {
$('#miGrid').datagrid('endEdit', miEditIndex);
miEditIndex = undefined;
return true;
}
return false;
}
function miRemoveRow(index) {
if (miEditIndex !== undefined) {
$('#miGrid').datagrid('cancelEdit', miEditIndex);
miEditIndex = undefined;
}
$('#miGrid').datagrid('deleteRow', index);
// re-render so the Remove links carry the right indexes
var rows = $('#miGrid').datagrid('getRows').slice();
$('#miGrid').datagrid('loadData', rows);
}
function miSetCategoryChoices(names) {
var opt = $('#miGrid').datagrid('getColumnOption', 'category');
opt.editor.options.data = names.map(function (n) { return { name: n }; });
}
/* ------------------------------------------------------------- extract */
function menuImportExtract() {
var input = document.getElementById('mi_files');
var files = input.files;
if (!files || !files.length) {
$.messager.alert('Info', 'Please choose a photo or PDF of the menu first.', 'info');
return;
}
if (files.length > 6) {
$.messager.alert('Info', 'Please import at most 6 files at a time.', 'info');
return;
}
if (!miEndEditing()) {
return;
}
// A key typed into AI settings but not yet saved: save it first, then read.
if ($('#mi_api_key').val().trim() !== '') {
menuImportSaveSettings(function () { menuImportExtract(); });
return;
}
var fd = new FormData();
for (var i = 0; i < files.length; i++) {
fd.append('menu_images[]', files[i]);
}
fd.append('pos_no', miPosNo());
$.messager.progress({
title: 'Reading menu',
msg: 'Sending the menu to the AI service and reading the items. This usually takes 20 to 90 seconds...'
});
$.ajax({
url: 'menu_import_extract.php?action=extract',
type: 'POST',
data: fd,
processData: false,
contentType: false,
dataType: 'json',
timeout: 320000
}).done(function (r) {
$.messager.progress('close');
if (!r.success) {
$.messager.alert('Could not read menu', miEsc(r.msg), 'error');
if (/API key/i.test(r.msg || '')) {
miShowSettings(true);
}
return;
}
miExistingCategories = (r.existing_categories || []).map(function (n) { return String(n).trim().toLowerCase(); });
var names = (r.existing_categories || []).slice();
(r.rows || []).forEach(function (row) {
if (row.category && names.indexOf(row.category) === -1) {
names.push(row.category);
}
});
miSetCategoryChoices(names);
$('#miGrid').datagrid('loadData', r.rows || []);
if ((r.rows || []).length) {
miRenderSteps('miSteps1', 2, 1);
}
var msg = (r.rows || []).length + ' item(s) found in ' + r.images + ' file(s). Check the names and prices, then save.';
if (!(r.rows || []).length) {
msg = 'No menu / POS items could be read from the file. Try a sharper, better-lit photo or a text PDF.';
}
if (r.notes) {
msg += ' Note from the reader: ' + r.notes;
}
$('#miStatus').text(msg);
}).fail(function (xhr) {
$.messager.progress('close');
var msg = 'The request failed.';
try {
msg = JSON.parse(xhr.responseText).msg || msg;
} catch (e) {
if (xhr.status === 0) {
msg = 'The request timed out or the connection dropped.';
} else if (xhr.status === 413) {
msg = 'The photo is larger than the server upload limit.';
} else if (xhr.status) {
msg = 'Server error ' + xhr.status + '.';
}
}
$.messager.alert('Could not read menu', miEsc(msg), 'error');
});
}
/* ---------------------------------------------------------------- save */
function menuImportSave() {
if (!miEndEditing()) {
$.messager.alert('Info', 'Please fix the highlighted row first.', 'info');
return;
}
var rows = $('#miGrid').datagrid('getRows').filter(function (r) { return !/^saved/.test(r.status || ''); });
if (!rows.length) {
$.messager.alert('Info', 'There are no unsaved items in the list.', 'info');
return;
}
var noName = rows.filter(function (r) { return !String(r.name || '').trim(); }).length;
if (noName) {
$.messager.alert('Info', noName + ' row(s) have no item name. Fill them in or remove them.', 'info');
return;
}
var noPrice = rows.filter(function (r) { return !(Number(r.price) > 0); }).length;
var go = function () {
$.messager.progress({ title: 'Saving', msg: 'Creating categories and items...' });
$.ajax({
url: 'menu_import_save.php',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
pos_no: miPosNo(),
res_menu_id: $('#mi_res_menu').combobox('getValue') || 1,
rows: rows.map(function (r) {
return { category: r.category, name: r.name, price: r.price, description: r.description, accomp: r.accomp || 0 };
})
})
}).done(function (r) {
$.messager.progress('close');
if (!r.success) {
$.messager.alert('Not saved', miEsc(r.msg), 'error');
return;
}
$('#miGrid').datagrid('loadData', r.rows || []);
$('#miStatus').text(r.msg);
$.messager.show({ title: 'Menu import', msg: miEsc(r.msg), timeout: 8000 });
(r.rows || []).forEach(function (row) {
if (row.res_item) {
miSavedItems.push({ res_item: row.res_item, name: row.name, description: row.description || '' });
}
});
$('#miSuggestBtn').toggle(miSavedItems.length > 0);
if (miSavedItems.length) {
miRenderSteps('miSteps1', 3, 2);
$('#miStatus').text(r.msg + ' Next: click "Suggest ingredients for saved items" for step 3.');
}
// refresh the setup page's lists
$('#dg').datagrid('reload');
['#categorydg'].forEach(function (id) { try { $(id).datagrid('reload'); } catch (e) { } });
['#category', '#item_category'].forEach(function (id) { try { $(id).combobox('reload'); } catch (e) { } });
if (r.efris_on && r.created_items > 0 && typeof AutoPostErisItems === 'function') {
AutoPostErisItems();
}
}).fail(function (xhr) {
$.messager.progress('close');
var msg = 'The request failed.';
try { msg = JSON.parse(xhr.responseText).msg || msg; } catch (e) { }
$.messager.alert('Not saved', miEsc(msg), 'error');
});
};
if (noPrice) {
$.messager.confirm('Confirm', noPrice + ' item(s) have no price and will be saved at 0. Save anyway?', function (ok) {
if (ok) { go(); }
});
} else {
go();
}
}
/* ------------------------------------------------------------ settings */
function miShowSettings(show) {
$('#miSettings').toggle(!!show);
try { $('#dlgMenuImport').dialog('resize'); } catch (e) { }
}
function menuImportToggleSettings() {
$('#miSettings').toggle();
try { $('#dlgMenuImport').dialog('resize'); } catch (e) { }
}
function miLoadSettings() {
$.getJSON('menu_import_extract.php?action=settings').done(function (r) {
$('#mi_model').val(r.model || '');
$('#mi_ca_file').val(r.ca_file || '');
$('#mi_api_key').val('').attr('placeholder', r.has_key ? 'Saved (' + r.key_hint + ') - leave blank to keep' : 'sk-ant-...');
if (!r.has_key) {
miShowSettings(true);
$('#miSettingsStatus').text('Paste your Anthropic API key to enable menu reading.');
} else {
miShowSettings(false);
$('#miSettingsStatus').text('');
}
});
}
function menuImportSaveSettings(onSaved) {
$.post('menu_import_extract.php?action=save_settings', {
api_key: $('#mi_api_key').val().trim(),
model: $('#mi_model').val(),
ca_file: $('#mi_ca_file').val()
}, function (r) {
$('#miSettingsStatus').text(r.success ? (r.has_key ? 'Saved.' : 'Saved, but no API key is set yet.') : (r.msg || 'Could not save'));
if (r.success && r.has_key) {
$('#mi_api_key').val('');
miLoadSettings();
if (typeof onSaved === 'function') {
onSaved();
}
} else if (!r.success) {
$.messager.alert('Settings', miEsc(r.msg || 'Could not save settings.'), 'error');
}
}, 'json').fail(function () {
$('#miSettingsStatus').text('Could not save settings.');
$.messager.alert('Settings', 'Could not save settings. Please log in again and retry.', 'error');
});
}