feat: Migrate RecipePage to use real OPModel data

- Updated RecipePage to load actual recipe data from OPModel table
- Added GetRecipe() and SaveRecipe() methods to communication layer
- Implemented real-time recipe editing with change tracking
- Added type definitions for GetRecipe and SaveRecipe in types.ts
- Recipe editor now displays all major fields:
  - Basic Settings (Motion Model, Auto Out Conveyor, Vendor Name, MFG)
  - Barcode Settings (1D, QR, Data Matrix)
  - Feature Flags (IgnoreOtherBarcode, DisableCamera, etc.)
- Copy and Delete operations now use recipe Title instead of id
- Added unsaved changes warning when switching recipes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-25 21:15:39 +09:00
parent 8364f7478c
commit d6678422a7
3 changed files with 286 additions and 83 deletions

View File

@@ -284,6 +284,65 @@ class CommunicationLayer {
}); });
} }
} }
public async getRecipe(recipeTitle: string): Promise<string> {
if (isWebView && machine) {
return await machine.GetRecipe(recipeTitle);
} else {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
setTimeout(() => {
if (!this.isConnected) reject("WebSocket connection timeout");
}, 2000);
}
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject("Recipe fetch timeout");
}, 10000);
const handler = (data: any) => {
if (data.type === 'RECIPE_DATA') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(JSON.stringify(data.data));
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'GET_RECIPE', recipeTitle }));
});
}
}
public async saveRecipe(recipeTitle: string, recipeData: string): Promise<{ success: boolean; message: string; recipeId?: string }> {
if (isWebView && machine) {
const resultJson = await machine.SaveRecipe(recipeTitle, recipeData);
return JSON.parse(resultJson);
} else {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
setTimeout(() => {
if (!this.isConnected) reject({ success: false, message: "WebSocket connection timeout" });
}, 2000);
}
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject({ success: false, message: "Recipe save timeout" });
}, 10000);
const handler = (data: any) => {
if (data.type === 'RECIPE_SAVED') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(data.data);
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'SAVE_RECIPE', recipeTitle, recipeData }));
});
}
}
} }
export const comms = new CommunicationLayer(); export const comms = new CommunicationLayer();

View File

