mcp-grocy 2.7.1 → 2.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +15 -5
- package/build/api/client.js +119 -0
- package/build/config/index.js +283 -0
- package/build/main.js +44 -0
- package/build/resources/CHANGELOG.md +9 -3
- package/build/resources/README.md +15 -5
- package/build/resources/api-reference.md +2 -1
- package/build/resources/response-format.md +1 -3
- package/build/server/http-server.js +398 -0
- package/build/server/mcp-server.js +230 -0
- package/build/server/resources.js +73 -0
- package/build/server/tool-input-zod.js +86 -0
- package/build/tools/base.js +157 -0
- package/build/tools/household/definitions.js +161 -0
- package/build/tools/household/handlers.js +109 -0
- package/build/tools/household/index.js +25 -0
- package/build/tools/index.js +2 -0
- package/build/tools/inventory/definitions.js +416 -0
- package/build/tools/inventory/handlers.js +443 -0
- package/build/tools/inventory/index.js +32 -0
- package/build/tools/module-loader.js +154 -0
- package/build/tools/recipes/definitions.js +278 -0
- package/build/tools/recipes/handlers.js +518 -0
- package/build/tools/recipes/index.js +33 -0
- package/build/tools/recipes/validations.js +29 -0
- package/build/tools/shopping/definitions.js +147 -0
- package/build/tools/shopping/handlers.js +198 -0
- package/build/tools/shopping/index.js +17 -0
- package/build/tools/system/definitions.js +89 -0
- package/build/tools/system/handlers.js +156 -0
- package/build/tools/system/index.js +16 -0
- package/build/tools/types.js +1 -0
- package/build/tools/validation-helpers.js +39 -0
- package/build/types/index.js +64 -0
- package/build/utils/errors.js +143 -0
- package/build/utils/logger.js +142 -0
- package/build/version.js +1 -1
- package/package.json +27 -25
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Simplified recipe tool handlers
|
|
3
|
+
* Demonstrates the new simplified pattern
|
|
4
|
+
*/
|
|
5
|
+
import { BaseToolHandler } from '../base.js';
|
|
6
|
+
import { InventoryToolHandlers } from '../inventory/handlers.js';
|
|
7
|
+
import { ValidationError } from '../../utils/errors.js';
|
|
8
|
+
const RECIPES_COOKING_COMPLETE_TOOL = 'recipes_cooking_complete';
|
|
9
|
+
export class RecipeToolHandlers extends BaseToolHandler {
|
|
10
|
+
inventoryHandlers = new InventoryToolHandlers();
|
|
11
|
+
/**
|
|
12
|
+
* Helper method to get meal plan for multiple days
|
|
13
|
+
*/
|
|
14
|
+
async getMealPlanForDays(dates) {
|
|
15
|
+
const allResults = [];
|
|
16
|
+
for (const date of dates) {
|
|
17
|
+
const dayString = date.toISOString().split('T')[0];
|
|
18
|
+
const dayResult = await this.apiCall(`/objects/meal_plan`, 'GET', undefined, {
|
|
19
|
+
queryParams: {
|
|
20
|
+
'query[]': `day=${dayString}`,
|
|
21
|
+
order: 'day',
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
if (Array.isArray(dayResult)) {
|
|
25
|
+
allResults.push(...dayResult);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return allResults;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Validate a YYYY-MM-DD day parameter. Grocy stores any string in this column, so both the
|
|
32
|
+
* format and the calendar date are checked before writing.
|
|
33
|
+
*/
|
|
34
|
+
validateDay(day, context) {
|
|
35
|
+
const parsed = typeof day === 'string' ? new Date(`${day}T00:00:00Z`) : new Date(NaN);
|
|
36
|
+
const valid = typeof day === 'string' &&
|
|
37
|
+
/^\d{4}-\d{2}-\d{2}$/.test(day) &&
|
|
38
|
+
!Number.isNaN(parsed.getTime()) &&
|
|
39
|
+
parsed.toISOString().slice(0, 10) === day;
|
|
40
|
+
if (!valid) {
|
|
41
|
+
throw new ValidationError('day must be a valid calendar date in YYYY-MM-DD format (e.g., "2024-12-25").', context);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Create a meal plan entry with the same payload shape as the Grocy UI.
|
|
46
|
+
* `fields` carries the type-specific columns of the entry (type, recipe_id, recipe_servings, ...).
|
|
47
|
+
*/
|
|
48
|
+
async createMealPlanEntry(day, sectionId, fields, context) {
|
|
49
|
+
this.validateDay(day, context);
|
|
50
|
+
const section = this.parseNumberParam(sectionId, 'sectionId');
|
|
51
|
+
// Grocy has no section 0 and no foreign-key check: -1 is its built-in "no section",
|
|
52
|
+
// real section ids start at 1.
|
|
53
|
+
if (!Number.isInteger(section) || (section !== -1 && section < 1)) {
|
|
54
|
+
throw new ValidationError('sectionId must be a section id from recipes_mealplan_get_sections, or -1 for no section', context);
|
|
55
|
+
}
|
|
56
|
+
return this.apiCall('/objects/meal_plan', 'POST', { day, section_id: section, ...fields });
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Get recipes with specified fields
|
|
60
|
+
*/
|
|
61
|
+
getRecipes = async (args) => {
|
|
62
|
+
return this.executeToolHandler(async () => {
|
|
63
|
+
const { fields } = args || {};
|
|
64
|
+
// Validate required parameters
|
|
65
|
+
this.validateRequired({ fields }, ['fields']);
|
|
66
|
+
const fieldList = this.parseArrayParam(fields, 'fields');
|
|
67
|
+
// Fetch recipes
|
|
68
|
+
const recipes = await this.apiCall('/objects/recipes', 'GET', undefined, {
|
|
69
|
+
queryParams: { 'query[]': 'type=normal' },
|
|
70
|
+
});
|
|
71
|
+
if (!Array.isArray(recipes)) {
|
|
72
|
+
return this.createSuccess([]);
|
|
73
|
+
}
|
|
74
|
+
// Filter to requested fields
|
|
75
|
+
const filteredRecipes = this.filterFields(recipes, fieldList);
|
|
76
|
+
return this.createSuccess(filteredRecipes);
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Get recipe by ID
|
|
81
|
+
*/
|
|
82
|
+
getRecipeById = async (args) => {
|
|
83
|
+
return this.executeToolHandler(async () => {
|
|
84
|
+
const { recipeId } = args || {};
|
|
85
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
86
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
87
|
+
const recipe = await this.apiCall(`/objects/recipes/${id}`);
|
|
88
|
+
return this.createSuccess(recipe);
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Get recipe fulfillment information
|
|
93
|
+
*/
|
|
94
|
+
getRecipeFulfillment = async (args) => {
|
|
95
|
+
return this.executeToolHandler(async () => {
|
|
96
|
+
const { recipeId } = args || {};
|
|
97
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
98
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
99
|
+
const fulfillment = await this.apiCall(`/recipes/${id}/fulfillment`);
|
|
100
|
+
return this.createSuccess(fulfillment);
|
|
101
|
+
});
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Add recipe to meal plan
|
|
105
|
+
*/
|
|
106
|
+
addRecipeToMealPlan = async (args) => {
|
|
107
|
+
return this.executeToolHandler(async () => {
|
|
108
|
+
const { recipeId, day, servings, sectionId } = args || {};
|
|
109
|
+
this.validateRequired({ recipeId, day, servings, sectionId }, [
|
|
110
|
+
'recipeId',
|
|
111
|
+
'day',
|
|
112
|
+
'servings',
|
|
113
|
+
'sectionId',
|
|
114
|
+
]);
|
|
115
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
116
|
+
const recipeServings = this.parseNumberParam(servings, 'servings');
|
|
117
|
+
if (recipeServings <= 0) {
|
|
118
|
+
throw new ValidationError('servings must be a positive number', 'recipes_mealplan_add_recipe');
|
|
119
|
+
}
|
|
120
|
+
const result = await this.createMealPlanEntry(day, sectionId, { type: 'recipe', recipe_id: id, recipe_servings: recipeServings }, 'recipes_mealplan_add_recipe');
|
|
121
|
+
return this.createSuccess(result, 'Recipe added to meal plan successfully');
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* Cook recipe - consume ingredients from stock
|
|
126
|
+
*/
|
|
127
|
+
cookRecipe = async (args) => {
|
|
128
|
+
return this.executeToolHandler(async () => {
|
|
129
|
+
const { recipeId, servings } = args || {};
|
|
130
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
131
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
132
|
+
const servingCount = this.parseNumberParam(servings, 'servings', false) || 1;
|
|
133
|
+
// Get recipe details first
|
|
134
|
+
const recipe = await this.apiCall(`/objects/recipes/${id}`);
|
|
135
|
+
// Cook the recipe
|
|
136
|
+
const cookData = {
|
|
137
|
+
recipe_id: id,
|
|
138
|
+
servings: servingCount,
|
|
139
|
+
};
|
|
140
|
+
const result = await this.apiCall('/recipes/cook', 'POST', cookData);
|
|
141
|
+
return this.createSuccess({
|
|
142
|
+
recipe: recipe.name,
|
|
143
|
+
servings: servingCount,
|
|
144
|
+
result,
|
|
145
|
+
}, `Recipe "${recipe.name}" cooked successfully`);
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* Get recipe nutrition information
|
|
150
|
+
*/
|
|
151
|
+
getRecipeNutrition = async (args) => {
|
|
152
|
+
return this.executeToolHandler(async () => {
|
|
153
|
+
const { recipeId } = args || {};
|
|
154
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
155
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
156
|
+
const nutrition = await this.apiCall(`/recipes/${id}/nutrition`);
|
|
157
|
+
return this.createSuccess(nutrition);
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
/**
|
|
161
|
+
* Search recipes by name or ingredients
|
|
162
|
+
*/
|
|
163
|
+
searchRecipes = async (args) => {
|
|
164
|
+
return this.executeToolHandler(async () => {
|
|
165
|
+
const { query, fields } = args || {};
|
|
166
|
+
this.validateRequired({ query }, ['query']);
|
|
167
|
+
const fieldList = this.parseArrayParam(fields || ['id', 'name'], 'fields');
|
|
168
|
+
// Get all recipes and filter locally
|
|
169
|
+
// Note: This could be optimized with server-side search if Grocy supports it
|
|
170
|
+
const recipes = await this.apiCall('/objects/recipes', 'GET', undefined, {
|
|
171
|
+
queryParams: { 'query[]': 'type=normal' },
|
|
172
|
+
});
|
|
173
|
+
if (!Array.isArray(recipes)) {
|
|
174
|
+
return this.createSuccess([]);
|
|
175
|
+
}
|
|
176
|
+
const searchTerm = query.toLowerCase();
|
|
177
|
+
const filtered = recipes.filter((recipe) => recipe.name?.toLowerCase().includes(searchTerm) ||
|
|
178
|
+
recipe.description?.toLowerCase().includes(searchTerm));
|
|
179
|
+
const result = this.filterFields(filtered, fieldList);
|
|
180
|
+
return this.createSuccess(result);
|
|
181
|
+
});
|
|
182
|
+
};
|
|
183
|
+
// ==================== MEAL PLANNING METHODS ====================
|
|
184
|
+
/**
|
|
185
|
+
* Get meal plan data with context
|
|
186
|
+
*/
|
|
187
|
+
getMealPlan = async (args) => {
|
|
188
|
+
return this.executeToolHandler(async () => {
|
|
189
|
+
const { date, weekly } = args || {};
|
|
190
|
+
// Date parameter is mandatory
|
|
191
|
+
this.validateRequired({ date }, ['date']);
|
|
192
|
+
const targetDate = new Date(date);
|
|
193
|
+
if (isNaN(targetDate.getTime())) {
|
|
194
|
+
throw new ValidationError('Invalid date format. Use YYYY-MM-DD.', 'getMealPlan');
|
|
195
|
+
}
|
|
196
|
+
const datesToQuery = [];
|
|
197
|
+
if (weekly) {
|
|
198
|
+
// For weekly view, get the start of the week (Monday)
|
|
199
|
+
const dayOfWeek = targetDate.getDay();
|
|
200
|
+
const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
|
|
201
|
+
const startDate = new Date(targetDate);
|
|
202
|
+
startDate.setDate(targetDate.getDate() + mondayOffset);
|
|
203
|
+
// Get all 7 days of the week with ±1 day buffer for timezone issues
|
|
204
|
+
for (let i = -1; i <= 7; i++) {
|
|
205
|
+
const day = new Date(startDate);
|
|
206
|
+
day.setDate(startDate.getDate() + i);
|
|
207
|
+
datesToQuery.push(day);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
// Get the specific date with ±1 day buffer for timezone issues
|
|
212
|
+
const dayBefore = new Date(targetDate);
|
|
213
|
+
dayBefore.setDate(targetDate.getDate() - 1);
|
|
214
|
+
const dayAfter = new Date(targetDate);
|
|
215
|
+
dayAfter.setDate(targetDate.getDate() + 1);
|
|
216
|
+
datesToQuery.push(dayBefore, targetDate, dayAfter);
|
|
217
|
+
}
|
|
218
|
+
const result = await this.getMealPlanForDays(datesToQuery);
|
|
219
|
+
if (result.length === 0) {
|
|
220
|
+
return this.createSuccess({
|
|
221
|
+
message: weekly
|
|
222
|
+
? 'No meals planned for the requested week'
|
|
223
|
+
: 'No meals planned for the requested date',
|
|
224
|
+
meal_plan_by_date: {},
|
|
225
|
+
}, 'Meal plan retrieved successfully');
|
|
226
|
+
}
|
|
227
|
+
// Extract unique recipe IDs
|
|
228
|
+
const recipeIds = [...new Set(result.map((entry) => entry.recipe_id).filter((id) => id))];
|
|
229
|
+
// Fetch recipe details and all sections in parallel
|
|
230
|
+
const [recipeDetails, allSections] = await Promise.all([
|
|
231
|
+
Promise.all(recipeIds.map((recipeId) => this.apiCall(`/objects/recipes/${recipeId}`))),
|
|
232
|
+
this.apiCall('/objects/meal_plan_sections'),
|
|
233
|
+
]);
|
|
234
|
+
// Simplify meal plan entries - don't merge recipe/section details
|
|
235
|
+
const simplifiedMealPlanByDate = {};
|
|
236
|
+
result.forEach((entry) => {
|
|
237
|
+
const entryDate = entry.day;
|
|
238
|
+
if (!simplifiedMealPlanByDate[entryDate]) {
|
|
239
|
+
simplifiedMealPlanByDate[entryDate] = [];
|
|
240
|
+
}
|
|
241
|
+
simplifiedMealPlanByDate[entryDate].push({
|
|
242
|
+
id: entry.id,
|
|
243
|
+
day: entry.day,
|
|
244
|
+
section_id: entry.section_id,
|
|
245
|
+
recipe_id: entry.recipe_id,
|
|
246
|
+
recipe_servings: entry.recipe_servings,
|
|
247
|
+
note: entry.note,
|
|
248
|
+
done: entry.done,
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
return this.createSuccess({
|
|
252
|
+
meal_plan_by_date: simplifiedMealPlanByDate,
|
|
253
|
+
recipes: recipeDetails.map((recipe) => ({
|
|
254
|
+
id: recipe.id,
|
|
255
|
+
name: recipe.name,
|
|
256
|
+
product_id: recipe.product_id,
|
|
257
|
+
})),
|
|
258
|
+
sections: Array.isArray(allSections)
|
|
259
|
+
? allSections.map((section) => ({
|
|
260
|
+
id: section.id,
|
|
261
|
+
name: section.name,
|
|
262
|
+
time_info: section.time_info,
|
|
263
|
+
}))
|
|
264
|
+
: [],
|
|
265
|
+
}, 'Meal plan retrieved successfully');
|
|
266
|
+
});
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* Get meal plan sections
|
|
270
|
+
*/
|
|
271
|
+
getMealPlanSections = async () => {
|
|
272
|
+
return this.executeToolHandler(async () => {
|
|
273
|
+
const result = await this.apiCall('/objects/meal_plan_sections');
|
|
274
|
+
return this.createSuccess(result, 'Meal plan sections retrieved successfully');
|
|
275
|
+
});
|
|
276
|
+
};
|
|
277
|
+
/**
|
|
278
|
+
* Delete recipe from meal plan
|
|
279
|
+
*/
|
|
280
|
+
deleteRecipeFromMealPlan = async (args) => {
|
|
281
|
+
return this.executeToolHandler(async () => {
|
|
282
|
+
const { mealPlanEntryId } = args || {};
|
|
283
|
+
this.validateRequired({ mealPlanEntryId }, ['mealPlanEntryId']);
|
|
284
|
+
const result = await this.apiCall(`/objects/meal_plan/${mealPlanEntryId}`, 'DELETE');
|
|
285
|
+
return this.createSuccess(result, 'Recipe deleted from meal plan successfully');
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
// ==================== RECIPE CREATION ====================
|
|
289
|
+
/**
|
|
290
|
+
* Create a new recipe
|
|
291
|
+
*/
|
|
292
|
+
printRecipeLabel = async (args) => {
|
|
293
|
+
return this.executeToolHandler(async () => {
|
|
294
|
+
const { recipeId } = args || {};
|
|
295
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
296
|
+
const result = await this.apiCall(`/recipes/${recipeId}/printlabel`);
|
|
297
|
+
return this.createSuccess(result, 'Recipe label printed successfully');
|
|
298
|
+
});
|
|
299
|
+
};
|
|
300
|
+
createRecipe = async (args) => {
|
|
301
|
+
return this.executeToolHandler(async () => {
|
|
302
|
+
const { name, description, baseServings, instructions } = args || {};
|
|
303
|
+
this.validateRequired({ name }, ['name']);
|
|
304
|
+
const recipeData = {
|
|
305
|
+
name,
|
|
306
|
+
description: description || '',
|
|
307
|
+
base_servings: baseServings || 1,
|
|
308
|
+
type: 'normal',
|
|
309
|
+
instructions: instructions || '',
|
|
310
|
+
};
|
|
311
|
+
const result = await this.apiCall('/objects/recipes', 'POST', recipeData);
|
|
312
|
+
return this.createSuccess(result, `Recipe "${name}" created successfully`);
|
|
313
|
+
});
|
|
314
|
+
};
|
|
315
|
+
// ==================== RECIPE FULFILLMENT ====================
|
|
316
|
+
/**
|
|
317
|
+
* Get fulfillment status for all recipes
|
|
318
|
+
*/
|
|
319
|
+
getAllRecipeFulfillment = async () => {
|
|
320
|
+
return this.executeToolHandler(async () => {
|
|
321
|
+
const fulfillment = await this.apiCall('/recipes/fulfillment');
|
|
322
|
+
return this.createSuccess(fulfillment);
|
|
323
|
+
});
|
|
324
|
+
};
|
|
325
|
+
// ==================== RECIPE CONSUMPTION ====================
|
|
326
|
+
/**
|
|
327
|
+
* Consume/cook a recipe (simple version)
|
|
328
|
+
*/
|
|
329
|
+
consumeRecipe = async (args) => {
|
|
330
|
+
return this.executeToolHandler(async () => {
|
|
331
|
+
const { recipeId, servings } = args || {};
|
|
332
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
333
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
334
|
+
const servingCount = this.parseNumberParam(servings, 'servings', false) || 1;
|
|
335
|
+
const consumeData = {
|
|
336
|
+
recipe_id: id,
|
|
337
|
+
servings: servingCount,
|
|
338
|
+
};
|
|
339
|
+
const result = await this.apiCall('/recipes/consume', 'POST', consumeData);
|
|
340
|
+
return this.createSuccess(result, `Recipe consumed (${servingCount} servings)`);
|
|
341
|
+
});
|
|
342
|
+
};
|
|
343
|
+
// ==================== RECIPE SHOPPING INTEGRATION ====================
|
|
344
|
+
/**
|
|
345
|
+
* Add all products from a recipe to shopping list
|
|
346
|
+
*/
|
|
347
|
+
addAllProductsToShopping = async (args) => {
|
|
348
|
+
return this.executeToolHandler(async () => {
|
|
349
|
+
const { recipeId } = args || {};
|
|
350
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
351
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
352
|
+
const result = await this.apiCall(`/recipes/${id}/add-all-ingredients-to-shopping-list`, 'POST');
|
|
353
|
+
return this.createSuccess(result, 'All recipe products added to shopping list');
|
|
354
|
+
});
|
|
355
|
+
};
|
|
356
|
+
/**
|
|
357
|
+
* Add missing products from a recipe to shopping list
|
|
358
|
+
*/
|
|
359
|
+
addMissingProductsToShopping = async (args) => {
|
|
360
|
+
return this.executeToolHandler(async () => {
|
|
361
|
+
const { recipeId } = args || {};
|
|
362
|
+
this.validateRequired({ recipeId }, ['recipeId']);
|
|
363
|
+
const id = this.parseNumberParam(recipeId, 'recipeId');
|
|
364
|
+
const result = await this.apiCall(`/recipes/${id}/add-not-fulfilled-products-to-shopping-list`, 'POST');
|
|
365
|
+
return this.createSuccess(result, 'Missing recipe products added to shopping list');
|
|
366
|
+
});
|
|
367
|
+
};
|
|
368
|
+
// ==================== COOKING METHODS ====================
|
|
369
|
+
/**
|
|
370
|
+
* Mark recipe from meal plan entry as cooked - modernized version
|
|
371
|
+
*/
|
|
372
|
+
cookedSomething = async (args) => {
|
|
373
|
+
return this.executeToolHandler(async () => {
|
|
374
|
+
const { mealPlanEntryId, recipeId, stockAmounts } = args || {};
|
|
375
|
+
// Get configuration from unified config
|
|
376
|
+
const { config } = await import('../../config/index.js');
|
|
377
|
+
const { toolSubConfigs } = config.parseToolConfiguration();
|
|
378
|
+
const subConfigs = toolSubConfigs?.get(RECIPES_COOKING_COMPLETE_TOOL);
|
|
379
|
+
const allowMealPlanEntryAlreadyDone = subConfigs?.get('allow_meal_plan_entry_already_done') ?? false;
|
|
380
|
+
const printLabels = subConfigs?.get('print_labels') ?? true;
|
|
381
|
+
const allowNoMealPlan = subConfigs?.get('allow_no_meal_plan') ?? false;
|
|
382
|
+
// Validate parameters based on configuration
|
|
383
|
+
if (!allowNoMealPlan && !mealPlanEntryId) {
|
|
384
|
+
throw new ValidationError('mealPlanEntryId is required when allow_no_meal_plan is false.', 'recipes_cooking_complete');
|
|
385
|
+
}
|
|
386
|
+
if (allowNoMealPlan && !recipeId) {
|
|
387
|
+
throw new ValidationError('recipeId is required when allow_no_meal_plan is true.', 'recipes_cooking_complete');
|
|
388
|
+
}
|
|
389
|
+
if (allowNoMealPlan && mealPlanEntryId) {
|
|
390
|
+
throw new ValidationError('mealPlanEntryId should not be provided when allow_no_meal_plan is true. Use recipeId instead.', 'recipes_cooking_complete');
|
|
391
|
+
}
|
|
392
|
+
this.validateRequired({ stockAmounts }, ['stockAmounts']);
|
|
393
|
+
if (!Array.isArray(stockAmounts) || stockAmounts.length === 0) {
|
|
394
|
+
throw new ValidationError('stockAmounts must be a non-empty array of serving amounts.', 'recipes_cooking_complete');
|
|
395
|
+
}
|
|
396
|
+
// Validate all stock amounts are positive numbers
|
|
397
|
+
for (let i = 0; i < stockAmounts.length; i++) {
|
|
398
|
+
const amount = stockAmounts[i];
|
|
399
|
+
if (typeof amount !== 'number' || amount <= 0) {
|
|
400
|
+
throw new ValidationError(`stockAmounts[${i}] must be a positive number, got: ${amount}`, 'recipes_cooking_complete');
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const completedSteps = [];
|
|
404
|
+
let actualRecipeId;
|
|
405
|
+
let totalServings;
|
|
406
|
+
let mealPlanDate;
|
|
407
|
+
let mealplanShadow;
|
|
408
|
+
if (allowNoMealPlan) {
|
|
409
|
+
// Direct recipe mode - no meal plan entry involved
|
|
410
|
+
actualRecipeId = recipeId;
|
|
411
|
+
totalServings = stockAmounts.reduce((sum, amount) => sum + amount, 0);
|
|
412
|
+
mealPlanDate = new Date().toISOString().split('T')[0];
|
|
413
|
+
mealplanShadow = `${mealPlanDate}#direct-recipe-${actualRecipeId}`;
|
|
414
|
+
completedSteps.push('Using direct recipe mode (no meal plan entry)');
|
|
415
|
+
}
|
|
416
|
+
else {
|
|
417
|
+
// Meal plan mode - traditional workflow
|
|
418
|
+
const mealPlanEntry = await this.apiCall(`/objects/meal_plan/${mealPlanEntryId}`);
|
|
419
|
+
if (!mealPlanEntry) {
|
|
420
|
+
throw new ValidationError(`Meal plan entry ${mealPlanEntryId} not found.`, 'recipes_cooking_complete');
|
|
421
|
+
}
|
|
422
|
+
// Only recipe-typed entries are handled here; check before any write so a note, a
|
|
423
|
+
// product entry or an entry with an unrecognised type is never marked as done.
|
|
424
|
+
if (mealPlanEntry.type !== 'recipe' || mealPlanEntry.recipe_id == null) {
|
|
425
|
+
const hasRecipe = mealPlanEntry.recipe_id != null;
|
|
426
|
+
const reason = hasRecipe
|
|
427
|
+
? 'it was stored with an unrecognised type, so Grocy created no shadow recipe for it; delete it with recipes_mealplan_delete_entry and plan it again'
|
|
428
|
+
: 'note entries have nothing to consume and product entries are not supported by this tool';
|
|
429
|
+
throw new ValidationError(`Meal plan entry ${mealPlanEntryId} cannot be cooked (type '${mealPlanEntry.type ?? 'unknown'}'${hasRecipe ? '' : ', no recipe_id'}): only entries with type 'recipe' are handled; ${reason}.`, 'recipes_cooking_complete');
|
|
430
|
+
}
|
|
431
|
+
if (mealPlanEntry.done == 1 && !allowMealPlanEntryAlreadyDone) {
|
|
432
|
+
throw new ValidationError(`Meal plan entry ${mealPlanEntryId} is already marked as done. Cannot mark as cooked again.`, 'recipes_cooking_complete');
|
|
433
|
+
}
|
|
434
|
+
actualRecipeId = mealPlanEntry.recipe_id;
|
|
435
|
+
totalServings = stockAmounts.reduce((sum, amount) => sum + amount, 0);
|
|
436
|
+
mealPlanDate = mealPlanEntry.day || new Date().toISOString().split('T')[0];
|
|
437
|
+
mealplanShadow = `${mealPlanDate}#${mealPlanEntryId}`;
|
|
438
|
+
// Mark the meal plan entry as done and update recipe_servings
|
|
439
|
+
await this.apiCall(`/objects/meal_plan/${mealPlanEntryId}`, 'PUT', {
|
|
440
|
+
done: 1,
|
|
441
|
+
recipe_servings: totalServings,
|
|
442
|
+
});
|
|
443
|
+
completedSteps.push('Meal plan entry marked as done');
|
|
444
|
+
}
|
|
445
|
+
// Consume recipe ingredients
|
|
446
|
+
if (allowNoMealPlan) {
|
|
447
|
+
// Direct consumption using the recipe ID
|
|
448
|
+
await this.apiCall(`/recipes/${actualRecipeId}/consume`, 'POST');
|
|
449
|
+
completedSteps.push('Recipe consumed directly');
|
|
450
|
+
}
|
|
451
|
+
else {
|
|
452
|
+
// Query for the mealplan shadow recipe by name
|
|
453
|
+
const shadowRecipes = await this.apiCall('/objects/recipes', 'GET', undefined, {
|
|
454
|
+
queryParams: { 'query[]': `name=${mealplanShadow}` },
|
|
455
|
+
});
|
|
456
|
+
if (!Array.isArray(shadowRecipes) || shadowRecipes.length === 0) {
|
|
457
|
+
throw new ValidationError(`Mealplan shadow recipe '${mealplanShadow}' not found. Cannot consume ingredients.`, 'recipes_cooking_complete');
|
|
458
|
+
}
|
|
459
|
+
const shadowRecipeId = shadowRecipes[0].id;
|
|
460
|
+
// Consume ingredients using the shadow recipe ID
|
|
461
|
+
await this.apiCall(`/recipes/${shadowRecipeId}/consume`, 'POST');
|
|
462
|
+
completedSteps.push('Recipe consumed via meal plan entry');
|
|
463
|
+
}
|
|
464
|
+
// Handle stock entry splitting and label printing
|
|
465
|
+
const stockEntries = { splitEntries: [], labelsPrinted: 0 };
|
|
466
|
+
const recipe = await this.apiCall(`/objects/recipes/${actualRecipeId}`);
|
|
467
|
+
if (recipe && recipe.product_id) {
|
|
468
|
+
// Get product details and most recent stock entry
|
|
469
|
+
const [product, entries] = await Promise.all([
|
|
470
|
+
this.apiCall(`/objects/products/${recipe.product_id}`),
|
|
471
|
+
this.apiCall(`/stock/products/${recipe.product_id}/entries`, 'GET', undefined, {
|
|
472
|
+
queryParams: { order: 'row_created_timestamp:desc', limit: '1' },
|
|
473
|
+
}),
|
|
474
|
+
]);
|
|
475
|
+
// Get quantity unit info
|
|
476
|
+
let quantityUnit = null;
|
|
477
|
+
if (product.qu_id_stock) {
|
|
478
|
+
try {
|
|
479
|
+
quantityUnit = await this.apiCall(`/objects/quantity_units/${product.qu_id_stock}`);
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
console.warn('Failed to fetch quantity unit:', error);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
// Helper function to get correct unit form
|
|
486
|
+
const getUnitForm = (amount) => {
|
|
487
|
+
if (!quantityUnit || !quantityUnit.name)
|
|
488
|
+
return '';
|
|
489
|
+
if (amount === 1)
|
|
490
|
+
return quantityUnit.name;
|
|
491
|
+
return quantityUnit.name_plural || quantityUnit.name;
|
|
492
|
+
};
|
|
493
|
+
if (Array.isArray(entries) && entries.length > 0) {
|
|
494
|
+
const originalEntry = entries[0];
|
|
495
|
+
// Use the real stock splitting functionality
|
|
496
|
+
stockEntries.splitEntries = await this.inventoryHandlers.splitStockEntry(originalEntry, stockAmounts, getUnitForm);
|
|
497
|
+
// Print labels for all entries (if enabled)
|
|
498
|
+
if (printLabels) {
|
|
499
|
+
for (const entry of stockEntries.splitEntries) {
|
|
500
|
+
try {
|
|
501
|
+
await this.apiCall(`/stock/entry/${originalEntry.id}/printlabel`);
|
|
502
|
+
stockEntries.labelsPrinted++;
|
|
503
|
+
}
|
|
504
|
+
catch (error) {
|
|
505
|
+
console.error(`Failed to print label for stock entry ${entry.stockId}:`, error);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return this.createSuccess({
|
|
512
|
+
message: `Recipe ${actualRecipeId} cooked (${totalServings} servings consumed, ${stockEntries.splitEntries.length} stock entries created, ${stockEntries.labelsPrinted} labels printed)`,
|
|
513
|
+
stockEntries,
|
|
514
|
+
completedSteps,
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
};
|
|
518
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { recipeToolDefinitions } from './definitions.js';
|
|
2
|
+
import { RecipeToolHandlers } from './handlers.js';
|
|
3
|
+
import { validateCompleteSubConfigs } from './validations.js';
|
|
4
|
+
// Use simplified handlers
|
|
5
|
+
const handlers = new RecipeToolHandlers();
|
|
6
|
+
export const recipeModule = {
|
|
7
|
+
definitions: recipeToolDefinitions,
|
|
8
|
+
handlers: {
|
|
9
|
+
// Recipe Management
|
|
10
|
+
recipes_management_get: handlers.getRecipes,
|
|
11
|
+
recipes_management_get_by_id: handlers.getRecipeById,
|
|
12
|
+
recipes_management_create: handlers.createRecipe,
|
|
13
|
+
recipes_management_print_label: handlers.printRecipeLabel,
|
|
14
|
+
// Recipe Fulfillment
|
|
15
|
+
recipes_fulfillment_get: handlers.getRecipeFulfillment,
|
|
16
|
+
recipes_fulfillment_get_all: handlers.getAllRecipeFulfillment,
|
|
17
|
+
// Meal Planning
|
|
18
|
+
recipes_mealplan_get: handlers.getMealPlan,
|
|
19
|
+
recipes_mealplan_get_sections: handlers.getMealPlanSections,
|
|
20
|
+
recipes_mealplan_add_recipe: handlers.addRecipeToMealPlan,
|
|
21
|
+
recipes_mealplan_delete_entry: handlers.deleteRecipeFromMealPlan,
|
|
22
|
+
// Recipe Cooking
|
|
23
|
+
recipes_cooking_consume: handlers.consumeRecipe,
|
|
24
|
+
recipes_cooking_complete: handlers.cookedSomething,
|
|
25
|
+
// Shopping Integration
|
|
26
|
+
recipes_shopping_add_all_products: handlers.addAllProductsToShopping,
|
|
27
|
+
recipes_shopping_add_missing_products: handlers.addMissingProductsToShopping,
|
|
28
|
+
},
|
|
29
|
+
validators: {
|
|
30
|
+
recipes_cooking_complete: validateCompleteSubConfigs,
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
export * from './definitions.js';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recipe tools sub-configuration validation functions
|
|
3
|
+
*/
|
|
4
|
+
import { ValidationHelpers } from '../validation-helpers.js';
|
|
5
|
+
import { ValidationError } from '../../utils/errors.js';
|
|
6
|
+
/**
|
|
7
|
+
* Validation function for complete tool sub-configurations
|
|
8
|
+
*/
|
|
9
|
+
export const validateCompleteSubConfigs = (subConfigs) => {
|
|
10
|
+
const allowMealPlanEntryAlreadyDone = subConfigs.get('allow_meal_plan_entry_already_done');
|
|
11
|
+
const allowNoMealPlan = subConfigs.get('allow_no_meal_plan');
|
|
12
|
+
const printLabels = subConfigs.get('print_labels');
|
|
13
|
+
// Validate types
|
|
14
|
+
ValidationHelpers.validateBoolean(allowMealPlanEntryAlreadyDone, 'allow_meal_plan_entry_already_done');
|
|
15
|
+
ValidationHelpers.validateBoolean(allowNoMealPlan, 'allow_no_meal_plan');
|
|
16
|
+
ValidationHelpers.validateBoolean(printLabels, 'print_labels');
|
|
17
|
+
// Business logic validation
|
|
18
|
+
if (allowNoMealPlan && allowMealPlanEntryAlreadyDone) {
|
|
19
|
+
throw new ValidationError('allow_no_meal_plan and allow_meal_plan_entry_already_done cannot both be true - they are mutually exclusive modes', 'complete sub-config');
|
|
20
|
+
}
|
|
21
|
+
// Check for unknown options
|
|
22
|
+
const knownOptions = new Set([
|
|
23
|
+
'allow_meal_plan_entry_already_done',
|
|
24
|
+
'allow_no_meal_plan',
|
|
25
|
+
'print_labels',
|
|
26
|
+
'ack_token',
|
|
27
|
+
]);
|
|
28
|
+
ValidationHelpers.validateKnownOptions(subConfigs, knownOptions, 'complete');
|
|
29
|
+
};
|