spms 1.2.1__py3-none-any.whl

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.
Files changed (89) hide show
  1. app_core/__init__.py +1 -0
  2. app_core/assistant/__init__.py +70 -0
  3. app_core/assistant/action_validation.py +970 -0
  4. app_core/assistant/actions.py +473 -0
  5. app_core/assistant/common.py +265 -0
  6. app_core/assistant/engine.py +571 -0
  7. app_core/assistant/feedback.py +175 -0
  8. app_core/assistant/formatting.py +1299 -0
  9. app_core/assistant/nlu.py +186 -0
  10. app_core/assistant/runtime.py +387 -0
  11. app_core/assistant/tools.py +1154 -0
  12. app_core/barcodes.py +248 -0
  13. app_core/db.py +1540 -0
  14. app_core/doctor.py +686 -0
  15. app_core/domain/__init__.py +10 -0
  16. app_core/domain/availability.py +64 -0
  17. app_core/domain/dates.py +162 -0
  18. app_core/domain/metrics.py +119 -0
  19. app_core/domain/money.py +106 -0
  20. app_core/domain/tax.py +66 -0
  21. app_core/paths.py +223 -0
  22. app_core/services/__init__.py +36 -0
  23. app_core/services/_monolith.py +7846 -0
  24. app_core/services/_seed_data.py +214 -0
  25. app_core/services/billing_docs.py +245 -0
  26. app_core/services/reports_metrics.py +180 -0
  27. app_core/support.py +389 -0
  28. app_core/updater.py +478 -0
  29. spms-1.2.1.dist-info/METADATA +298 -0
  30. spms-1.2.1.dist-info/RECORD +89 -0
  31. spms-1.2.1.dist-info/WHEEL +5 -0
  32. spms-1.2.1.dist-info/entry_points.txt +3 -0
  33. spms-1.2.1.dist-info/licenses/LICENSE +14 -0
  34. spms-1.2.1.dist-info/top_level.txt +4 -0
  35. ui/__init__.py +1 -0
  36. ui/web/__init__.py +1 -0
  37. ui/web/deps.py +614 -0
  38. ui/web/rendering.py +81 -0
  39. ui/web/route_utils.py +48 -0
  40. ui/web/routes/__init__.py +1 -0
  41. ui/web/routes/accounting.py +168 -0
  42. ui/web/routes/assistant.py +585 -0
  43. ui/web/routes/dashboard.py +33 -0
  44. ui/web/routes/files.py +28 -0
  45. ui/web/routes/guests.py +115 -0
  46. ui/web/routes/housekeeping.py +158 -0
  47. ui/web/routes/pos_inventory.py +492 -0
  48. ui/web/routes/reports_analytics.py +80 -0
  49. ui/web/routes/reservations.py +628 -0
  50. ui/web/routes/settings_branding.py +910 -0
  51. ui/web/routes/support.py +55 -0
  52. ui/web/server.py +273 -0
  53. ui/web/static/app.css +142 -0
  54. ui/web/static/app.js +80 -0
  55. ui/web/static/assistant_widget.js +284 -0
  56. ui/web/static/icons/apple-touch-icon.png +0 -0
  57. ui/web/static/icons/icon-192.png +0 -0
  58. ui/web/static/icons/icon-512.png +0 -0
  59. ui/web/static/manifest.webmanifest +25 -0
  60. ui/web/static/sw.js +63 -0
  61. ui/web/templates/accounting/index.html +163 -0
  62. ui/web/templates/assistant/_messages.html +102 -0
  63. ui/web/templates/assistant/index.html +80 -0
  64. ui/web/templates/base.html +94 -0
  65. ui/web/templates/dashboard.html +95 -0
  66. ui/web/templates/errors/500.html +29 -0
  67. ui/web/templates/guests/detail.html +132 -0
  68. ui/web/templates/guests/list.html +23 -0
  69. ui/web/templates/housekeeping/index.html +94 -0
  70. ui/web/templates/partials/forms.html +7 -0
  71. ui/web/templates/partials/ui.html +24 -0
  72. ui/web/templates/pos/index.html +378 -0
  73. ui/web/templates/reports/index.html +51 -0
  74. ui/web/templates/reports/view.html +7 -0
  75. ui/web/templates/reservations/detail.html +249 -0
  76. ui/web/templates/reservations/groups.html +89 -0
  77. ui/web/templates/reservations/list.html +71 -0
  78. ui/web/templates/settings/approvals.html +70 -0
  79. ui/web/templates/settings/health.html +25 -0
  80. ui/web/templates/settings/index.html +230 -0
  81. ui/web/templates/settings/packages.html +69 -0
  82. ui/web/templates/settings/rate_plans.html +89 -0
  83. ui/web/templates/settings/service_catalog.html +56 -0
  84. ui/web/templates/settings/users.html +55 -0
  85. ui/web/templates/settings/vouchers.html +56 -0
  86. ui/web/templates/setup_wizard.html +41 -0
  87. ui/web/templates/support/report.html +322 -0
  88. ui/web/templates/unlock.html +14 -0
  89. ui/web/templates/unlock_recovery.html +17 -0