@@ -1,62 +1,118 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Layers, Plus, Trash2, Copy, Save, ArrowLeft, FileText, Calendar } from 'lucide-react'; import { Layers, Plus, Trash2, Copy, Save, ArrowLeft, FileText, Calendar, Check } from 'lucide-react';
import { Recipe } from '../types'; import { Recipe } from '../types';
import { comms } from '../communication'; import { comms } from '../communication';
import { TechButton } from '../components/common/TechButton'; import { TechButton } from '../components/common/TechButton';
interface RecipeData {
idx?: number;
Title?: string;
Motion?: string;
BCD_1D?: boolean;
BCD_QR?: boolean;
BCD_DM?: boolean;
vOption?: number;
vWMSInfo?: number;
vSIDInfo?: number;
vJobInfo?: number;
vSIDConv?: number;
Def_VName?: string;
Def_MFG?: string;
IgnoreOtherBarcode?: boolean;
DisableCamera?: boolean;
DisablePrinter?: boolean;
CheckSIDExsit?: boolean;
bOwnZPL?: boolean;
IgnorePartNo?: boolean;
IgnoreBatch?: boolean;
BSave?: number;
AutoOutConveyor?: number;
[key: string]: any;
}
export const RecipePage: React.FC = () => { export const RecipePage: React.FC = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const [recipes, setRecipes] = useState<Recipe[]>([]); const [recipes, setRecipes] = useState<Recipe[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null); const [selectedTitle, setSelectedTitle] = useState<string | null>(null);
const [editedRecipe, setEditedRecipe] = useState<Recipe | null>(null); const [editedRecipe, setEditedRecipe] = useState<RecipeData | null>(null);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [hasChanges, setHasChanges] = useState(false);
useEffect(() => { useEffect(() => {
loadRecipes();
}, []);
const loadRecipes = async () => { const loadRecipes = async () => {
try { try {
const recipeStr = await comms.getRecipeList(); const recipeStr = await comms.getRecipeList();
const recipeData = JSON.parse(recipeStr); const recipeData = JSON.parse(recipeStr);
setRecipes(recipeData); setRecipes(recipeData);
if (recipeData.length > 0) { if (recipeData.length > 0 && !selectedTitle) {
setSelectedId(recipeData[0].id); await handleSelect(recipeData[0]);
setEditedRecipe(recipeData[0]);
} }
} catch (e) { } catch (e) {
console.error("Failed to load recipes", e); console.error("Failed to load recipes", e);
} }
setIsLoading(false); setIsLoading(false);
}; };
loadRecipes();
}, []);
const handleSelect = (r: Recipe) => { const handleSelect = async (r: Recipe) => {
setSelectedId(r.id); if (hasChanges) {
setEditedRecipe({ ...r }); const confirmed = window.confirm("You have unsaved changes. Do you want to discard them?");
if (!confirmed) return;
}
setSelectedTitle(r.name);
try {
const recipeStr = await comms.getRecipe(r.name);
const recipeData = JSON.parse(recipeStr);
setEditedRecipe(recipeData);
setHasChanges(false);
} catch (e) {
console.error("Failed to load recipe details", e);
alert("Failed to load recipe details");
}
};
const handleFieldChange = (field: string, value: any) => {
if (!editedRecipe) return;
setEditedRecipe({ ...editedRecipe, [field]: value });
setHasChanges(true);
}; };
const handleSave = async () => { const handleSave = async () => {
// Mock Save Logic if (!editedRecipe || !selectedTitle) return;
console.log("Saving recipe:", editedRecipe);
// In real app: await comms.saveRecipe(editedRecipe); try {
const result = await comms.saveRecipe(selectedTitle, JSON.stringify(editedRecipe));
if (result.success) {
setHasChanges(false);
alert("Recipe saved successfully!");
await loadRecipes();
} else {
alert(`Failed to save recipe: ${result.message}`);
}
} catch (error: any) {
alert(`Error saving recipe: ${error.message || 'Unknown error'}`);
console.error('Recipe save error:', error);
}
}; };
const handleCopy = async () => { const handleCopy = async () => {
if (!selectedId) return; if (!selectedTitle) return;
const selectedRecipe = recipes.find(r => r.id === selectedId); const selectedRecipe = recipes.find(r => r.name === selectedTitle);
if (!selectedRecipe) return; if (!selectedRecipe) return;
const newName = prompt(`Copy "${selectedRecipe.name}" as:`, `${selectedRecipe.name}_Copy`); const newName = prompt(`Copy "${selectedRecipe.name}" as:`, `${selectedRecipe.name}_Copy`);
if (!newName || newName.trim() === '') return; if (!newName || newName.trim() === '') return;
try { try {
const result = await comms.copyRecipe(selectedId, newName.trim()); const result = await comms.copyRecipe(selectedTitle, newName.trim());
if (result.success && result.newRecipe) { if (result.success && result.newRecipe) {
const newRecipeList = [...recipes, result.newRecipe]; await loadRecipes();
setRecipes(newRecipeList); await handleSelect(result.newRecipe);
setSelectedId(result.newRecipe.id);
setEditedRecipe(result.newRecipe);
console.log("Recipe copied successfully:", result.newRecipe); console.log("Recipe copied successfully:", result.newRecipe);
} else { } else {
alert(`Failed to copy recipe: ${result.message}`); alert(`Failed to copy recipe: ${result.message}`);
@@ -68,26 +124,25 @@ export const RecipePage: React.FC = () => {
}; };
const handleDelete = async () => { const handleDelete = async () => {
if (!selectedId) return; if (!selectedTitle) return;
const selectedRecipe = recipes.find(r => r.id === selectedId); const selectedRecipe = recipes.find(r => r.name === selectedTitle);
if (!selectedRecipe) return; if (!selectedRecipe) return;
const confirmed = window.confirm(`Are you sure you want to delete "${selectedRecipe.name}"?`); const confirmed = window.confirm(`Are you sure you want to delete "${selectedRecipe.name}"?`);
if (!confirmed) return; if (!confirmed) return;
try { try {
const result = await comms.deleteRecipe(selectedId); const result = await comms.deleteRecipe(selectedTitle);
if (result.success) { if (result.success) {
const newRecipeList = recipes.filter(r => r.id !== selectedId); await loadRecipes();
setRecipes(newRecipeList);
// Select first recipe or clear selection // Select first recipe or clear selection
const newRecipeList = recipes.filter(r => r.name !== selectedTitle);
if (newRecipeList.length > 0) { if (newRecipeList.length > 0) {
setSelectedId(newRecipeList[0].id); await handleSelect(newRecipeList[0]);
setEditedRecipe(newRecipeList[0]);
} else { } else {
setSelectedId(null); setSelectedTitle(null);
setEditedRecipe(null); setEditedRecipe(null);
} }
@@ -135,7 +190,7 @@ export const RecipePage: React.FC = () => {
onClick={() => handleSelect(r)} onClick={() => handleSelect(r)}
className={` className={`
p-3 rounded border cursor-pointer transition-all group p-3 rounded border cursor-pointer transition-all group
${selectedId === r.id ${selectedTitle === r.name
? 'bg-neon-blue/20 border-neon-blue text-white shadow-glow-blue' ? 'bg-neon-blue/20 border-neon-blue text-white shadow-glow-blue'
: 'bg-white/5 border-white/5 text-slate-400 hover:bg-white/10 hover:border-white/20'} : 'bg-white/5 border-white/5 text-slate-400 hover:bg-white/10 hover:border-white/20'}
`} `}
@@ -149,16 +204,13 @@ export const RecipePage: React.FC = () => {
</div> </div>
{/* List Actions */} {/* List Actions */}
<div className="p-3 border-t border-white/10 bg-black/20 grid grid-cols-3 gap-2"> <div className="p-3 border-t border-white/10 bg-black/20 grid grid-cols-2 gap-2">
<TechButton variant="default" className="flex justify-center" title="Add New">
<Plus className="w-4 h-4" />
</TechButton>
<TechButton <TechButton
variant="default" variant="default"
className="flex justify-center" className="flex justify-center"
title="Copy Selected" title="Copy Selected"
onClick={handleCopy} onClick={handleCopy}
disabled={!selectedId} disabled={!selectedTitle}
> >
<Copy className="w-4 h-4" /> <Copy className="w-4 h-4" />
</TechButton> </TechButton>
@@ -167,7 +219,7 @@ export const RecipePage: React.FC = () => {
className="flex justify-center" className="flex justify-center"
title="Delete Selected" title="Delete Selected"
onClick={handleDelete} onClick={handleDelete}
disabled={!selectedId} disabled={!selectedTitle}
> >
<Trash2 className="w-4 h-4" /> <Trash2 className="w-4 h-4" />
</TechButton> </TechButton>
@@ -179,44 +231,129 @@ export const RecipePage: React.FC = () => {
<div className="flex-1 bg-slate-950/40 backdrop-blur-md border border-white/10 rounded-lg flex flex-col overflow-hidden"> <div className="flex-1 bg-slate-950/40 backdrop-blur-md border border-white/10 rounded-lg flex flex-col overflow-hidden">
<div className="p-3 border-b border-white/10 bg-white/5 font-bold text-sm tracking-wider text-slate-300 flex justify-between items-center"> <div className="p-3 border-b border-white/10 bg-white/5 font-bold text-sm tracking-wider text-slate-300 flex justify-between items-center">
<span>RECIPE EDITOR</span> <span>RECIPE EDITOR</span>
{editedRecipe && <span className="text-neon-blue font-mono">{editedRecipe.id}</span>} {editedRecipe && <span className="text-neon-blue font-mono">{editedRecipe.Title || selectedTitle}</span>}
</div> </div>
<div className="flex-1 p-6 overflow-y-auto custom-scrollbar"> <div className="flex-1 p-6 overflow-y-auto custom-scrollbar">
{editedRecipe ? ( {editedRecipe ? (
<div className="max-w-2xl space-y-6"> <div className="max-w-3xl space-y-6">
{/* Basic Settings */}
<div className="space-y-4 p-4 border border-white/10 rounded-lg bg-white/5">
<h3 className="text-xs font-bold text-neon-blue uppercase tracking-wider border-b border-white/10 pb-2">Basic Settings</h3>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Recipe Name</label> <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Motion Model</label>
<input <input
type="text" type="text"
value={editedRecipe.name} value={editedRecipe.Motion || ''}
onChange={(e) => setEditedRecipe({ ...editedRecipe, name: e.target.value })} onChange={(e) => handleFieldChange('Motion', e.target.value)}
className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono" className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Description</label> <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Auto Out Conveyor</label>
<textarea <input
className="w-full h-32 bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono resize-none" type="number"
placeholder="Enter recipe description..." value={editedRecipe.AutoOutConveyor || 0}
></textarea> onChange={(e) => handleFieldChange('AutoOutConveyor', parseInt(e.target.value) || 0)}
</div> className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
/>
<div className="grid grid-cols-2 gap-6">
<div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Process Time (sec)</label>
<input type="number" className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono" defaultValue="120" />
</div>
<div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Temperature (°C)</label>
<input type="number" className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono" defaultValue="24.5" />
</div> </div>
</div> </div>
{/* Placeholder for more parameters */} <div className="grid grid-cols-2 gap-4">
<div className="p-4 border border-dashed border-white/10 rounded bg-white/5 text-center text-slate-500 text-sm"> <div className="space-y-2">
Additional process parameters would go here... <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Default Vendor Name</label>
<input
type="text"
value={editedRecipe.Def_VName || ''}
onChange={(e) => handleFieldChange('Def_VName', e.target.value)}
className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
/>
</div>
<div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Default MFG</label>
<input
type="text"
value={editedRecipe.Def_MFG || ''}
onChange={(e) => handleFieldChange('Def_MFG', e.target.value)}
className="w-full bg-black/40 border border-white/10 rounded px-4 py-2 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono text-sm"
/>
</div>
</div>
</div>
{/* Barcode Settings */}
<div className="space-y-4 p-4 border border-white/10 rounded-lg bg-white/5">
<h3 className="text-xs font-bold text-neon-blue uppercase tracking-wider border-b border-white/10 pb-2">Barcode Settings</h3>
<div className="grid grid-cols-3 gap-4">
<label className="flex items-center gap-3 cursor-pointer">
<div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe.BCD_1D ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
{editedRecipe.BCD_1D && <Check className="w-3 h-3 text-black" />}
</div>
<span className="text-sm text-slate-300">1D Barcode</span>
<input
type="checkbox"
checked={editedRecipe.BCD_1D || false}
onChange={(e) => handleFieldChange('BCD_1D', e.target.checked)}
className="hidden"
/>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe.BCD_QR ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
{editedRecipe.BCD_QR && <Check className="w-3 h-3 text-black" />}
</div>
<span className="text-sm text-slate-300">QR Code</span>
<input
type="checkbox"
checked={editedRecipe.BCD_QR || false}
onChange={(e) => handleFieldChange('BCD_QR', e.target.checked)}
className="hidden"
/>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe.BCD_DM ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
{editedRecipe.BCD_DM && <Check className="w-3 h-3 text-black" />}
</div>
<span className="text-sm text-slate-300">Data Matrix</span>
<input
type="checkbox"
checked={editedRecipe.BCD_DM || false}
onChange={(e) => handleFieldChange('BCD_DM', e.target.checked)}
className="hidden"
/>
</label>
</div>
</div>
{/* Feature Flags */}
<div className="space-y-4 p-4 border border-white/10 rounded-lg bg-white/5">
<h3 className="text-xs font-bold text-neon-blue uppercase tracking-wider border-b border-white/10 pb-2">Feature Flags</h3>
<div className="grid grid-cols-2 gap-3">
{[
{ key: 'IgnoreOtherBarcode', label: 'Ignore Other Barcode' },
{ key: 'DisableCamera', label: 'Disable Camera' },
{ key: 'DisablePrinter', label: 'Disable Printer' },
{ key: 'CheckSIDExsit', label: 'Check SID Exist' },
{ key: 'bOwnZPL', label: 'Own ZPL' },
{ key: 'IgnorePartNo', label: 'Ignore Part No' },
{ key: 'IgnoreBatch', label: 'Ignore Batch' },
].map(({ key, label }) => (
<label key={key} className="flex items-center gap-3 cursor-pointer">
<div className={`w-5 h-5 rounded border transition-all flex items-center justify-center ${editedRecipe[key] ? 'bg-neon-green border-neon-green' : 'bg-black/40 border-white/20'}`}>
{editedRecipe[key] && <Check className="w-3 h-3 text-black" />}
</div>
<span className="text-sm text-slate-300">{label}</span>
<input
type="checkbox"
checked={editedRecipe[key] || false}
onChange={(e) => handleFieldChange(key, e.target.checked)}
className="hidden"
/>
</label>
))}
</div>
</div> </div>
</div> </div>
) : ( ) : (
@@ -228,12 +365,16 @@ export const RecipePage: React.FC = () => {
</div> </div>
{/* Editor Actions */} {/* Editor Actions */}
<div className="p-4 border-t border-white/10 bg-black/20 flex justify-end"> <div className="p-4 border-t border-white/10 bg-black/20 flex justify-between items-center">
{hasChanges && (
<span className="text-xs text-neon-yellow font-mono animate-pulse"> UNSAVED CHANGES</span>
)}
<div className="ml-auto">
<TechButton <TechButton
variant="green" variant="green"
className="flex items-center gap-2 px-8" className="flex items-center gap-2 px-8"
onClick={handleSave} onClick={handleSave}
disabled={!editedRecipe} disabled={!editedRecipe || !hasChanges}
> >
<Save className="w-4 h-4" /> SAVE CHANGES <Save className="w-4 h-4" /> SAVE CHANGES
</TechButton> </TechButton>
@@ -241,5 +382,6 @@ export const RecipePage: React.FC = () => {
</div> </div>
</div> </div>
</div> </div>
</div>
); );
}; };

View File

@@ -65,6 +65,8 @@ declare global {
GetConfig(): Promise<string>; GetConfig(): Promise<string>;
GetIOList(): Promise<string>; GetIOList(): Promise<string>;
GetRecipeList(): Promise<string>; GetRecipeList(): Promise<string>;
GetRecipe(recipeTitle: string): Promise<string>;
SaveRecipe(recipeTitle: string, recipeData: string): Promise<string>;
SaveConfig(configJson: string): Promise<void>; SaveConfig(configJson: string): Promise<void>;
} }
}; };