@holoscript/plugin-restaurant 2.0.1

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 ADDED
@@ -0,0 +1,14 @@
1
+ # @holoscript/plugin-restaurant
2
+
3
+ ## 2.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [c64fc1a]
8
+ - @holoscript/core@8.0.6
9
+
10
+ ## 2.0.0
11
+
12
+ ### Patch Changes
13
+
14
+ - @holoscript/core@6.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 HoloScript Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@holoscript/plugin-restaurant",
3
+ "version": "2.0.1",
4
+ "main": "src/index.ts",
5
+ "peerDependencies": {
6
+ "@holoscript/core": "8.0.6"
7
+ },
8
+ "license": "MIT",
9
+ "scripts": {
10
+ "test": "vitest run --passWithNoTests",
11
+ "test:coverage": "vitest run --coverage --passWithNoTests"
12
+ }
13
+ }
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Restaurant operations solver tests — restaurant-plugin
3
+ *
4
+ * Reference values verified against:
5
+ * - Kasavana M, Smith D (1982) Menu Engineering. Hospitality Publications.
6
+ * - National Restaurant Association food cost standards (28-32%)
7
+ * - SJF scheduling theory
8
+ */
9
+
10
+ import { describe, it, expect } from 'vitest';
11
+ import {
12
+ tableAssignment,
13
+ kitchenQueueScheduler,
14
+ menuEngineering,
15
+ foodCostAnalysis,
16
+ turnTimePredictor,
17
+ buildRestaurantReceipt,
18
+ } from '../restaurantsolver';
19
+
20
+ // ─── Table Assignment ─────────────────────────────────────────────────────────
21
+
22
+ describe('tableAssignment', () => {
23
+ const tables = [
24
+ { id: 'T1', capacity: 2, section: 'patio', available: true },
25
+ { id: 'T2', capacity: 4, section: 'main', available: true },
26
+ { id: 'T3', capacity: 6, section: 'main', available: true },
27
+ { id: 'T4', capacity: 8, section: 'bar', available: true },
28
+ ];
29
+
30
+ it('party of 2 assigned to smallest fitting table (best-fit)', () => {
31
+ const parties = [{ id: 'P1', partySize: 2, priorityGuest: false }];
32
+ const r = tableAssignment(tables, parties);
33
+ const assigned = r.assignments.find(a => a.partyId === 'P1');
34
+ expect(assigned!.tableCapacity).toBeGreaterThanOrEqual(2);
35
+ // Best-fit: should assign T1 (cap=2) over T2 (cap=4)
36
+ expect(assigned!.tableCapacity).toBe(2);
37
+ });
38
+
39
+ it('priority guests seated before regular guests', () => {
40
+ const parties = [
41
+ { id: 'Regular', partySize: 4, priorityGuest: false },
42
+ { id: 'VIP', partySize: 4, priorityGuest: true },
43
+ ];
44
+ const r = tableAssignment(tables, parties);
45
+ // VIP should be assigned (both should fit since we have 2 4+ tables)
46
+ expect(r.assignments.some(a => a.partyId === 'VIP')).toBe(true);
47
+ });
48
+
49
+ it('party larger than any table goes to unassigned', () => {
50
+ const parties = [{ id: 'Huge', partySize: 20, priorityGuest: false }];
51
+ const r = tableAssignment(tables, parties);
52
+ expect(r.unassigned).toContain('Huge');
53
+ });
54
+
55
+ it('utilization = partySize / tableCapacity', () => {
56
+ const parties = [{ id: 'P1', partySize: 3, priorityGuest: false }];
57
+ const r = tableAssignment(tables, parties);
58
+ const assigned = r.assignments.find(a => a.partyId === 'P1');
59
+ expect(assigned!.utilization).toBeCloseTo(assigned!.partySize / assigned!.tableCapacity, 4);
60
+ });
61
+
62
+ it('section preference respected when available', () => {
63
+ const parties = [{ id: 'P1', partySize: 2, preferredSection: 'patio', priorityGuest: false }];
64
+ const r = tableAssignment(tables, parties);
65
+ const assigned = r.assignments.find(a => a.partyId === 'P1');
66
+ expect(assigned!.sectionMatch).toBe(true);
67
+ expect(assigned!.tableId).toBe('T1');
68
+ });
69
+
70
+ it('overallUtilization in [0, 1]', () => {
71
+ const parties = [{ id: 'P1', partySize: 2, priorityGuest: false }];
72
+ const r = tableAssignment(tables, parties);
73
+ expect(r.overallUtilization).toBeGreaterThanOrEqual(0);
74
+ expect(r.overallUtilization).toBeLessThanOrEqual(1);
75
+ });
76
+
77
+ it('throws for empty tables', () => {
78
+ expect(() => tableAssignment([], [{ id: 'P1', partySize: 2, priorityGuest: false }])).toThrow();
79
+ });
80
+ });
81
+
82
+ // ─── Kitchen Queue Scheduler ──────────────────────────────────────────────────
83
+
84
+ describe('kitchenQueueScheduler', () => {
85
+ const tickets = [
86
+ { id: 'T1', estimatedMinutes: 15, priority: 2 as const, tableId: 'A', items: ['burger'] },
87
+ { id: 'T2', estimatedMinutes: 8, priority: 1 as const, tableId: 'B', items: ['soup'] },
88
+ { id: 'T3', estimatedMinutes: 20, priority: 2 as const, tableId: 'C', items: ['steak'] },
89
+ { id: 'T4', estimatedMinutes: 5, priority: 3 as const, tableId: 'D', items: ['dessert'] },
90
+ ];
91
+
92
+ it('priority 1 ticket scheduled first', () => {
93
+ const r = kitchenQueueScheduler(tickets);
94
+ expect(r.sequence[0].ticketId).toBe('T2'); // priority 1 ticket
95
+ });
96
+
97
+ it('makespan = sum of all cook times (sequential)', () => {
98
+ const r = kitchenQueueScheduler(tickets);
99
+ const expected = tickets.reduce((s, t) => s + t.estimatedMinutes, 0);
100
+ expect(r.makespan).toBe(expected);
101
+ });
102
+
103
+ it('sequence covers all tickets', () => {
104
+ const r = kitchenQueueScheduler(tickets);
105
+ expect(r.sequence).toHaveLength(tickets.length);
106
+ });
107
+
108
+ it('each ticket starts at previous end', () => {
109
+ const r = kitchenQueueScheduler(tickets);
110
+ for (let i = 1; i < r.sequence.length; i++) {
111
+ expect(r.sequence[i].startMin).toBe(r.sequence[i - 1].endMin);
112
+ }
113
+ });
114
+
115
+ it('within same priority: shorter job goes first (SJF)', () => {
116
+ const r = kitchenQueueScheduler(tickets);
117
+ // Priority 2 tickets: T1 (15min) and T3 (20min) → T1 before T3
118
+ const t1pos = r.sequence.findIndex(s => s.ticketId === 'T1');
119
+ const t3pos = r.sequence.findIndex(s => s.ticketId === 'T3');
120
+ expect(t1pos).toBeLessThan(t3pos);
121
+ });
122
+
123
+ it('avgWaitMin ≥ 0', () => {
124
+ const r = kitchenQueueScheduler(tickets);
125
+ expect(r.avgWaitMin).toBeGreaterThanOrEqual(0);
126
+ });
127
+
128
+ it('throws for empty tickets', () => {
129
+ expect(() => kitchenQueueScheduler([])).toThrow();
130
+ });
131
+ });
132
+
133
+ // ─── Menu Engineering ─────────────────────────────────────────────────────────
134
+
135
+ describe('menuEngineering', () => {
136
+ /**
137
+ * Stars: high popularity + high margin
138
+ * Plow-horses: high popularity + low margin
139
+ * Puzzles: low popularity + high margin
140
+ * Dogs: low popularity + low margin
141
+ */
142
+ const items = [
143
+ { id: 'burger', name: 'Burger', popularity: 100, contributionMargin: 12.00 }, // star — avg margin = (12+4+25+3)/4 = 11; 12 > 11 → star
144
+ { id: 'pasta', name: 'Pasta', popularity: 80, contributionMargin: 4.00 }, // plow-horse
145
+ { id: 'lobster',name: 'Lobster', popularity: 20, contributionMargin: 25.00 }, // puzzle
146
+ { id: 'salad', name: 'Salad', popularity: 30, contributionMargin: 3.00 }, // dog
147
+ ];
148
+
149
+ it('burger (high pop, high margin) → star', () => {
150
+ const r = menuEngineering(items);
151
+ const burger = r.items.find(i => i.id === 'burger');
152
+ expect(burger!.category).toBe('star');
153
+ });
154
+
155
+ it('pasta (high pop, low margin) → plow-horse', () => {
156
+ const r = menuEngineering(items);
157
+ const pasta = r.items.find(i => i.id === 'pasta');
158
+ expect(pasta!.category).toBe('plow-horse');
159
+ });
160
+
161
+ it('lobster (low pop, high margin) → puzzle', () => {
162
+ const r = menuEngineering(items);
163
+ const lobster = r.items.find(i => i.id === 'lobster');
164
+ expect(lobster!.category).toBe('puzzle');
165
+ });
166
+
167
+ it('salad (low pop, low margin) → dog', () => {
168
+ const r = menuEngineering(items);
169
+ const salad = r.items.find(i => i.id === 'salad');
170
+ expect(salad!.category).toBe('dog');
171
+ });
172
+
173
+ it('averagePopularity = mean of item popularities', () => {
174
+ const r = menuEngineering(items);
175
+ const expected = items.reduce((s, i) => s + i.popularity, 0) / items.length;
176
+ expect(r.averagePopularity).toBeCloseTo(expected, 4);
177
+ });
178
+
179
+ it('categoryCount sums to total items', () => {
180
+ const r = menuEngineering(items);
181
+ const total = r.categoryCount.star + r.categoryCount['plow-horse'] + r.categoryCount.puzzle + r.categoryCount.dog;
182
+ expect(total).toBe(items.length);
183
+ });
184
+
185
+ it('throws for empty items', () => {
186
+ expect(() => menuEngineering([])).toThrow();
187
+ });
188
+ });
189
+
190
+ // ─── Food Cost Analysis ───────────────────────────────────────────────────────
191
+
192
+ describe('foodCostAnalysis', () => {
193
+ /**
194
+ * Burger: ingredient $3, price $12, sold 100 → food cost 25%
195
+ * Steak: ingredient $15, price $35, sold 50 → food cost 42.9%
196
+ */
197
+ const lines = [
198
+ { item: 'burger', ingredientCostUSD: 3, sellingPriceUSD: 12, unitsSold: 100 },
199
+ { item: 'steak', ingredientCostUSD: 15, sellingPriceUSD: 35, unitsSold: 50 },
200
+ ];
201
+
202
+ it('per-item foodCostPct = ingredient / price', () => {
203
+ const r = foodCostAnalysis(lines);
204
+ expect(r.lines[0].foodCostPct).toBeCloseTo(3 / 12, 4);
205
+ expect(r.lines[1].foodCostPct).toBeCloseTo(15 / 35, 4);
206
+ });
207
+
208
+ it('totalRevenue = sum of price × units', () => {
209
+ const r = foodCostAnalysis(lines);
210
+ const expected = 12 * 100 + 35 * 50;
211
+ expect(r.totalRevenue).toBeCloseTo(expected, 2);
212
+ });
213
+
214
+ it('blendedFoodCostPct = totalCost / totalRevenue', () => {
215
+ const r = foodCostAnalysis(lines);
216
+ expect(r.blendedFoodCostPct).toBeCloseTo(r.totalCost / r.totalRevenue, 4);
217
+ });
218
+
219
+ it('overTarget=true when blended cost exceeds target', () => {
220
+ // Steak-heavy menu at 42.9% → over standard 30% target
221
+ const heavySteak = [{ item: 'steak', ingredientCostUSD: 15, sellingPriceUSD: 35, unitsSold: 200 }];
222
+ const r = foodCostAnalysis(heavySteak, 0.30);
223
+ expect(r.overTarget).toBe(true);
224
+ });
225
+
226
+ it('overTarget=false when within target', () => {
227
+ const lowCost = [{ item: 'drink', ingredientCostUSD: 1, sellingPriceUSD: 8, unitsSold: 100 }];
228
+ const r = foodCostAnalysis(lowCost, 0.30);
229
+ expect(r.overTarget).toBe(false);
230
+ });
231
+
232
+ it('throws for empty lines', () => {
233
+ expect(() => foodCostAnalysis([])).toThrow();
234
+ });
235
+ });
236
+
237
+ // ─── Turn Time Predictor ──────────────────────────────────────────────────────
238
+
239
+ describe('turnTimePredictor', () => {
240
+ it('dinner base is longer than lunch', () => {
241
+ const lunch = turnTimePredictor({ partySize: 2, mealPeriod: 'lunch', specialEvent: false });
242
+ const dinner = turnTimePredictor({ partySize: 2, mealPeriod: 'dinner', specialEvent: false });
243
+ expect(dinner.predictedTurnMin).toBeGreaterThan(lunch.predictedTurnMin);
244
+ });
245
+
246
+ it('special event adds to turn time', () => {
247
+ const normal = turnTimePredictor({ partySize: 2, mealPeriod: 'dinner', specialEvent: false });
248
+ const special = turnTimePredictor({ partySize: 2, mealPeriod: 'dinner', specialEvent: true });
249
+ expect(special.predictedTurnMin).toBeGreaterThan(normal.predictedTurnMin);
250
+ });
251
+
252
+ it('larger party → longer turn time', () => {
253
+ const small = turnTimePredictor({ partySize: 2, mealPeriod: 'dinner', specialEvent: false });
254
+ const large = turnTimePredictor({ partySize: 8, mealPeriod: 'dinner', specialEvent: false });
255
+ expect(large.predictedTurnMin).toBeGreaterThan(small.predictedTurnMin);
256
+ });
257
+
258
+ it('turnsPerEvening = 480 / predictedTurnMin', () => {
259
+ const r = turnTimePredictor({ partySize: 4, mealPeriod: 'dinner', specialEvent: false });
260
+ expect(r.turnsPerEvening).toBeCloseTo(480 / r.predictedTurnMin, 4);
261
+ });
262
+
263
+ it('confidenceInterval spans ±10% of predictedTurnMin', () => {
264
+ const r = turnTimePredictor({ partySize: 4, mealPeriod: 'dinner', specialEvent: false });
265
+ const margin = r.predictedTurnMin * 0.10;
266
+ expect(r.confidenceInterval[0]).toBeCloseTo(r.predictedTurnMin - margin, 1);
267
+ expect(r.confidenceInterval[1]).toBeCloseTo(r.predictedTurnMin + margin, 1);
268
+ });
269
+
270
+ it('throws for partySize < 1', () => {
271
+ expect(() => turnTimePredictor({ partySize: 0, mealPeriod: 'dinner', specialEvent: false })).toThrow();
272
+ });
273
+ });
274
+
275
+ // ─── Receipt ─────────────────────────────────────────────────────────────────
276
+
277
+ describe('buildRestaurantReceipt', () => {
278
+ it('plugin=restaurant and CAEL event correct', () => {
279
+ const menu = menuEngineering([{ id: 'burger', name: 'Burger', popularity: 100, contributionMargin: 8 }]);
280
+ const receipt = buildRestaurantReceipt({ menuEngineering: menu, converged: true });
281
+ expect(receipt.plugin).toBe('restaurant');
282
+ expect(receipt.cael.event).toBe('restaurant.operations_analysis');
283
+ expect(receipt.payloadHash).toBeTruthy();
284
+ });
285
+
286
+ it('accepted=true for efficient operation', () => {
287
+ const foodCost = foodCostAnalysis([{ item: 'drink', ingredientCostUSD: 1, sellingPriceUSD: 8, unitsSold: 100 }]);
288
+ const receipt = buildRestaurantReceipt({ foodCost, converged: true });
289
+ expect(receipt.acceptance.accepted).toBe(true);
290
+ });
291
+
292
+ it('accepted=false when food cost over target', () => {
293
+ const foodCost = foodCostAnalysis(
294
+ [{ item: 'steak', ingredientCostUSD: 15, sellingPriceUSD: 35, unitsSold: 100 }],
295
+ 0.30, // 42.9% actual > 30% target
296
+ );
297
+ const receipt = buildRestaurantReceipt({ foodCost, converged: true });
298
+ expect(receipt.acceptance.accepted).toBe(false);
299
+ expect(receipt.acceptance.violations.length).toBeGreaterThan(0);
300
+ });
301
+
302
+ it('accepted=false when parties unassigned', () => {
303
+ const tables = [{ id: 'T1', capacity: 2, section: 'main', available: true }];
304
+ const parties = [{ id: 'Huge', partySize: 20, priorityGuest: false }];
305
+ const tableAssign = tableAssignment(tables, parties);
306
+ const receipt = buildRestaurantReceipt({ tableAssign, converged: true });
307
+ expect(receipt.acceptance.accepted).toBe(false);
308
+ });
309
+
310
+ it('uses provided runId', () => {
311
+ const receipt = buildRestaurantReceipt({ converged: true }, { runId: 'rst-run-007' });
312
+ expect(receipt.runId).toBe('rst-run-007');
313
+ });
314
+ });
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export * from './restaurantsolver';
2
+ export { createMenuHandler, type MenuConfig, type MenuItem } from './traits/MenuTrait';
3
+ export { createOrderHandler, type OrderConfig, type OrderItem, type OrderStatus } from './traits/OrderTrait';
4
+ export { createKitchenDisplayHandler, type KitchenDisplayConfig, type KitchenTicket } from './traits/KitchenDisplayTrait';
5
+ export { createTableManagementHandler, type TableManagementConfig, type Table, type TableStatus } from './traits/TableManagementTrait';
6
+ export * from './traits/types';
7
+
8
+ import { createMenuHandler } from './traits/MenuTrait';
9
+ import { createOrderHandler } from './traits/OrderTrait';
10
+ import { createKitchenDisplayHandler } from './traits/KitchenDisplayTrait';
11
+ import { createTableManagementHandler } from './traits/TableManagementTrait';
12
+
13
+ export const pluginMeta = { name: '@holoscript/plugin-restaurant', version: '1.0.0', traits: ['menu', 'order', 'kitchen_display', 'table_management'] };
14
+ export const traitHandlers = [createMenuHandler(), createOrderHandler(), createKitchenDisplayHandler(), createTableManagementHandler()];
@@ -0,0 +1,350 @@
1
+ /**
2
+ * Restaurant operations solvers — restaurant-plugin
3
+ *
4
+ * Implements:
5
+ * - Table assignment optimizer (bin-packing / best-fit-decreasing)
6
+ * - Kitchen queue scheduler (Shortest Job First + priority)
7
+ * - Menu engineering matrix (Star/Plow-horse/Puzzle/Dog — Kasavana & Smith 1982)
8
+ * - Food cost optimizer (target cost % → price calculation)
9
+ * - Turn time predictor (regression on party size + meal period)
10
+ * - Seating utilization metrics
11
+ *
12
+ * References:
13
+ * - Kasavana M, Smith D (1982) Menu Engineering. Hospitality Publications.
14
+ * - Siguaw J, Enz C (1999) Cornell Hotel and Restaurant Admin. Quarterly 40(6).
15
+ * - National Restaurant Association — FoodCost % standard 28-32%
16
+ */
17
+
18
+ import { buildDomainSimulationReceipt, type DomainSimulationReceipt } from '@holoscript/core';
19
+
20
+ // ─── Types ────────────────────────────────────────────────────────────────────
21
+
22
+ export interface RestaurantTable {
23
+ id: string;
24
+ capacity: number;
25
+ section: string;
26
+ available: boolean;
27
+ }
28
+
29
+ export interface PartyRequest {
30
+ id: string;
31
+ partySize: number;
32
+ preferredSection?: string;
33
+ priorityGuest: boolean;
34
+ }
35
+
36
+ export interface TableAssignmentResult {
37
+ assignments: Array<{
38
+ partyId: string;
39
+ tableId: string;
40
+ tableCapacity: number;
41
+ partySize: number;
42
+ utilization: number;
43
+ sectionMatch: boolean;
44
+ }>;
45
+ unassigned: string[];
46
+ overallUtilization: number;
47
+ }
48
+
49
+ export interface KitchenTicket {
50
+ id: string;
51
+ /** Estimated cook time minutes */
52
+ estimatedMinutes: number;
53
+ /** 1=fire immediately (rush), 2=normal, 3=can-wait */
54
+ priority: 1 | 2 | 3;
55
+ /** Table/order id */
56
+ tableId: string;
57
+ items: string[];
58
+ }
59
+
60
+ export interface KitchenQueueResult {
61
+ sequence: Array<{
62
+ ticketId: string;
63
+ startMin: number;
64
+ endMin: number;
65
+ tableId: string;
66
+ }>;
67
+ makespan: number; // total completion time minutes
68
+ avgWaitMin: number;
69
+ avgFlowMin: number;
70
+ }
71
+
72
+ export interface MenuItem {
73
+ id: string;
74
+ name: string;
75
+ /** Average monthly units sold */
76
+ popularity: number;
77
+ /** Contribution margin = price − variable cost */
78
+ contributionMargin: number;
79
+ }
80
+
81
+ export type MenuCategory = 'star' | 'plow-horse' | 'puzzle' | 'dog';
82
+
83
+ export interface MenuEngineeringResult {
84
+ items: Array<{
85
+ id: string;
86
+ name: string;
87
+ popularity: number;
88
+ contributionMargin: number;
89
+ popularityIndex: number; // vs average popularity
90
+ marginIndex: number; // vs average margin
91
+ category: MenuCategory;
92
+ }>;
93
+ averagePopularity: number;
94
+ averageMargin: number;
95
+ categoryCount: Record<MenuCategory, number>;
96
+ }
97
+
98
+ export interface FoodCostLine {
99
+ item: string;
100
+ ingredientCostUSD: number;
101
+ sellingPriceUSD: number;
102
+ unitsSold: number;
103
+ }
104
+
105
+ export interface FoodCostResult {
106
+ lines: Array<{
107
+ item: string;
108
+ ingredientCostUSD: number;
109
+ sellingPriceUSD: number;
110
+ unitsSold: number;
111
+ foodCostPct: number;
112
+ revenueUSD: number;
113
+ costUSD: number;
114
+ grossProfitUSD: number;
115
+ }>;
116
+ totalRevenue: number;
117
+ totalCost: number;
118
+ blendedFoodCostPct: number;
119
+ targetFoodCostPct: number;
120
+ variance: number;
121
+ overTarget: boolean;
122
+ }
123
+
124
+ export interface RestaurantReceiptOptions {
125
+ runId?: string;
126
+ }
127
+
128
+ // ─── Table Assignment (Best-Fit-Decreasing bin-packing) ───────────────────────
129
+
130
+ /**
131
+ * Assign parties to tables using best-fit strategy:
132
+ * priority guests first, then largest parties first,
133
+ * assign to smallest available table that fits.
134
+ */
135
+ export function tableAssignment(
136
+ tables: RestaurantTable[],
137
+ parties: PartyRequest[],
138
+ ): TableAssignmentResult {
139
+ if (tables.length === 0) throw new Error('No tables available');
140
+ if (parties.length === 0) throw new Error('No parties to seat');
141
+
142
+ const available = tables.map(t => ({ ...t }));
143
+ const sorted = [...parties].sort((a, b) => {
144
+ // Priority guests first, then by descending party size
145
+ if (a.priorityGuest !== b.priorityGuest) return a.priorityGuest ? -1 : 1;
146
+ return b.partySize - a.partySize;
147
+ });
148
+
149
+ const assignments: TableAssignmentResult['assignments'] = [];
150
+ const unassigned: string[] = [];
151
+
152
+ for (const party of sorted) {
153
+ // Best-fit: find smallest available table that fits
154
+ const candidates = available.filter(t => t.available && t.capacity >= party.partySize);
155
+ if (candidates.length === 0) { unassigned.push(party.id); continue; }
156
+
157
+ // Prefer preferred section, then smallest-capacity table
158
+ const sectionMatch = candidates.filter(t => !party.preferredSection || t.section === party.preferredSection);
159
+ const pool = sectionMatch.length > 0 ? sectionMatch : candidates;
160
+ pool.sort((a, b) => a.capacity - b.capacity);
161
+ const table = pool[0];
162
+
163
+ table.available = false;
164
+ assignments.push({
165
+ partyId: party.id,
166
+ tableId: table.id,
167
+ tableCapacity: table.capacity,
168
+ partySize: party.partySize,
169
+ utilization: party.partySize / table.capacity,
170
+ sectionMatch: !party.preferredSection || table.section === party.preferredSection,
171
+ });
172
+ }
173
+
174
+ const seatedSeats = assignments.reduce((a, x) => a + x.partySize, 0);
175
+ const totalSeats = tables.reduce((a, t) => a + t.capacity, 0);
176
+
177
+ return { assignments, unassigned, overallUtilization: totalSeats > 0 ? seatedSeats / totalSeats : 0 };
178
+ }
179
+
180
+ // ─── Kitchen Queue (SJF with priority) ───────────────────────────────────────
181
+
182
+ /**
183
+ * Schedule kitchen tickets using priority-ordered SJF.
184
+ * Priority 1 always goes first, then within each priority level: shortest job.
185
+ */
186
+ export function kitchenQueueScheduler(tickets: KitchenTicket[]): KitchenQueueResult {
187
+ if (tickets.length === 0) throw new Error('No kitchen tickets');
188
+
189
+ // Sort: priority level first, then shortest cook time
190
+ const sorted = [...tickets].sort((a, b) =>
191
+ a.priority !== b.priority ? a.priority - b.priority : a.estimatedMinutes - b.estimatedMinutes,
192
+ );
193
+
194
+ const sequence: KitchenQueueResult['sequence'] = [];
195
+ let time = 0;
196
+ let totalWait = 0, totalFlow = 0;
197
+
198
+ for (const ticket of sorted) {
199
+ const start = time;
200
+ const end = time + ticket.estimatedMinutes;
201
+ sequence.push({ ticketId: ticket.id, startMin: start, endMin: end, tableId: ticket.tableId });
202
+ totalWait += start;
203
+ totalFlow += end;
204
+ time = end;
205
+ }
206
+
207
+ return {
208
+ sequence,
209
+ makespan: time,
210
+ avgWaitMin: totalWait / tickets.length,
211
+ avgFlowMin: totalFlow / tickets.length,
212
+ };
213
+ }
214
+
215
+ // ─── Menu Engineering Matrix ──────────────────────────────────────────────────
216
+
217
+ /**
218
+ * Kasavana & Smith (1982) Menu Engineering:
219
+ * - Star: high popularity, high margin
220
+ * - Plow-horse: high popularity, low margin
221
+ * - Puzzle: low popularity, high margin
222
+ * - Dog: low popularity, low margin
223
+ */
224
+ export function menuEngineering(items: MenuItem[]): MenuEngineeringResult {
225
+ if (items.length === 0) throw new Error('No menu items');
226
+
227
+ const avgPopularity = items.reduce((s, i) => s + i.popularity, 0) / items.length;
228
+ const avgMargin = items.reduce((s, i) => s + i.contributionMargin, 0) / items.length;
229
+
230
+ const analyzed = items.map(item => {
231
+ const popularityIndex = item.popularity / avgPopularity;
232
+ const marginIndex = item.contributionMargin / avgMargin;
233
+ const category: MenuCategory =
234
+ popularityIndex >= 1 && marginIndex >= 1 ? 'star' :
235
+ popularityIndex >= 1 && marginIndex < 1 ? 'plow-horse' :
236
+ popularityIndex < 1 && marginIndex >= 1 ? 'puzzle' : 'dog';
237
+ return { id: item.id, name: item.name, popularity: item.popularity, contributionMargin: item.contributionMargin, popularityIndex, marginIndex, category };
238
+ });
239
+
240
+ const categoryCount: Record<MenuCategory, number> = { star: 0, 'plow-horse': 0, puzzle: 0, dog: 0 };
241
+ for (const a of analyzed) categoryCount[a.category]++;
242
+
243
+ return { items: analyzed, averagePopularity: avgPopularity, averageMargin: avgMargin, categoryCount };
244
+ }
245
+
246
+ // ─── Food Cost Optimizer ──────────────────────────────────────────────────────
247
+
248
+ export function foodCostAnalysis(
249
+ lines: FoodCostLine[],
250
+ targetFoodCostPct = 0.30,
251
+ ): FoodCostResult {
252
+ if (lines.length === 0) throw new Error('No food cost lines');
253
+ if (targetFoodCostPct <= 0 || targetFoodCostPct >= 1) throw new Error('targetFoodCostPct must be in (0,1)');
254
+
255
+ const analyzed = lines.map(l => {
256
+ const revenueUSD = l.sellingPriceUSD * l.unitsSold;
257
+ const costUSD = l.ingredientCostUSD * l.unitsSold;
258
+ const grossProfitUSD = revenueUSD - costUSD;
259
+ const foodCostPct = l.sellingPriceUSD > 0 ? l.ingredientCostUSD / l.sellingPriceUSD : 0;
260
+ return { ...l, foodCostPct, revenueUSD, costUSD, grossProfitUSD };
261
+ });
262
+
263
+ const totalRevenue = analyzed.reduce((s, l) => s + l.revenueUSD, 0);
264
+ const totalCost = analyzed.reduce((s, l) => s + l.costUSD, 0);
265
+ const blendedFoodCostPct = totalRevenue > 0 ? totalCost / totalRevenue : 0;
266
+ const variance = blendedFoodCostPct - targetFoodCostPct;
267
+
268
+ return { lines: analyzed, totalRevenue, totalCost, blendedFoodCostPct, targetFoodCostPct, variance, overTarget: variance > 0 };
269
+ }
270
+
271
+ // ─── Turn Time Predictor ──────────────────────────────────────────────────────
272
+
273
+ export interface TurnTimePredictorInput {
274
+ partySize: number;
275
+ /** 'lunch' | 'dinner' | 'brunch' */
276
+ mealPeriod: 'lunch' | 'dinner' | 'brunch';
277
+ /** Is the party a special event (birthday, anniversary)? */
278
+ specialEvent: boolean;
279
+ }
280
+
281
+ export interface TurnTimeResult {
282
+ /** Predicted table turn time in minutes */
283
+ predictedTurnMin: number;
284
+ /** Tables turned per evening (8hr dinner service) */
285
+ turnsPerEvening: number;
286
+ /** 95% confidence interval [low, high] minutes */
287
+ confidenceInterval: [number, number];
288
+ }
289
+
290
+ /**
291
+ * Linear regression model for turn time:
292
+ * base = (lunch=45, dinner=75, brunch=55) + 5×partySize + 15×specialEvent
293
+ */
294
+ export function turnTimePredictor(input: TurnTimePredictorInput): TurnTimeResult {
295
+ if (input.partySize < 1) throw new Error('partySize must be ≥ 1');
296
+
297
+ const periodBase = input.mealPeriod === 'lunch' ? 45 : input.mealPeriod === 'brunch' ? 55 : 75;
298
+ const predictedTurnMin = periodBase + 5 * input.partySize + (input.specialEvent ? 15 : 0);
299
+ const turnsPerEvening = 480 / predictedTurnMin; // 8hr service / turn time
300
+
301
+ // ±10% CI (simplified residual from regression)
302
+ const margin = predictedTurnMin * 0.10;
303
+ const confidenceInterval: [number, number] = [predictedTurnMin - margin, predictedTurnMin + margin];
304
+
305
+ return { predictedTurnMin, turnsPerEvening, confidenceInterval };
306
+ }
307
+
308
+ // ─── Receipt ──────────────────────────────────────────────────────────────────
309
+
310
+ export interface RestaurantAnalysisResult {
311
+ tableAssign?: TableAssignmentResult;
312
+ queue?: KitchenQueueResult;
313
+ menuEngineering?: MenuEngineeringResult;
314
+ foodCost?: FoodCostResult;
315
+ turnTime?: TurnTimeResult;
316
+ converged: true;
317
+ }
318
+
319
+ export function buildRestaurantReceipt(
320
+ result: RestaurantAnalysisResult,
321
+ options?: RestaurantReceiptOptions,
322
+ ): DomainSimulationReceipt {
323
+ const violations: Array<{ criterion: string; message: string }> = [];
324
+
325
+ if (result.tableAssign && result.tableAssign.unassigned.length > 0) {
326
+ violations.push({ criterion: 'unseated_parties', message: `${result.tableAssign.unassigned.length} party/parties could not be seated` });
327
+ }
328
+ if (result.foodCost?.overTarget) {
329
+ violations.push({ criterion: 'food_cost', message: `Blended food cost ${(result.foodCost.blendedFoodCostPct * 100).toFixed(1)}% exceeds ${(result.foodCost.targetFoodCostPct * 100).toFixed(0)}% target` });
330
+ }
331
+ if (result.queue && result.queue.makespan > 60) {
332
+ violations.push({ criterion: 'kitchen_throughput', message: `Kitchen makespan ${result.queue.makespan.toFixed(0)} min exceeds 60 min service standard` });
333
+ }
334
+
335
+ return buildDomainSimulationReceipt({
336
+ plugin: 'restaurant',
337
+ pluginVersion: '1.0.0',
338
+ runId: options?.runId ?? `rst-${Date.now().toString(36)}`,
339
+ solverConfig: { solverType: 'restaurant-operations', scale: 'shift' },
340
+ resultSummary: {
341
+ seatingUtilization: result.tableAssign?.overallUtilization ?? null,
342
+ unseatatedParties: result.tableAssign?.unassigned.length ?? null,
343
+ kitchenMakespan: result.queue?.makespan ?? null,
344
+ blendedFoodCostPct: result.foodCost?.blendedFoodCostPct ?? null,
345
+ menuStarCount: result.menuEngineering?.categoryCount.star ?? null,
346
+ },
347
+ cael: { version: 'cael.v1', event: 'restaurant.operations_analysis', solverType: 'restaurant.table-assignment' },
348
+ acceptance: { accepted: violations.length === 0, violations },
349
+ });
350
+ }
@@ -0,0 +1,33 @@
1
+ /** @kitchen_display Trait — Kitchen display system (KDS). @trait kitchen_display */
2
+ import type { TraitHandler, HSPlusNode, TraitContext, TraitEvent } from './types';
3
+
4
+ export interface KitchenTicket { orderId: string; items: string[]; priority: 'normal' | 'rush' | 'vip'; receivedAt: number; startedAt: number | null; completedAt: number | null; }
5
+ export interface KitchenDisplayConfig { stations: string[]; maxActiveTickets: number; targetPrepTimeMin: number; }
6
+ export interface KitchenDisplayState { activeTickets: KitchenTicket[]; completedToday: number; avgPrepTimeMin: number; }
7
+
8
+ const defaultConfig: KitchenDisplayConfig = { stations: ['grill', 'salad', 'dessert'], maxActiveTickets: 20, targetPrepTimeMin: 15 };
9
+
10
+ export function createKitchenDisplayHandler(): TraitHandler<KitchenDisplayConfig> {
11
+ return { name: 'kitchen_display', defaultConfig,
12
+ onAttach(n: HSPlusNode, _c: KitchenDisplayConfig, ctx: TraitContext) { n.__kdsState = { activeTickets: [], completedToday: 0, avgPrepTimeMin: 0 }; ctx.emit?.('kds:online'); },
13
+ onDetach(n: HSPlusNode, _c: KitchenDisplayConfig, ctx: TraitContext) { delete n.__kdsState; ctx.emit?.('kds:offline'); },
14
+ onUpdate() {},
15
+ onEvent(n: HSPlusNode, c: KitchenDisplayConfig, ctx: TraitContext, e: TraitEvent) {
16
+ const s = n.__kdsState as KitchenDisplayState | undefined; if (!s) return;
17
+ if (e.type === 'kds:new_ticket') {
18
+ const ticket: KitchenTicket = { orderId: (e.payload?.orderId as string) ?? '', items: (e.payload?.items as string[]) ?? [], priority: (e.payload?.priority as KitchenTicket['priority']) ?? 'normal', receivedAt: Date.now(), startedAt: null, completedAt: null };
19
+ if (s.activeTickets.length < c.maxActiveTickets) { s.activeTickets.push(ticket); ctx.emit?.('kds:ticket_received', { orderId: ticket.orderId }); }
20
+ else ctx.emit?.('kds:queue_full');
21
+ }
22
+ if (e.type === 'kds:complete_ticket') {
23
+ const idx = s.activeTickets.findIndex(t => t.orderId === (e.payload?.orderId as string));
24
+ if (idx >= 0) { const t = s.activeTickets.splice(idx, 1)[0]; t.completedAt = Date.now(); s.completedToday++;
25
+ const prepTime = (t.completedAt - t.receivedAt) / 60000;
26
+ s.avgPrepTimeMin = (s.avgPrepTimeMin * (s.completedToday - 1) + prepTime) / s.completedToday;
27
+ ctx.emit?.('kds:ticket_done', { orderId: t.orderId, prepMin: Math.round(prepTime) });
28
+ if (prepTime > c.targetPrepTimeMin) ctx.emit?.('kds:slow_ticket', { orderId: t.orderId, prepMin: Math.round(prepTime) });
29
+ }
30
+ }
31
+ },
32
+ };
33
+ }
@@ -0,0 +1,19 @@
1
+ /** @menu Trait — Restaurant menu management. @trait menu */
2
+ import type { TraitHandler, HSPlusNode, TraitContext, TraitEvent } from './types';
3
+
4
+ export interface MenuItem { id: string; name: string; price: number; category: string; description: string; allergens: string[]; calories?: number; available: boolean; }
5
+ export interface MenuConfig { items: MenuItem[]; currency: string; taxRate: number; serviceChargePercent: number; }
6
+
7
+ const defaultConfig: MenuConfig = { items: [], currency: 'USD', taxRate: 0.08, serviceChargePercent: 0 };
8
+
9
+ export function createMenuHandler(): TraitHandler<MenuConfig> {
10
+ return { name: 'menu', defaultConfig,
11
+ onAttach(n: HSPlusNode, c: MenuConfig, ctx: TraitContext) { n.__menuState = { availableItems: c.items.filter(i => i.available).length, categories: [...new Set(c.items.map(i => i.category))] }; ctx.emit?.('menu:loaded', { items: c.items.length }); },
12
+ onDetach(n: HSPlusNode, _c: MenuConfig, ctx: TraitContext) { delete n.__menuState; ctx.emit?.('menu:unloaded'); },
13
+ onUpdate() {},
14
+ onEvent(_n: HSPlusNode, c: MenuConfig, ctx: TraitContext, e: TraitEvent) {
15
+ if (e.type === 'menu:search') { const q = ((e.payload?.query as string) ?? '').toLowerCase(); const results = c.items.filter(i => i.available && (i.name.toLowerCase().includes(q) || i.category.toLowerCase().includes(q))); ctx.emit?.('menu:results', { count: results.length, items: results.map(r => ({ id: r.id, name: r.name, price: r.price })) }); }
16
+ if (e.type === 'menu:toggle_availability') { const item = c.items.find(i => i.id === (e.payload?.itemId as string)); if (item) { item.available = !item.available; ctx.emit?.('menu:availability_changed', { item: item.name, available: item.available }); } }
17
+ },
18
+ };
19
+ }
@@ -0,0 +1,27 @@
1
+ /** @order Trait — Customer order lifecycle. @trait order */
2
+ import type { TraitHandler, HSPlusNode, TraitContext, TraitEvent } from './types';
3
+
4
+ export type OrderStatus = 'new' | 'confirmed' | 'preparing' | 'ready' | 'served' | 'paid' | 'cancelled';
5
+ export interface OrderItem { menuItemId: string; name: string; quantity: number; price: number; modifications?: string[]; }
6
+ export interface OrderConfig { tableNumber: number; items: OrderItem[]; orderType: 'dine_in' | 'takeout' | 'delivery'; }
7
+ export interface OrderState { status: OrderStatus; orderId: string; subtotal: number; createdAt: number; }
8
+
9
+ const defaultConfig: OrderConfig = { tableNumber: 0, items: [], orderType: 'dine_in' };
10
+
11
+ export function createOrderHandler(): TraitHandler<OrderConfig> {
12
+ return { name: 'order', defaultConfig,
13
+ onAttach(n: HSPlusNode, c: OrderConfig, ctx: TraitContext) {
14
+ const subtotal = c.items.reduce((s, i) => s + i.price * i.quantity, 0);
15
+ n.__orderState = { status: 'new' as OrderStatus, orderId: `ORD-${Date.now()}`, subtotal, createdAt: Date.now() };
16
+ ctx.emit?.('order:created', { table: c.tableNumber, items: c.items.length, subtotal });
17
+ },
18
+ onDetach(n: HSPlusNode, _c: OrderConfig, ctx: TraitContext) { delete n.__orderState; ctx.emit?.('order:removed'); },
19
+ onUpdate() {},
20
+ onEvent(n: HSPlusNode, _c: OrderConfig, ctx: TraitContext, e: TraitEvent) {
21
+ const s = n.__orderState as OrderState | undefined; if (!s) return;
22
+ const flow: OrderStatus[] = ['new','confirmed','preparing','ready','served','paid'];
23
+ if (e.type === 'order:advance') { const i = flow.indexOf(s.status); if (i < flow.length - 1) { s.status = flow[i+1]; ctx.emit?.('order:status_changed', { status: s.status, orderId: s.orderId }); } }
24
+ if (e.type === 'order:cancel') { s.status = 'cancelled'; ctx.emit?.('order:cancelled', { orderId: s.orderId }); }
25
+ },
26
+ };
27
+ }
@@ -0,0 +1,35 @@
1
+ /** @table_management Trait — Restaurant table/seating management. @trait table_management */
2
+ import type { TraitHandler, HSPlusNode, TraitContext, TraitEvent } from './types';
3
+
4
+ export type TableStatus = 'available' | 'reserved' | 'occupied' | 'cleaning' | 'blocked';
5
+ export interface Table { id: string; seats: number; section: string; status: TableStatus; partySize?: number; seatedAt?: number; }
6
+ export interface TableManagementConfig { tables: Table[]; turnoverTargetMin: number; waitlistEnabled: boolean; }
7
+ export interface TableManagementState { availableCount: number; occupiedCount: number; waitlistSize: number; avgTurnoverMin: number; }
8
+
9
+ const defaultConfig: TableManagementConfig = { tables: [], turnoverTargetMin: 60, waitlistEnabled: true };
10
+
11
+ export function createTableManagementHandler(): TraitHandler<TableManagementConfig> {
12
+ return { name: 'table_management', defaultConfig,
13
+ onAttach(n: HSPlusNode, c: TableManagementConfig, ctx: TraitContext) {
14
+ const avail = c.tables.filter(t => t.status === 'available').length;
15
+ n.__tableState = { availableCount: avail, occupiedCount: c.tables.length - avail, waitlistSize: 0, avgTurnoverMin: 0 };
16
+ ctx.emit?.('tables:initialized', { total: c.tables.length, available: avail });
17
+ },
18
+ onDetach(n: HSPlusNode, _c: TableManagementConfig, ctx: TraitContext) { delete n.__tableState; ctx.emit?.('tables:closed'); },
19
+ onUpdate() {},
20
+ onEvent(n: HSPlusNode, c: TableManagementConfig, ctx: TraitContext, e: TraitEvent) {
21
+ const s = n.__tableState as TableManagementState | undefined; if (!s) return;
22
+ if (e.type === 'tables:seat') {
23
+ const tableId = e.payload?.tableId as string; const party = (e.payload?.partySize as number) ?? 1;
24
+ const table = c.tables.find(t => t.id === tableId);
25
+ if (table && table.status === 'available') { table.status = 'occupied'; table.partySize = party; table.seatedAt = Date.now(); s.availableCount--; s.occupiedCount++; ctx.emit?.('tables:seated', { table: tableId, party }); }
26
+ }
27
+ if (e.type === 'tables:clear') {
28
+ const tableId = e.payload?.tableId as string;
29
+ const table = c.tables.find(t => t.id === tableId);
30
+ if (table && table.status === 'occupied') { table.status = 'available'; s.availableCount++; s.occupiedCount--; ctx.emit?.('tables:cleared', { table: tableId }); }
31
+ }
32
+ if (e.type === 'tables:add_waitlist') { s.waitlistSize++; ctx.emit?.('tables:waitlist_updated', { size: s.waitlistSize }); }
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,4 @@
1
+ export interface HSPlusNode { id?: string; properties?: Record<string, unknown>; [key: string]: unknown; }
2
+ export interface TraitContext { emit?: (event: string, payload?: unknown) => void; [key: string]: unknown; }
3
+ export interface TraitEvent { type: string; payload?: Record<string, unknown>; [key: string]: unknown; }
4
+ export interface TraitHandler<T = unknown> { name: string; defaultConfig: T; onAttach(n: HSPlusNode, c: T, ctx: TraitContext): void; onDetach(n: HSPlusNode, c: T, ctx: TraitContext): void; onUpdate(n: HSPlusNode, c: T, ctx: TraitContext, d: number): void; onEvent(n: HSPlusNode, c: T, ctx: TraitContext, e: TraitEvent): void; }
package/tsconfig.json ADDED
@@ -0,0 +1 @@
1
+ { "extends": "../../../tsconfig.json", "compilerOptions": { "outDir": "dist", "rootDir": "src", "declaration": true }, "include": ["src"] }
@@ -0,0 +1,10 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ include: ['src/**/*.test.ts'],
8
+ passWithNoTests: true,
9
+ },
10
+ });