@@ -0,0 +1,970 @@
1
+ """Read-only validation and preview helpers for assistant write-action proposals.
2
+
3
+ These helpers resolve entities, perform prechecks, and build structured previews
4
+ without mutating application state. They are intended to back confirmed action
5
+ proposals and re-validation before execution.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from datetime import datetime, timedelta
12
+ from typing import Any, Mapping
13
+
14
+ from .common import _parse_iso, _safe_int
15
+ from .. import services
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ DEFAULT_TTL_SECONDS = 600
20
+ ALLOWED_RES_STATUSES_FOR_POSTING = {"Reserved", "Checked In"}
21
+ ALLOWED_PAYMENT_METHODS = {"Cash", "Visa", "Bank", "Other"}
22
+
23
+ # (proposal_action_type) -> (preview_type, execute_type)
24
+ ACTION_MAP = {
25
+ "preview_add_pos_item": ("preview_add_pos_item", None),
26
+ "propose_add_pos_item": ("preview_add_pos_item", "execute_add_pos_item"),
27
+ "propose_complete_walkin_sale": ("preview_complete_walkin_sale", "execute_complete_walkin_sale"),
28
+ "propose_record_payment": ("preview_record_payment", "execute_record_payment"),
29
+ "propose_book_activity": ("preview_book_activity", "execute_book_activity"),
30
+ "propose_create_reservation": ("preview_create_reservation", "execute_create_reservation"),
31
+ }
32
+
33
+ PROPOSAL_ACTION_TYPES = set(ACTION_MAP.keys())
34
+ EXECUTE_ACTION_TYPES = {v[1] for v in ACTION_MAP.values() if v[1]}
35
+
36
+
37
+ def _ok_base(preview_type: str, args: dict | None = None) -> dict[str, Any]:
38
+ return {
39
+ "ok": True,
40
+ "errors": [],
41
+ "warnings": [],
42
+ "checks": [],
43
+ "resolved": {},
44
+ "preview": {"type": preview_type, "args": dict(args or {})},
45
+ }
46
+
47
+
48
+ def _add_error(out: dict[str, Any], msg: str) -> None:
49
+ out["errors"].append(msg)
50
+ out["ok"] = False
51
+
52
+
53
+ def _add_warning(out: dict[str, Any], msg: str) -> None:
54
+ out["warnings"].append(msg)
55
+
56
+
57
+ def _check(out: dict[str, Any], name: str, ok: bool, detail: str = "") -> None:
58
+ out["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
59
+
60
+
61
+ def _row_to_dict(row: Any) -> Any:
62
+ if row is None:
63
+ return None
64
+ try:
65
+ if hasattr(row, "keys"):
66
+ return {k: row[k] for k in row.keys()}
67
+ except Exception:
68
+ pass
69
+ if isinstance(row, dict):
70
+ return dict(row)
71
+ return row
72
+
73
+
74
+ def _float_or_none(v: Any) -> float | None:
75
+ try:
76
+ if v is None or v == "":
77
+ return None
78
+ return float(v)
79
+ except (TypeError, ValueError):
80
+ return None
81
+
82
+
83
+ def _int_or_none(v: Any) -> int | None:
84
+ return _safe_int(v)
85
+
86
+
87
+ def _bool(v: Any) -> bool:
88
+ if isinstance(v, bool):
89
+ return v
90
+ if isinstance(v, (int, float)):
91
+ return bool(v)
92
+ if isinstance(v, str):
93
+ return v.strip().lower() in {"1", "true", "yes", "on"}
94
+ return bool(v)
95
+
96
+
97
+ def _norm_str(v: Any) -> str:
98
+ return str(v or "").strip()
99
+
100
+
101
+ def _get(args: Mapping[str, Any] | None, *keys: str, default: Any = None) -> Any:
102
+ if not isinstance(args, Mapping):
103
+ return default
104
+ for k in keys:
105
+ if k in args and args[k] is not None:
106
+ return args[k]
107
+ return default
108
+
109
+
110
+ def _now_utc() -> datetime:
111
+ return datetime.utcnow()
112
+
113
+
114
+ def _expires_at(ttl_seconds: int | None = None) -> str:
115
+ ttl = int(ttl_seconds if ttl_seconds is not None else DEFAULT_TTL_SECONDS)
116
+ if ttl < 1:
117
+ ttl = DEFAULT_TTL_SECONDS
118
+ return (_now_utc() + timedelta(seconds=ttl)).replace(microsecond=0).isoformat() + "Z"
119
+
120
+
121
+ def _parse_expiry(expires_at: Any) -> datetime | None:
122
+ s = _norm_str(expires_at)
123
+ if not s:
124
+ return None
125
+ try:
126
+ if s.endswith("Z"):
127
+ s = s[:-1] + "+00:00"
128
+ dt = datetime.fromisoformat(s)
129
+ if dt.tzinfo is not None:
130
+ dt = dt.astimezone(tz=None).replace(tzinfo=None)
131
+ return dt
132
+ except Exception:
133
+ try:
134
+ return datetime.strptime(_norm_str(expires_at).replace("Z", ""), "%Y-%m-%dT%H:%M:%S")
135
+ except Exception:
136
+ return None
137
+
138
+
139
+ def _is_expired(expires_at: Any, now: datetime | None = None) -> bool:
140
+ dt = _parse_expiry(expires_at)
141
+ if dt is None:
142
+ return False
143
+ now_dt = now or datetime.utcnow()
144
+ return now_dt > dt
145
+
146
+
147
+ # ── Entity resolution helpers (read-only) ────────────────────────────────────
148
+
149
+ def resolve_reservation(args: Mapping[str, Any] | None, *, for_posting: bool = False) -> dict[str, Any]:
150
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
151
+ rid = _int_or_none(_get(args, "reservation_id", "rid", "res_id", "id"))
152
+ if not rid or rid <= 0:
153
+ _add_error(out, "reservation_id is required")
154
+ _check(out, "reservation_id_present", False)
155
+ return out
156
+ _check(out, "reservation_id_present", True, str(rid))
157
+ try:
158
+ row = services.get_reservation(rid)
159
+ except Exception as e:
160
+ logger.debug("resolve_reservation failed rid=%s", rid, exc_info=True)
161
+ _add_error(out, f"Unable to load reservation #{rid}: {e}")
162
+ _check(out, "reservation_exists", False)
163
+ return out
164
+ if not row:
165
+ _add_error(out, f"Reservation #{rid} not found")
166
+ _check(out, "reservation_exists", False)
167
+ return out
168
+ res = _row_to_dict(row)
169
+ out["resolved"]["reservation"] = res
170
+ status = _norm_str(res.get("status"))
171
+ _check(out, "reservation_exists", True, status or "ok")
172
+ if for_posting:
173
+ allowed = status in ALLOWED_RES_STATUSES_FOR_POSTING
174
+ _check(out, "reservation_status_allows_posting", allowed, status or "unknown")
175
+ if not allowed:
176
+ _add_error(out, f"Reservation #{rid} status '{status or 'unknown'}' does not allow posting (allowed: Reserved, Checked In)")
177
+ return out
178
+
179
+
180
+ def resolve_guest(args: Mapping[str, Any] | None) -> dict[str, Any]:
181
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
182
+ gid = _int_or_none(_get(args, "guest_id", "id"))
183
+ name = _norm_str(_get(args, "guest_name", "name", "query"))
184
+ if gid and gid > 0:
185
+ try:
186
+ guest = _row_to_dict(services.get_guest_by_id(gid))
187
+ except Exception as e:
188
+ logger.debug("resolve_guest get_by_id failed gid=%s", gid, exc_info=True)
189
+ _add_error(out, f"Unable to load guest #{gid}: {e}")
190
+ _check(out, "guest_exists", False)
191
+ return out
192
+ if not guest:
193
+ _add_error(out, f"Guest #{gid} not found")
194
+ _check(out, "guest_exists", False)
195
+ return out
196
+ out["resolved"]["guest"] = guest
197
+ _check(out, "guest_exists", True, f"id={gid}")
198
+ return out
199
+
200
+ if not name:
201
+ _add_warning(out, "No guest_id/guest_name provided; guest will be resolved/created by reservation flow if supported")
202
+ _check(out, "guest_resolved", False, "not provided")
203
+ return out
204
+
205
+ try:
206
+ guests = services.assistant_find_guests(name, limit=8) or []
207
+ except Exception as e:
208
+ logger.debug("resolve_guest search failed name=%r", name, exc_info=True)
209
+ _add_warning(out, f"Guest lookup failed for '{name}': {e}")
210
+ _check(out, "guest_search", False, str(e))
211
+ out["resolved"]["guest_query"] = name
212
+ return out
213
+
214
+ guests = [g for g in guests if g]
215
+ out["resolved"]["guest_query"] = name
216
+ out["resolved"]["guest_matches"] = guests
217
+ if len(guests) == 1:
218
+ out["resolved"]["guest"] = guests[0]
219
+ _check(out, "guest_resolved", True, f"id={guests[0].get('id')}")
220
+ elif len(guests) > 1:
221
+ _add_warning(out, f"Guest name '{name}' is ambiguous ({len(guests)} matches)")
222
+ _check(out, "guest_disambiguation_needed", False, f"{len(guests)} matches")
223
+ else:
224
+ _check(out, "guest_resolved", False, "no existing match (may be created)")
225
+ _add_warning(out, f"No existing guest matched '{name}'; reservation creation may create/find guest by name")
226
+ return out
227
+
228
+
229
+ def _match_inventory_candidate(item: Mapping[str, Any], key: str) -> bool:
230
+ k = key.strip().lower()
231
+ if not k:
232
+ return False
233
+ for field in ("item_name", "name", "sku", "barcode"):
234
+ v = _norm_str(item.get(field)).lower()
235
+ if v and v == k:
236
+ return True
237
+ try:
238
+ iid = _int_or_none(item.get("id"))
239
+ if iid is not None and str(iid) == key.strip():
240
+ return True
241
+ except Exception:
242
+ pass
243
+ return False
244
+
245
+
246
+ def resolve_inventory_item(args: Mapping[str, Any] | None) -> dict[str, Any]:
247
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
248
+ item_id = _int_or_none(_get(args, "item_id", "inv_id", "inventory_item_id", "product_id"))
249
+ code = _norm_str(_get(args, "barcode", "sku", "code"))
250
+ name = _norm_str(_get(args, "item_name", "name", "product_name", "query", "desc"))
251
+ item = None
252
+
253
+ try:
254
+ if item_id:
255
+ row = services.get_inventory_item(item_id)
256
+ item = _row_to_dict(row)
257
+ _check(out, "item_lookup_by_id", bool(item), str(item_id))
258
+ if not item:
259
+ _add_error(out, f"Inventory item #{item_id} not found")
260
+ elif code:
261
+ resolved = services.resolve_barcode(code) or {}
262
+ if resolved.get("type") == "item" and resolved.get("item"):
263
+ item = _row_to_dict(resolved.get("item"))
264
+ elif resolved.get("type") == "batch" and resolved.get("item"):
265
+ item = _row_to_dict(resolved.get("item"))
266
+ if resolved.get("batch"):
267
+ out["resolved"]["resolved_batch_hint"] = _row_to_dict(resolved.get("batch"))
268
+ _check(out, "item_lookup_by_code", bool(item), code)
269
+ out["resolved"]["barcode_resolution"] = _row_to_dict(resolved)
270
+ if not item:
271
+ _add_error(out, f"Inventory item not found for code '{code}'")
272
+ elif name:
273
+ candidates = []
274
+ try:
275
+ candidates = services.search_inventory(query=name) or []
276
+ except Exception:
277
+ try:
278
+ candidates = services.get_inventory_items(query=name) or []
279
+ except Exception:
280
+ candidates = []
281
+ normed = [_row_to_dict(c) for c in candidates if c]
282
+ out["resolved"]["inventory_matches"] = normed[:10]
283
+ exact = [c for c in normed if _match_inventory_candidate(c, name)]
284
+ if len(exact) == 1:
285
+ item = exact[0]
286
+ elif len(normed) == 1:
287
+ item = normed[0]
288
+ elif len(normed) > 1:
289
+ _add_error(out, f"Inventory item '{name}' is ambiguous ({len(normed)} matches); specify item_id/sku/barcode")
290
+ else:
291
+ _add_error(out, f"Inventory item '{name}' not found")
292
+ _check(out, "item_lookup_by_name", bool(item), name)
293
+ else:
294
+ _add_error(out, "Inventory item identifier is required (item_id/inv_id or sku/barcode or item_name)")
295
+ _check(out, "item_identifier_present", False)
296
+ except Exception as e:
297
+ logger.debug("resolve_inventory_item failed args=%r", args, exc_info=True)
298
+ _add_error(out, f"Inventory lookup failed: {e}")
299
+
300
+ if item:
301
+ out["resolved"]["item"] = item
302
+ active = item.get("active", 1)
303
+ is_active = bool(active) if active is not None else True
304
+ _check(out, "item_active", is_active, str(active))
305
+ if not is_active:
306
+ _add_error(out, f"Inventory item '{item.get('item_name') or item.get('id')}' is inactive")
307
+ return out
308
+
309
+
310
+ def resolve_batch_or_lot(item: Mapping[str, Any] | None, args: Mapping[str, Any] | None) -> dict[str, Any]:
311
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
312
+ if not isinstance(item, Mapping):
313
+ return out
314
+ item_id = _int_or_none(item.get("id"))
315
+ batch_id = _int_or_none(_get(args, "batch_id"))
316
+ lot_code = _norm_str(_get(args, "lot_code", "lot"))
317
+ requested_qty = _float_or_none(_get(args, "qty", "quantity"))
318
+ track_batches = _bool(item.get("track_batches"))
319
+
320
+ batch = None
321
+ try:
322
+ if batch_id:
323
+ b = _row_to_dict(services.get_inventory_batch(batch_id))
324
+ if not b:
325
+ _add_error(out, f"Batch #{batch_id} not found")
326
+ _check(out, "batch_exists", False)
327
+ return out
328
+ batch = b
329
+ _check(out, "batch_exists", True, str(batch_id))
330
+ elif lot_code:
331
+ resolved = services.resolve_barcode(lot_code) or {}
332
+ b = _row_to_dict(resolved.get("batch")) if resolved.get("type") == "batch" else None
333
+ if b:
334
+ batch = b
335
+ _check(out, "batch_resolved_by_lot", True, lot_code)
336
+ else:
337
+ _add_error(out, f"Batch/lot '{lot_code}' not found")
338
+ _check(out, "batch_resolved_by_lot", False, lot_code)
339
+ out["resolved"]["barcode_resolution"] = _row_to_dict(resolved)
340
+ elif track_batches:
341
+ _check(out, "batch_specified", False, "auto-allocation possible")
342
+ _add_warning(out, "Batch-tracked item without explicit batch/lot; service may auto-allocate available batches")
343
+ except Exception as e:
344
+ logger.debug("resolve_batch_or_lot failed", exc_info=True)
345
+ _add_error(out, f"Batch lookup failed: {e}")
346
+
347
+ if batch:
348
+ b_item_id = _int_or_none(batch.get("item_id"))
349
+ if item_id and b_item_id and b_item_id != item_id:
350
+ _add_error(out, f"Batch #{batch.get('id') or batch_id} belongs to item #{b_item_id}, not item #{item_id}")
351
+ _check(out, "batch_belongs_to_item", False, f"{b_item_id} != {item_id}")
352
+ else:
353
+ _check(out, "batch_belongs_to_item", True)
354
+ status = _norm_str(batch.get("status")).lower()
355
+ if status and status not in {"active"}:
356
+ _add_warning(out, f"Batch status is '{status}'")
357
+ _check(out, "batch_status_active", False, status)
358
+ else:
359
+ _check(out, "batch_status_active", True, status or "active")
360
+ rem = _float_or_none(batch.get("quantity_remaining"))
361
+ if rem is not None:
362
+ if requested_qty is not None and requested_qty > rem + 1e-9:
363
+ _add_warning(out, f"Requested qty {requested_qty} exceeds batch remaining {rem}; sale may fail or allocate across batches depending on service behavior")
364
+ _check(out, "batch_has_requested_qty", False, f"remaining={rem}")
365
+ else:
366
+ _check(out, "batch_has_requested_qty", True, f"remaining={rem}")
367
+ out["resolved"]["batch"] = batch
368
+ return out
369
+
370
+
371
+ def resolve_room(args: Mapping[str, Any] | None) -> dict[str, Any]:
372
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
373
+ room_id = _int_or_none(_get(args, "room_id"))
374
+ room_query = _norm_str(_get(args, "room", "room_number", "room_query"))
375
+ try:
376
+ if room_id:
377
+ room = _row_to_dict(services.get_room(room_id))
378
+ if not room:
379
+ _add_error(out, f"Room #{room_id} not found")
380
+ _check(out, "room_exists", False)
381
+ else:
382
+ out["resolved"]["room"] = room
383
+ _check(out, "room_exists", True, str(room_id))
384
+ return out
385
+ if room_query:
386
+ rooms = [_row_to_dict(r) for r in (services.get_all_rooms() or []) if r]
387
+ matches = [r for r in rooms if _norm_str(r.get("room_number")).lower() == room_query.lower()]
388
+ if not matches:
389
+ matches = [r for r in rooms if room_query.lower() in _norm_str(r.get("room_number")).lower()]
390
+ if len(matches) == 1:
391
+ out["resolved"]["room"] = matches[0]
392
+ _check(out, "room_resolved", True, _norm_str(matches[0].get("room_number")))
393
+ elif len(matches) > 1:
394
+ _add_error(out, f"Room '{room_query}' is ambiguous ({len(matches)} matches)")
395
+ out["resolved"]["room_matches"] = matches[:10]
396
+ _check(out, "room_disambiguation_needed", False)
397
+ else:
398
+ _add_error(out, f"Room '{room_query}' not found")
399
+ _check(out, "room_resolved", False)
400
+ return out
401
+ _add_error(out, "room_id or room/room_number is required")
402
+ _check(out, "room_identifier_present", False)
403
+ except Exception as e:
404
+ logger.debug("resolve_room failed", exc_info=True)
405
+ _add_error(out, f"Room lookup failed: {e}")
406
+ return out
407
+
408
+
409
+ def resolve_rate_plan(args: Mapping[str, Any] | None) -> dict[str, Any]:
410
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
411
+ rate_plan_id = _int_or_none(_get(args, "rate_plan_id", "plan_id"))
412
+ try:
413
+ plans = [_row_to_dict(p) for p in (services.get_all_rate_plans() or []) if p]
414
+ out["resolved"]["rate_plans_count"] = len(plans)
415
+ if rate_plan_id is None:
416
+ _check(out, "rate_plan_optional", True, "none provided")
417
+ return out
418
+ match = next((p for p in plans if _int_or_none(p.get("id")) == rate_plan_id), None)
419
+ if not match:
420
+ _add_error(out, f"Rate plan #{rate_plan_id} not found")
421
+ _check(out, "rate_plan_exists", False)
422
+ else:
423
+ out["resolved"]["rate_plan"] = match
424
+ _check(out, "rate_plan_exists", True, _norm_str(match.get("name")))
425
+ except Exception as e:
426
+ logger.debug("resolve_rate_plan failed", exc_info=True)
427
+ _add_error(out, f"Rate plan lookup failed: {e}")
428
+ return out
429
+
430
+
431
+ def resolve_activity(args: Mapping[str, Any] | None) -> dict[str, Any]:
432
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
433
+ aid = _int_or_none(_get(args, "activity_id", "id"))
434
+ if not aid:
435
+ _add_error(out, "activity_id is required")
436
+ _check(out, "activity_id_present", False)
437
+ return out
438
+ try:
439
+ act = _row_to_dict(services.get_activity(aid))
440
+ if not act:
441
+ _add_error(out, f"Activity #{aid} not found")
442
+ _check(out, "activity_exists", False)
443
+ return out
444
+ out["resolved"]["activity"] = act
445
+ active = bool(act.get("active", 1))
446
+ _check(out, "activity_exists", True, _norm_str(act.get("name")))
447
+ _check(out, "activity_active", active)
448
+ if not active:
449
+ _add_error(out, f"Activity #{aid} is inactive")
450
+ except Exception as e:
451
+ logger.debug("resolve_activity failed", exc_info=True)
452
+ _add_error(out, f"Activity lookup failed: {e}")
453
+ return out
454
+
455
+
456
+ def check_availability(args: Mapping[str, Any] | None, room_id: int | None = None) -> dict[str, Any]:
457
+ out = {"ok": True, "errors": [], "warnings": [], "checks": [], "resolved": {}, "preview": {}}
458
+ rid = room_id or _int_or_none(_get(args, "room_id"))
459
+ ci = _norm_str(_get(args, "check_in", "check_in_date", "start"))
460
+ co = _norm_str(_get(args, "check_out", "check_out_date", "end"))
461
+ exclude_res_id = _int_or_none(_get(args, "exclude_reservation_id", "exclude_res_id"))
462
+ if not rid or not ci or not co:
463
+ _check(out, "availability_inputs_present", False)
464
+ return out
465
+ d1 = _parse_iso(ci)
466
+ d2 = _parse_iso(co)
467
+ if not d1 or not d2:
468
+ _add_error(out, "check_in/check_out must be valid YYYY-MM-DD dates")
469
+ _check(out, "dates_parse", False)
470
+ return out
471
+ if d2 <= d1:
472
+ _add_error(out, "check_out must be after check_in")
473
+ _check(out, "dates_order", False)
474
+ return out
475
+ nights = (d2 - d1).days
476
+ out["preview"] = {"nights": nights}
477
+ _check(out, "dates_order", True, f"{nights} night(s)")
478
+ try:
479
+ available = bool(services.check_room_availability(rid, ci, co, exclude_res_id=exclude_res_id))
480
+ _check(out, "room_available", available)
481
+ if not available:
482
+ _add_error(out, f"Room #{rid} is not available for {ci} to {co}")
483
+ try:
484
+ avail_rooms = services.get_rooms_available_between(ci, co) or []
485
+ avail_ids = {_int_or_none((r["id"] if hasattr(r, "keys") else r.get("id"))) for r in [_row_to_dict(x) for x in avail_rooms]}
486
+ out["resolved"]["available_room_ids"] = sorted([i for i in avail_ids if i])
487
+ except Exception:
488
+ logger.debug("check_availability: get_rooms_available_between failed", exc_info=True)
489
+ except Exception as e:
490
+ logger.debug("check_availability failed", exc_info=True)
491
+ _add_error(out, f"Availability check failed: {e}")
492
+ _check(out, "room_available", False, str(e))
493
+ return out
494
+
495
+
496
+ # ── Preview builders / prechecks ──────────────────────────────────────────────
497
+
498
+ def _merge_child(out: dict[str, Any], child: Mapping[str, Any] | None, *, namespace: str | None = None) -> None:
499
+ if not isinstance(child, Mapping):
500
+ return
501
+ out["errors"].extend(child.get("errors") or [])
502
+ out["warnings"].extend(child.get("warnings") or [])
503
+ checks = child.get("checks") or []
504
+ if namespace:
505
+ for c in checks:
506
+ cc = dict(c)
507
+ if cc.get("name"):
508
+ cc["name"] = f"{namespace}.{cc['name']}"
509
+ out["checks"].append(cc)
510
+ else:
511
+ out["checks"].extend(checks)
512
+ resolved = child.get("resolved") or {}
513
+ if namespace:
514
+ out["resolved"].setdefault(namespace, {})
515
+ if isinstance(out["resolved"][namespace], dict):
516
+ out["resolved"][namespace].update(resolved)
517
+ else:
518
+ out["resolved"].update(resolved)
519
+ if child.get("ok") is False:
520
+ out["ok"] = False
521
+
522
+
523
+ def _money_round(v: float | None) -> float | None:
524
+ if v is None:
525
+ return None
526
+ try:
527
+ return round(float(v), 2)
528
+ except Exception:
529
+ return v
530
+
531
+
532
+ def preview_add_pos_item(args: Mapping[str, Any] | None) -> dict[str, Any]:
533
+ args = dict(args or {})
534
+ out = _ok_base("preview_add_pos_item", args)
535
+ rid = _int_or_none(_get(args, "reservation_id", "rid", "res_id"))
536
+ qty = _float_or_none(_get(args, "qty", "quantity"))
537
+ price_arg = _float_or_none(_get(args, "price", "unit_price", "selling_price"))
538
+ desc = _norm_str(_get(args, "desc", "item_description", "description", "item_name", "name"))
539
+
540
+ res = resolve_reservation({"reservation_id": rid}, for_posting=True)
541
+ _merge_child(out, res)
542
+ item_res = resolve_inventory_item(args)
543
+ _merge_child(out, item_res)
544
+ item = (item_res.get("resolved") or {}).get("item") if isinstance(item_res.get("resolved"), dict) else None
545
+ batch_res = resolve_batch_or_lot(item or {}, args)
546
+ _merge_child(out, batch_res)
547
+
548
+ if qty is None or qty <= 0:
549
+ _add_error(out, "qty must be a positive number")
550
+ _check(out, "qty_positive", False)
551
+ else:
552
+ _check(out, "qty_positive", True, str(qty))
553
+
554
+ allow_negative = False
555
+ stock_qty = None
556
+ try:
557
+ allow_negative = str(services.get_setting("allow_negative_stock", "false")).lower() == "true"
558
+ except Exception:
559
+ logger.debug("preview_add_pos_item: failed to read allow_negative_stock", exc_info=True)
560
+ if isinstance(item, dict):
561
+ stock_qty = _float_or_none(item.get("stock_qty"))
562
+ if desc == "":
563
+ desc = _norm_str(item.get("item_name") or item.get("name"))
564
+ if price_arg is None:
565
+ price_arg = _float_or_none(item.get("selling_price"))
566
+ out["resolved"]["allow_negative_stock"] = allow_negative
567
+
568
+ if not desc:
569
+ _add_error(out, "desc/item description is required")
570
+ _check(out, "description_present", False)
571
+ else:
572
+ _check(out, "description_present", True)
573
+
574
+ batch = (batch_res.get("resolved") or {}).get("batch") if isinstance(batch_res.get("resolved"), dict) else None
575
+ if isinstance(item, dict) and qty is not None and qty > 0:
576
+ if batch and _float_or_none(batch.get("quantity_remaining")) is not None:
577
+ pass
578
+ elif stock_qty is not None and qty > stock_qty + 1e-9 and not allow_negative:
579
+ _add_error(out, f"Insufficient stock: {stock_qty} available, {qty} requested")
580
+ _check(out, "stock_sufficient", False, f"available={stock_qty}")
581
+ else:
582
+ _check(out, "stock_sufficient", True, f"available={stock_qty}")
583
+
584
+ subtotal = None
585
+ if qty is not None and price_arg is not None:
586
+ try:
587
+ subtotal = _money_round(float(price_arg) * float(qty))
588
+ except Exception:
589
+ subtotal = None
590
+
591
+ tax_preview = None
592
+ if subtotal is not None:
593
+ try:
594
+ t = services.calculate_tax(subtotal, 0)
595
+ if isinstance(t, dict):
596
+ tax_preview = {
597
+ "net": _money_round(_float_or_none(t.get("net"))),
598
+ "service": _money_round(_float_or_none(t.get("service"))),
599
+ "vat": _money_round(_float_or_none(t.get("vat"))),
600
+ "city_tax": _money_round(_float_or_none(t.get("city_tax"))),
601
+ "gross": _money_round(_float_or_none(t.get("gross"))),
602
+ }
603
+ except Exception:
604
+ logger.debug("preview_add_pos_item: tax preview unavailable", exc_info=True)
605
+
606
+ out["preview"] = {
607
+ "type": "preview_add_pos_item",
608
+ "reservation_id": rid,
609
+ "item_id": _int_or_none(item.get("id")) if isinstance(item, dict) else _int_or_none(_get(args, "item_id", "inv_id")),
610
+ "item_name": (item.get("item_name") if isinstance(item, dict) else None) or desc or None,
611
+ "description": desc or None,
612
+ "qty": qty,
613
+ "unit_price": _money_round(price_arg),
614
+ "estimated_subtotal": subtotal,
615
+ "tax_preview": tax_preview,
616
+ "batch_id": _int_or_none((batch or {}).get("id")) if isinstance(batch, dict) else _int_or_none(_get(args, "batch_id")),
617
+ "lot_code": _norm_str((batch or {}).get("lot_code")) if isinstance(batch, dict) else (_norm_str(_get(args, "lot_code")) or None),
618
+ "stock_qty": stock_qty,
619
+ "allow_negative_stock": allow_negative,
620
+ }
621
+ return out
622
+
623
+
624
+ def preview_complete_walkin_sale(args: Mapping[str, Any] | None) -> dict[str, Any]:
625
+ args = dict(args or {})
626
+ out = _ok_base("preview_complete_walkin_sale", args)
627
+ items = _get(args, "items") or []
628
+ method = _norm_str(_get(args, "method", "payment_method"))
629
+ notes = _norm_str(_get(args, "notes"))
630
+ payment_type = _norm_str(_get(args, "payment_type")) or "Payment"
631
+ if not isinstance(items, list) or not items:
632
+ _add_error(out, "items must be a non-empty list")
633
+ _check(out, "items_present", False)
634
+ items = []
635
+ else:
636
+ _check(out, "items_present", True, str(len(items)))
637
+ if not method:
638
+ _add_error(out, "payment method is required")
639
+ _check(out, "payment_method_present", False)
640
+ else:
641
+ _check(out, "payment_method_present", True, method)
642
+ if method not in ALLOWED_PAYMENT_METHODS:
643
+ _add_warning(out, f"Payment method '{method}' is uncommon; ensure it is supported")
644
+
645
+ normalized_items = []
646
+ total = 0.0
647
+ for idx, it in enumerate(items):
648
+ it = dict(it or {})
649
+ it_args = {
650
+ "item_id": _get(it, "inv_id", "item_id", "inventory_item_id"),
651
+ "barcode": _get(it, "barcode", "sku"),
652
+ "item_name": _get(it, "desc", "item_name", "name"),
653
+ "batch_id": _get(it, "batch_id"),
654
+ "lot_code": _get(it, "lot_code"),
655
+ "qty": _get(it, "qty", "quantity"),
656
+ }
657
+ child = _ok_base("walkin_item", it_args)
658
+ item_res = resolve_inventory_item(it_args)
659
+ _merge_child(child, item_res)
660
+ item = (item_res.get("resolved") or {}).get("item") if isinstance(item_res.get("resolved"), dict) else None
661
+ batch_res = resolve_batch_or_lot(item or {}, it_args)
662
+ _merge_child(child, batch_res)
663
+ qty = _float_or_none(_get(it, "qty", "quantity"))
664
+ price = _float_or_none(_get(it, "price", "unit_price"))
665
+ desc = _norm_str(_get(it, "desc", "description"))
666
+ if isinstance(item, dict):
667
+ if not desc:
668
+ desc = _norm_str(item.get("item_name"))
669
+ if price is None:
670
+ price = _float_or_none(item.get("selling_price"))
671
+ if qty is None or qty <= 0:
672
+ _add_error(child, f"Item {idx + 1}: qty must be positive")
673
+ if not desc:
674
+ _add_error(child, f"Item {idx + 1}: desc is required")
675
+ if price is None or price < 0:
676
+ _add_error(child, f"Item {idx + 1}: price is required")
677
+ line_total = None
678
+ if qty is not None and price is not None:
679
+ line_total = _money_round(qty * price)
680
+ if line_total is not None:
681
+ total += float(line_total)
682
+ batch_resolved = (batch_res.get("resolved") or {}) if isinstance(batch_res.get("resolved"), dict) else {}
683
+ batch_obj = batch_resolved.get("batch") if isinstance(batch_resolved.get("batch"), dict) else {}
684
+ child_preview = {
685
+ "index": idx,
686
+ "inv_id": _int_or_none((item or {}).get("id")) if isinstance(item, dict) else _int_or_none(_get(it, "inv_id", "item_id")),
687
+ "desc": desc or None,
688
+ "qty": qty,
689
+ "price": _money_round(price),
690
+ "line_total": line_total,
691
+ "batch_id": _int_or_none(batch_obj.get("id")) or _int_or_none(_get(it, "batch_id")),
692
+ "lot_code": _norm_str(batch_obj.get("lot_code")) or (_norm_str(_get(it, "lot_code")) or None),
693
+ "errors": list(child.get("errors") or []),
694
+ "warnings": list(child.get("warnings") or []),
695
+ }
696
+ normalized_items.append(child_preview)
697
+ out["errors"].extend([f"Item {idx + 1}: {e}" if not str(e).startswith("Item ") else str(e) for e in (child.get("errors") or [])])
698
+ out["warnings"].extend([f"Item {idx + 1}: {w}" if not str(w).startswith("Item ") else str(w) for w in (child.get("warnings") or [])])
699
+ for c in (child.get("checks") or []):
700
+ cc = dict(c)
701
+ cc["name"] = f"item[{idx}].{cc.get('name')}"
702
+ out["checks"].append(cc)
703
+
704
+ if out["errors"]:
705
+ out["ok"] = False
706
+ out["preview"] = {
707
+ "type": "preview_complete_walkin_sale",
708
+ "items": normalized_items,
709
+ "item_count": len(normalized_items),
710
+ "estimated_total": _money_round(total),
711
+ "method": method or None,
712
+ "payment_type": payment_type,
713
+ "notes": notes or "",
714
+ }
715
+ return out
716
+
717
+
718
+ def preview_record_payment(args: Mapping[str, Any] | None) -> dict[str, Any]:
719
+ args = dict(args or {})
720
+ out = _ok_base("preview_record_payment", args)
721
+ rid = _int_or_none(_get(args, "reservation_id", "rid", "res_id"))
722
+ amount = _float_or_none(_get(args, "amount"))
723
+ method = _norm_str(_get(args, "method", "payment_method"))
724
+ notes = _norm_str(_get(args, "notes"))
725
+ payment_type = _norm_str(_get(args, "payment_type")) or "Payment"
726
+
727
+ res = resolve_reservation({"reservation_id": rid}, for_posting=True)
728
+ _merge_child(out, res)
729
+ if amount is None or amount <= 0:
730
+ _add_error(out, "amount must be positive")
731
+ _check(out, "amount_positive", False)
732
+ else:
733
+ _check(out, "amount_positive", True, str(amount))
734
+ if not method:
735
+ _add_error(out, "method is required")
736
+ _check(out, "method_present", False)
737
+ else:
738
+ _check(out, "method_present", True, method)
739
+
740
+ balance = None
741
+ try:
742
+ if rid:
743
+ bd = services.get_balance_breakdown(rid)
744
+ if isinstance(bd, dict):
745
+ balance = _float_or_none(bd.get("balance_due") if bd.get("balance_due") is not None else bd.get("balance"))
746
+ elif bd is not None:
747
+ balance = _float_or_none(bd)
748
+ except Exception:
749
+ try:
750
+ if rid:
751
+ balance = _float_or_none(services.calculate_guest_balance(rid))
752
+ except Exception:
753
+ logger.debug("preview_record_payment: balance lookup failed rid=%s", rid, exc_info=True)
754
+ if amount is not None and balance is not None and amount - balance > 0.01:
755
+ _add_warning(out, f"Payment amount {amount} exceeds current balance due {balance}")
756
+
757
+ out["preview"] = {
758
+ "type": "preview_record_payment",
759
+ "reservation_id": rid,
760
+ "amount": _money_round(amount),
761
+ "method": method or None,
762
+ "payment_type": payment_type,
763
+ "notes": notes or "",
764
+ "current_balance_due": _money_round(balance),
765
+ "projected_balance_due": _money_round((balance - amount) if (balance is not None and amount is not None) else None),
766
+ }
767
+ return out
768
+
769
+
770
+ def preview_book_activity(args: Mapping[str, Any] | None) -> dict[str, Any]:
771
+ args = dict(args or {})
772
+ out = _ok_base("preview_book_activity", args)
773
+ rid = _int_or_none(_get(args, "reservation_id", "rid", "res_id"))
774
+ aid = _int_or_none(_get(args, "activity_id", "id"))
775
+ qty = _int_or_none(_get(args, "quantity", "qty")) or 1
776
+ scheduled_at = _norm_str(_get(args, "scheduled_at"))
777
+ notes = _norm_str(_get(args, "notes"))
778
+
779
+ res = resolve_reservation({"reservation_id": rid}, for_posting=True)
780
+ _merge_child(out, res)
781
+ act_res = resolve_activity({"activity_id": aid})
782
+ _merge_child(out, act_res)
783
+ if qty <= 0:
784
+ _add_error(out, "quantity must be positive")
785
+ _check(out, "quantity_positive", False)
786
+ else:
787
+ _check(out, "quantity_positive", True, str(qty))
788
+
789
+ activity = (act_res.get("resolved") or {}).get("activity") if isinstance(act_res.get("resolved"), dict) else None
790
+ unit_price = _float_or_none(activity.get("unit_price")) if isinstance(activity, dict) else None
791
+ est = _money_round(unit_price * qty) if unit_price is not None else None
792
+ out["preview"] = {
793
+ "type": "preview_book_activity",
794
+ "reservation_id": rid,
795
+ "activity_id": aid,
796
+ "activity_name": _norm_str(activity.get("name")) if isinstance(activity, dict) else None,
797
+ "quantity": qty,
798
+ "unit_price": _money_round(unit_price),
799
+ "estimated_total": est,
800
+ "scheduled_at": scheduled_at or None,
801
+ "notes": notes or "",
802
+ }
803
+ return out
804
+
805
+
806
+ def preview_create_reservation(args: Mapping[str, Any] | None) -> dict[str, Any]:
807
+ args = dict(args or {})
808
+ out = _ok_base("preview_create_reservation", args)
809
+ guest_name = _norm_str(_get(args, "guest_name", "name"))
810
+ guest_id = _int_or_none(_get(args, "guest_id"))
811
+ source = _norm_str(_get(args, "source")) or "Direct"
812
+ room_id = _int_or_none(_get(args, "room_id"))
813
+ rate_plan_id = _int_or_none(_get(args, "rate_plan_id"))
814
+ rate = _float_or_none(_get(args, "rate", "agreed_nightly_rate", "nightly_rate"))
815
+ ci = _norm_str(_get(args, "check_in", "check_in_date"))
816
+ co = _norm_str(_get(args, "check_out", "check_out_date"))
817
+ deposit = _float_or_none(_get(args, "deposit", "deposit_amount")) or 0.0
818
+
819
+ if not guest_name and not guest_id:
820
+ _add_error(out, "guest_name or guest_id is required")
821
+ _check(out, "guest_identifier_present", False)
822
+ else:
823
+ _check(out, "guest_identifier_present", True)
824
+ _merge_child(out, resolve_guest({"guest_id": guest_id, "guest_name": guest_name}), namespace="guest_resolution")
825
+
826
+ room_res = resolve_room({"room_id": room_id, "room_number": _get(args, "room_number", "room")})
827
+ _merge_child(out, room_res)
828
+ resolved_room = (room_res.get("resolved") or {}).get("room") if isinstance(room_res.get("resolved"), dict) else None
829
+ if resolved_room and not room_id:
830
+ room_id = _int_or_none(resolved_room.get("id"))
831
+ out["resolved"]["room_id"] = room_id
832
+
833
+ rp_res = resolve_rate_plan({"rate_plan_id": rate_plan_id})
834
+ _merge_child(out, rp_res)
835
+
836
+ if rate is None or rate < 0:
837
+ if isinstance(resolved_room, dict):
838
+ base = _float_or_none(resolved_room.get("base_price"))
839
+ if base is not None:
840
+ rate = base
841
+ _add_warning(out, "Rate not provided; using room base_price for preview (service may require explicit rate)")
842
+ if rate is None:
843
+ _add_error(out, "rate/agreed_nightly_rate is required")
844
+ _check(out, "rate_present", False)
845
+ else:
846
+ _check(out, "rate_present", True, str(rate))
847
+
848
+ avail_res = check_availability({"room_id": room_id, "check_in": ci, "check_out": co})
849
+ _merge_child(out, avail_res)
850
+ nights = ((avail_res.get("preview") or {}).get("nights") if isinstance(avail_res.get("preview"), dict) else None)
851
+ if ci and not _parse_iso(ci):
852
+ _add_error(out, "check_in must be YYYY-MM-DD")
853
+ if co and not _parse_iso(co):
854
+ _add_error(out, "check_out must be YYYY-MM-DD")
855
+ if not ci or not co:
856
+ _add_error(out, "check_in and check_out are required")
857
+
858
+ est_total = _money_round(rate * nights) if (rate is not None and isinstance(nights, int) and nights > 0) else None
859
+ out["preview"] = {
860
+ "type": "preview_create_reservation",
861
+ "guest_id": guest_id or (((out.get("resolved") or {}).get("guest_resolution") or {}).get("guest") or {}).get("id") if isinstance(out.get("resolved"), dict) else None,
862
+ "guest_name": guest_name or None,
863
+ "source": source,
864
+ "room_id": room_id,
865
+ "room_number": _norm_str(resolved_room.get("room_number")) if isinstance(resolved_room, dict) else None,
866
+ "rate_plan_id": rate_plan_id,
867
+ "rate": _money_round(rate),
868
+ "check_in": ci or None,
869
+ "check_out": co or None,
870
+ "nights": nights,
871
+ "estimated_room_total": est_total,
872
+ "deposit": _money_round(deposit),
873
+ }
874
+ return out
875
+
876
+
877
+ _PREVIEW_BUILDERS = {
878
+ "preview_add_pos_item": preview_add_pos_item,
879
+ "propose_add_pos_item": preview_add_pos_item,
880
+ "execute_add_pos_item": preview_add_pos_item,
881
+ "preview_complete_walkin_sale": preview_complete_walkin_sale,
882
+ "propose_complete_walkin_sale": preview_complete_walkin_sale,
883
+ "execute_complete_walkin_sale": preview_complete_walkin_sale,
884
+ "preview_record_payment": preview_record_payment,
885
+ "propose_record_payment": preview_record_payment,
886
+ "execute_record_payment": preview_record_payment,
887
+ "preview_book_activity": preview_book_activity,
888
+ "propose_book_activity": preview_book_activity,
889
+ "execute_book_activity": preview_book_activity,
890
+ "preview_create_reservation": preview_create_reservation,
891
+ "propose_create_reservation": preview_create_reservation,
892
+ "execute_create_reservation": preview_create_reservation,
893
+ }
894
+
895
+
896
+ def build_prechecks(action_type: str, args: Mapping[str, Any] | None = None, ui_context: Mapping[str, Any] | None = None) -> dict[str, Any]:
897
+ """Build read-only prechecks/preview for a supported action type."""
898
+ action_type = _norm_str(action_type)
899
+ args = dict(args or {})
900
+ builder = _PREVIEW_BUILDERS.get(action_type)
901
+ if not builder:
902
+ return {
903
+ "ok": False,
904
+ "errors": [f"Unsupported action type '{action_type}'"],
905
+ "warnings": [],
906
+ "checks": [],
907
+ "resolved": {},
908
+ "preview": {"type": action_type, "args": args},
909
+ }
910
+ try:
911
+ out = builder(args)
912
+ except Exception as e:
913
+ logger.exception("build_prechecks failed action_type=%s", action_type)
914
+ out = _ok_base(action_type, args)
915
+ _add_error(out, f"Precheck failed: {e}")
916
+ out.setdefault("ok", not bool(out.get("errors")))
917
+ out.setdefault("errors", [])
918
+ out.setdefault("warnings", [])
919
+ out.setdefault("checks", [])
920
+ out.setdefault("resolved", {})
921
+ preview = out.setdefault("preview", {})
922
+ if isinstance(preview, dict):
923
+ preview.setdefault("type", action_type)
924
+ if ui_context:
925
+ out["resolved"]["ui_context"] = dict(ui_context)
926
+ return out
927
+
928
+
929
+ def normalize_action_args(action_type: str, args: Mapping[str, Any] | None = None) -> dict[str, Any]:
930
+ """Best-effort normalization for common arg aliases (non-destructive)."""
931
+ a = dict(args or {})
932
+ at = _norm_str(action_type)
933
+ if "reservation_id" not in a:
934
+ for k in ("rid", "res_id"):
935
+ if a.get(k) is not None:
936
+ a["reservation_id"] = _int_or_none(a.get(k)) or a.get(k)
937
+ break
938
+ if "guest_id" not in a and a.get("id") is not None and at in {"propose_create_reservation", "preview_create_reservation"}:
939
+ a["guest_id"] = _int_or_none(a.get("id")) or a.get("id")
940
+ if at in {"propose_add_pos_item", "preview_add_pos_item", "execute_add_pos_item"}:
941
+ if "item_id" not in a and a.get("inv_id") is not None:
942
+ a["item_id"] = _int_or_none(a.get("inv_id")) or a.get("inv_id")
943
+ if "desc" not in a:
944
+ for k in ("item_description", "description", "item_name", "name"):
945
+ if a.get(k):
946
+ a["desc"] = a.get(k)
947
+ break
948
+ if "qty" not in a and a.get("quantity") is not None:
949
+ a["qty"] = a.get("quantity")
950
+ if at in {"propose_record_payment", "execute_record_payment"}:
951
+ if "payment_type" not in a or not a.get("payment_type"):
952
+ a["payment_type"] = "Payment"
953
+ if at in {"propose_complete_walkin_sale", "execute_complete_walkin_sale"}:
954
+ if "payment_type" not in a or not a.get("payment_type"):
955
+ a["payment_type"] = "Payment"
956
+ items = a.get("items")
957
+ if isinstance(items, list):
958
+ norm_items = []
959
+ for it in items:
960
+ if not isinstance(it, dict):
961
+ norm_items.append(it)
962
+ continue
963
+ it2 = dict(it)
964
+ if "inv_id" not in it2 and it2.get("item_id") is not None:
965
+ it2["inv_id"] = it2.get("item_id")
966
+ if "desc" not in it2 and it2.get("item_name") is not None:
967
+ it2["desc"] = it2.get("item_name")
968
+ norm_items.append(it2)
969
+ a["items"] = norm_items
970
+ return a