@zimmerstack/connect 0.7.0 → 0.9.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/AGENTS.md +305 -25
- package/README.md +572 -56
- package/dist/cjs/client.d.ts +528 -13
- package/dist/cjs/client.js +778 -46
- package/dist/cjs/doctor.d.ts +86 -0
- package/dist/cjs/doctor.js +689 -0
- package/dist/cjs/errors.d.ts +6 -2
- package/dist/cjs/errors.js +7 -2
- package/dist/cjs/generated.d.ts +2873 -203
- package/dist/cjs/generated.js +222 -8
- package/dist/cjs/grid.d.ts +6 -1
- package/dist/cjs/grid.js +8 -0
- package/dist/cjs/index.d.ts +14 -5
- package/dist/cjs/index.js +41 -1
- package/dist/cjs/key.d.ts +39 -0
- package/dist/cjs/key.js +85 -0
- package/dist/cjs/money.d.ts +81 -0
- package/dist/cjs/money.js +172 -0
- package/dist/cjs/notices.d.ts +44 -0
- package/dist/cjs/notices.js +64 -0
- package/dist/cjs/shownOnce.d.ts +42 -0
- package/dist/cjs/shownOnce.js +83 -0
- package/dist/cjs/webhooks.d.ts +182 -3
- package/dist/cjs/webhooks.js +75 -1
- package/dist/esm/client.d.ts +528 -13
- package/dist/esm/client.js +776 -46
- package/dist/esm/doctor.d.ts +86 -0
- package/dist/esm/doctor.js +685 -0
- package/dist/esm/errors.d.ts +6 -2
- package/dist/esm/errors.js +7 -2
- package/dist/esm/generated.d.ts +2873 -203
- package/dist/esm/generated.js +221 -7
- package/dist/esm/grid.d.ts +6 -1
- package/dist/esm/grid.js +7 -0
- package/dist/esm/index.d.ts +14 -5
- package/dist/esm/index.js +8 -3
- package/dist/esm/key.d.ts +39 -0
- package/dist/esm/key.js +81 -0
- package/dist/esm/mcp/cli.js +95 -11
- package/dist/esm/mcp/reference.generated.js +5741 -1008
- package/dist/esm/mcp/server.d.ts +14 -6
- package/dist/esm/mcp/server.js +451 -25
- package/dist/esm/money.d.ts +81 -0
- package/dist/esm/money.js +161 -0
- package/dist/esm/notices.d.ts +44 -0
- package/dist/esm/notices.js +56 -0
- package/dist/esm/shownOnce.d.ts +42 -0
- package/dist/esm/shownOnce.js +77 -0
- package/dist/esm/webhooks.d.ts +182 -3
- package/dist/esm/webhooks.js +69 -0
- package/package.json +2 -2
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
import { ZimmerStack, aboutHowLong } from "./client.js";
|
|
2
|
+
import { ZimmerStackError, ZimmerStackUsageError } from "./errors.js";
|
|
3
|
+
import { checkKey } from "./key.js";
|
|
4
|
+
const DAY_MS = 86_400_000;
|
|
5
|
+
const HOUR_MS = 3_600_000;
|
|
6
|
+
/** A budget this full is worth a line. */
|
|
7
|
+
const NEARLY_FULL = 80;
|
|
8
|
+
const PORTAL = "the partner portal (https://partner.zimmerstack.com, Developers)";
|
|
9
|
+
const OWNER = "Admin → Developers → API keys (https://admin.zimmerstack.com/configure/developers)";
|
|
10
|
+
/** What a scope lets a key do, in a few words. A scope this list does not know is shown by its name. */
|
|
11
|
+
const SCOPE_DOES = {
|
|
12
|
+
"ari:read": "read the calendar and the sync state",
|
|
13
|
+
"ari:write": "send room counts, prices and stay rules",
|
|
14
|
+
"catalog:write": "create and change room types and rate plans",
|
|
15
|
+
"channel-modifiers:write": "set a channel's price modifier",
|
|
16
|
+
"channel-bookings:read": "read OTA bookings and the channel events",
|
|
17
|
+
"direct-bookings:read": "read the hotel's own website bookings",
|
|
18
|
+
"direct-bookings:cancel": "cancel a website booking and refund it",
|
|
19
|
+
"bookings:read": "read the bookings it created",
|
|
20
|
+
"bookings:write": "create and cancel bookings in the PMS",
|
|
21
|
+
"bookings:payments": "record a payment on a booking it creates",
|
|
22
|
+
"properties:write": "add and remove hotels",
|
|
23
|
+
"webhooks:manage": "manage your company webhook endpoints",
|
|
24
|
+
"channels:connect": "make one-time connect links",
|
|
25
|
+
"keys:manage": "list, mint, rotate and revoke the keys you made on a hotel",
|
|
26
|
+
"billing:read": "read your invoices and your hotel quota",
|
|
27
|
+
"support:write": "open and answer support tickets",
|
|
28
|
+
};
|
|
29
|
+
/** What to do about a refusal seen in the request log, by its code. */
|
|
30
|
+
const REFUSAL_ADVICE = {
|
|
31
|
+
VALIDATION: "The request itself is wrong: a field is missing, misnamed or out of range. Read the message your code received (err.message, err.details) and fix the request; sending it again unchanged is refused again.",
|
|
32
|
+
RATE_LIMITED: "A budget was used up. The package waits a minute's budget out by itself; if you call the API without it, wait for Retry-After. If this is constant, send only what changed instead of whole calendars.",
|
|
33
|
+
SCOPE_MISSING: "The key was not given that permission. Whoever made the key adds the scope; no rotation is needed.",
|
|
34
|
+
IP_NOT_ALLOWED: "A request came from an address that is not on the key's allowlist. If it is your own server, add its address to the key; if you do not recognise it, rotate the key.",
|
|
35
|
+
API_KEY_INVALID: "A request carried a key the API does not know. Check the environment of every server that calls the API.",
|
|
36
|
+
API_KEY_REVOKED: "A request carried a revoked key: one that was replaced, revoked by a person, or reported as found in a public place. Put the current key on every server.",
|
|
37
|
+
API_KEY_EXPIRED: "A request carried a key past its end of life. Make a new key and put it on every server.",
|
|
38
|
+
PROPERTY_REQUIRED: "A company key called a hotel route without naming the hotel. Use zs.forProperty(id), or send the X-ZS-Property header.",
|
|
39
|
+
PROPERTY_NOT_FOUND: "A request named a hotel this key may not act on (its owner ended your access, or the id is wrong). zs.properties.list() names the hotels the key reaches.",
|
|
40
|
+
ARI_NOT_AUTHORITATIVE: "A call went to a hotel that is not live yet (your software is not its source of truth), so nothing was written. zs.readiness.get() says what is missing; send values ahead with { beforeGoLive: true }, then zs.readiness.goLive().",
|
|
41
|
+
NOT_READY: "zs.readiness.goLive() was called before every readiness check passed. zs.readiness.get() lists the checks with what to do about each; call goLive again once they pass.",
|
|
42
|
+
LIVE_KEY_REQUIRED: "A connect link was asked for with a test key. A link connects a real booking site, so it is made with a live key; a sandbox has none.",
|
|
43
|
+
KEY_LIMIT: "The hotel already holds as many active keys as a hotel may. Revoke one you no longer use (zs.hotelKeys.revoke), then mint.",
|
|
44
|
+
SUPPORT_TICKET_CLOSED: "A message was sent to a closed support ticket. Open a new ticket and name the old one.",
|
|
45
|
+
WRITES_SUSPENDED: "ZimmerStack has suspended this integration's writes. Write to support@zimmerstack.com; the reason is on zs.sync.get().",
|
|
46
|
+
IDEMPOTENCY_KEY_REUSED: "One idempotency key was sent with two different requests. Make a new key for every new write; reuse a key only to send the same write again.",
|
|
47
|
+
IDEMPOTENCY_IN_FLIGHT: "The same write was sent again while the first was still running. Wait a moment and send it once; the package does.",
|
|
48
|
+
RATE_OUT_OF_BAND: "A price was outside the band the hotel allows around its standing price. It is a guard against a typing slip: check the price, never split the change into steps.",
|
|
49
|
+
CHANNEL_MANAGER_ERROR: "The channel manager did not take a change, so nothing was changed. Try once more later; if it repeats, write to support@zimmerstack.com with a request id.",
|
|
50
|
+
TOO_MANY_UPDATES: "One request carried more updates than a request may. zs.grid.save and the set methods split a large write for you.",
|
|
51
|
+
TOO_MANY_CELLS: "One request named more nights than a request may. zs.grid.save and the set methods split a large write for you.",
|
|
52
|
+
};
|
|
53
|
+
const plural = (n, one, many = one + "s") => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
|
|
54
|
+
const ago = (iso, now) => {
|
|
55
|
+
const t = iso ? Date.parse(iso) : NaN;
|
|
56
|
+
if (Number.isNaN(t))
|
|
57
|
+
return "at an unknown time";
|
|
58
|
+
const ms = now.getTime() - t;
|
|
59
|
+
return ms < 60_000 ? "just now" : `${aboutHowLong(ms)} ago`;
|
|
60
|
+
};
|
|
61
|
+
const list = (items, max = 4) => (items.length <= max ? items.join(", ") : `${items.slice(0, max).join(", ")} and ${items.length - max} more`);
|
|
62
|
+
/** Why a read did not answer, as a finding. A refusal for a missing scope is information, not a fault. */
|
|
63
|
+
function refusalFinding(check, what, err, propertyId) {
|
|
64
|
+
const hotel = propertyId === undefined ? {} : { propertyId };
|
|
65
|
+
if (err instanceof ZimmerStackError) {
|
|
66
|
+
if (err.code === "SCOPE_MISSING")
|
|
67
|
+
return { level: "info", check, message: `${what} was not read: this key does not hold the scope that route needs.`, ...hotel };
|
|
68
|
+
if (err.code === "RATE_LIMITED") {
|
|
69
|
+
return { level: "attention", check, message: `${what} was not read: the ${err.scope ?? "request"} budget is used up right now.`, action: `It has room again in ${aboutHowLong((err.retryAfterSeconds ?? 60) * 1000)}. Run the doctor again then.`, ...hotel };
|
|
70
|
+
}
|
|
71
|
+
return { level: "attention", check, message: `${what} was not read: ${err.code}${err.status ? ` (${err.status})` : ""}. ${err.message}`, ...hotel };
|
|
72
|
+
}
|
|
73
|
+
return { level: "attention", check, message: `${what} was not read: ${err instanceof Error ? err.name : "an unexpected error"}.`, ...hotel };
|
|
74
|
+
}
|
|
75
|
+
function budgetRows(limits) {
|
|
76
|
+
const propertyId = limits.key.propertyId;
|
|
77
|
+
return [...limits.budgets, ...(limits.shield?.budgets ?? [])].map((b) => ({
|
|
78
|
+
propertyId,
|
|
79
|
+
scope: b.scope,
|
|
80
|
+
per: b.per,
|
|
81
|
+
window: b.window,
|
|
82
|
+
quota: b.quota,
|
|
83
|
+
unit: b.unit,
|
|
84
|
+
used: b.used,
|
|
85
|
+
remaining: b.remaining,
|
|
86
|
+
resetSeconds: b.resetSeconds,
|
|
87
|
+
percentUsed: b.used === null || b.quota <= 0 ? null : Math.min(100, Math.round((b.used / b.quota) * 100)),
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
function limitFindings(limits, rows, propertyId) {
|
|
91
|
+
const out = [];
|
|
92
|
+
const hotel = propertyId === undefined ? {} : { propertyId };
|
|
93
|
+
for (const b of rows) {
|
|
94
|
+
if (b.remaining === 0) {
|
|
95
|
+
out.push({
|
|
96
|
+
level: "attention",
|
|
97
|
+
check: "limits",
|
|
98
|
+
message: `The ${b.scope} budget is used up: ${b.quota.toLocaleString("en-US")} ${b.unit} per ${b.per}, ${b.window}.`,
|
|
99
|
+
action: `It has room again in ${aboutHowLong((b.resetSeconds ?? 60) * 1000)}. The package waits by itself for a minute's budget; for an hour's or a day's, send less: only the nights that changed.`,
|
|
100
|
+
...hotel,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
else if (b.percentUsed !== null && b.percentUsed >= NEARLY_FULL) {
|
|
104
|
+
out.push({ level: "info", check: "limits", message: `The ${b.scope} budget is ${b.percentUsed}% used (${(b.used ?? 0).toLocaleString("en-US")} of ${b.quota.toLocaleString("en-US")} ${b.unit}, ${b.window}).`, ...hotel });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const counted = rows.filter((b) => b.percentUsed !== null);
|
|
108
|
+
if (counted.length > 0 && out.length === 0) {
|
|
109
|
+
const fullest = counted.reduce((a, b) => ((b.percentUsed ?? 0) > (a.percentUsed ?? 0) ? b : a));
|
|
110
|
+
out.push({ level: "ok", check: "limits", message: `${plural(rows.length, "budget")} read; the fullest is ${fullest.scope} at ${fullest.percentUsed}%.`, ...hotel });
|
|
111
|
+
}
|
|
112
|
+
const standing = limits.shield?.standing;
|
|
113
|
+
if (standing && standing.level !== "CLEAR") {
|
|
114
|
+
const until = standing.until ? ` until ${standing.until}` : "";
|
|
115
|
+
out.push(standing.level === "WATCH"
|
|
116
|
+
? { level: "info", check: "limits", message: `This integration is being watched${standing.reason ? `: ${standing.reason}` : ""}. Nothing is refused.`, ...hotel }
|
|
117
|
+
: {
|
|
118
|
+
level: "attention",
|
|
119
|
+
check: "limits",
|
|
120
|
+
message: standing.level === "PAUSED"
|
|
121
|
+
? `This integration's writes are paused${until}${standing.reason ? `: ${standing.reason}` : ""}. Only writes that close inventory are accepted.`
|
|
122
|
+
: `This integration's writes are suspended${standing.reason ? `: ${standing.reason}` : ""}. Every write is refused until ZimmerStack releases it.`,
|
|
123
|
+
action: standing.level === "PAUSED" ? "A pause with an end lifts by itself. Fix what the reason names; send closes on their own if a night must stop selling now." : "Write to support@zimmerstack.com with the hotel's id.",
|
|
124
|
+
...hotel,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
/** Is something wrong on ZimmerStack's side: the open incidents that touch this key's hotels, and the ones that ended in the last week. */
|
|
130
|
+
function statusFindings(status, now) {
|
|
131
|
+
const out = [];
|
|
132
|
+
const whose = (p) => (p.all ? "every hotel" : `${plural(p.count, "hotel")} of yours${p.ids.length ? ` (${list(p.ids.map((id) => `#${id}`), 6)})` : ""}`);
|
|
133
|
+
for (const incident of status.incidents.open) {
|
|
134
|
+
const said = incident.updates[0]?.message;
|
|
135
|
+
out.push({
|
|
136
|
+
// An incident is ZimmerStack's to fix, not yours: it is a note, and the command still exits 0 for it.
|
|
137
|
+
level: "info",
|
|
138
|
+
check: "status",
|
|
139
|
+
message: `ZimmerStack has an open incident on ${incident.componentName} (${incident.severity.replace(/_/g, " ")}, ${incident.status}), started ${ago(incident.startedAt, now)}, touching ${whose(incident.properties)}: ${incident.title}.${said ? ` Latest: ${said}` : ""}`,
|
|
140
|
+
action: "This is on ZimmerStack's side: there is nothing to fix in your integration. Keep what your people changed and send it when the incident is resolved (platform.incident.resolved, or zs.status.get()). Do not resend everything.",
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
for (const incident of status.incidents.recent) {
|
|
144
|
+
out.push({ level: "info", check: "status", message: `An incident on ${incident.componentName} ended ${ago(incident.resolvedAt ?? incident.updatedAt, now)}: ${incident.title}.` });
|
|
145
|
+
}
|
|
146
|
+
if (status.incidents.open.length === 0) {
|
|
147
|
+
out.push({
|
|
148
|
+
level: "ok",
|
|
149
|
+
check: "status",
|
|
150
|
+
message: `ZimmerStack reports no open incident that touches your hotels${status.incidents.recent.length ? "" : ", and none in the last 7 days"}.`,
|
|
151
|
+
// "operational" is a person's word, not a monitor's: say so, so a problem nobody reported yet is still reported.
|
|
152
|
+
action: status.incidents.recent.length ? undefined : "An incident is recorded by ZimmerStack's staff. If something looks wrong on its side and none is listed, write to support@zimmerstack.com or open a ticket (zs.supportTickets.create).",
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (status.page)
|
|
156
|
+
out.push({ level: "info", check: "status", message: `The status page: ${status.page}` });
|
|
157
|
+
return out.map((f) => (f.action === undefined ? { level: f.level, check: f.check, message: f.message } : f));
|
|
158
|
+
}
|
|
159
|
+
/** A hotel that is not live yet: what its readiness report says, check by check. */
|
|
160
|
+
function readinessFindings(who, report, propertyId) {
|
|
161
|
+
const failing = report.checks.filter((c) => !c.passed);
|
|
162
|
+
const out = [
|
|
163
|
+
{
|
|
164
|
+
level: "attention",
|
|
165
|
+
check: "hotels",
|
|
166
|
+
message: `${who} is not live yet: your software is not its source of truth, so what you send is refused (ARI_NOT_AUTHORITATIVE) unless the call says beforeGoLive.`,
|
|
167
|
+
action: report.ready
|
|
168
|
+
? "Every readiness check passed. zs.forProperty(id).readiness.goLive() switches it on: call it when a person has decided to."
|
|
169
|
+
: `${plural(failing.length, "readiness check")} of ${report.checks.length} ${failing.length === 1 ? "has" : "have"} not passed (below). Do what each says, read zs.readiness.get() again, then zs.readiness.goLive().`,
|
|
170
|
+
propertyId,
|
|
171
|
+
},
|
|
172
|
+
];
|
|
173
|
+
for (const check of failing) {
|
|
174
|
+
out.push({ level: "attention", check: "hotels", message: `${who}, readiness check ${check.id}: ${check.summary}`, ...(check.action ? { action: check.action } : {}), propertyId });
|
|
175
|
+
}
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
/** One night, explained: the API's own sentences, and the facts in it that need a person. */
|
|
179
|
+
function nightFindings(who, night, now, propertyId) {
|
|
180
|
+
const out = [];
|
|
181
|
+
const about = `${who}, ${night.roomType.name} (#${night.roomType.id}) on ${night.date}`;
|
|
182
|
+
for (const sentence of night.summary)
|
|
183
|
+
out.push({ level: "info", check: "night", message: `${about}: ${sentence}`, propertyId });
|
|
184
|
+
const lastPush = night.count.pushes[0];
|
|
185
|
+
if (lastPush && lastPush.outcome === "refused") {
|
|
186
|
+
out.push({
|
|
187
|
+
level: "attention",
|
|
188
|
+
check: "night",
|
|
189
|
+
message: `${about}: the last send of this night's room count was refused by the channel manager ${ago(lastPush.at, now)}${lastPush.words ? `, in its words: ${lastPush.words}` : ""}.`,
|
|
190
|
+
action: "Send the count again (zs.availability.set). If it is refused again, the words say why: fix that at the hotel's booking site or write to support@zimmerstack.com.",
|
|
191
|
+
propertyId,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
for (const plan of night.plans) {
|
|
195
|
+
const name = `${plan.name} (#${plan.ratePlanId})`;
|
|
196
|
+
if (plan.send.held) {
|
|
197
|
+
out.push({
|
|
198
|
+
level: "attention",
|
|
199
|
+
check: "night",
|
|
200
|
+
message: `${about}: the value sent for ${name} was refused by the channel manager ${ago(plan.send.held.since, now)} and is held, not sent again. Its words: ${plan.send.held.words}`,
|
|
201
|
+
action: "Send a different value for that night. The same value is answered as held.",
|
|
202
|
+
propertyId,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
if (plan.reach === "not-linked") {
|
|
206
|
+
out.push({ level: "attention", check: "night", message: `${about}: ${name} is not on the channel manager, so nothing sent for it reaches a booking site.`, action: "Save the rate plan again (zs.ratePlans.save) so it is linked, then send the night again.", propertyId });
|
|
207
|
+
}
|
|
208
|
+
else if (plan.reach === "not-mapped") {
|
|
209
|
+
out.push({
|
|
210
|
+
level: "attention",
|
|
211
|
+
check: "night",
|
|
212
|
+
message: `${about}: no connected booking site sells ${name}, so a price or a stop-sell sent for it changes nothing a guest sees${night.channels.seenAt ? ` (the connections were last read ${ago(night.channels.seenAt, now)})` : ""}.`,
|
|
213
|
+
action: "A person matches the plan to the booking site's rate (a connect link, the partner portal or the hotel's Channels app). A plan matched today reads mapped after the next nightly read.",
|
|
214
|
+
propertyId,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const seen = [night.count.channelManager.seenAt, ...night.plans.flatMap((p) => [p.price.channelManager.seenAt, p.stayRules.channelManager.seenAt])];
|
|
219
|
+
out.push({
|
|
220
|
+
level: "info",
|
|
221
|
+
check: "night",
|
|
222
|
+
message: `${about}: this is ZimmerStack's record and the channel manager's copy as last seen${seen.some((at) => at === null) ? " (part of this night was never read back from it, so that part is not known)" : ""}. It is not a booking site's own screen.${night.count.lastSent === null && night.plans.every((p) => p.price.lastSent === null && p.stayRules.lastSent === null) ? ` What your software last sent was not found in the ${plural(night.searched.batches, "write")} looked through: values are kept only for writes made since this was added.` : ""}`,
|
|
223
|
+
propertyId,
|
|
224
|
+
});
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
async function requestFindings(zs, now, signal) {
|
|
228
|
+
const since = new Date(now.getTime() - DAY_MS).toISOString();
|
|
229
|
+
const refused = [];
|
|
230
|
+
let more = false;
|
|
231
|
+
let cursor;
|
|
232
|
+
// At most five pages of refusals (1,000 requests): enough to group a bad day, and a bounded number of reads.
|
|
233
|
+
for (let page = 0; page < 5; page++) {
|
|
234
|
+
const answer = await zs.requests.list({ since, status: "errors", limit: 200, cursor }, { signal });
|
|
235
|
+
refused.push(...answer.items);
|
|
236
|
+
more = answer.more;
|
|
237
|
+
cursor = answer.more ? (answer.nextCursor ?? undefined) : undefined;
|
|
238
|
+
if (!cursor)
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
const out = [];
|
|
242
|
+
if (refused.length === 0)
|
|
243
|
+
out.push({ level: "ok", check: "requests", message: "No request made with this key was refused in the last 24 hours." });
|
|
244
|
+
const groups = new Map();
|
|
245
|
+
for (const r of refused) {
|
|
246
|
+
const reason = r.errorCode ?? `HTTP ${r.status}`;
|
|
247
|
+
groups.set(reason, [...(groups.get(reason) ?? []), r]);
|
|
248
|
+
}
|
|
249
|
+
for (const [reason, items] of [...groups].sort((a, b) => b[1].length - a[1].length)) {
|
|
250
|
+
const last = items[0]; // the log is newest first
|
|
251
|
+
const routes = [...new Set(items.map((r) => `${r.method} ${r.route}`))];
|
|
252
|
+
const recent = now.getTime() - Date.parse(last.at) < HOUR_MS;
|
|
253
|
+
const fault = items.some((r) => r.status >= 500);
|
|
254
|
+
out.push({
|
|
255
|
+
// Still happening in the last hour, or a fault on our side: look now. Older than that: it may be fixed already.
|
|
256
|
+
level: recent || fault ? "attention" : "info",
|
|
257
|
+
check: "requests",
|
|
258
|
+
message: `${reason}: ${plural(items.length, "request")} refused in the last 24 hours${more ? " (and more)" : ""}, the last ${ago(last.at, now)}, on ${list(routes)}.${last.requestId ? ` Last request id: ${last.requestId}.` : ""}`,
|
|
259
|
+
action: REFUSAL_ADVICE[reason] ?? (fault ? "That is a fault on ZimmerStack's side. If it repeats, write to support@zimmerstack.com and quote the request id." : "Look the code up: https://docs.zimmerstack.com/guides/errors"),
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
// The newest requests of any status, for the addresses they came from: an address that is not yours is the first sign of a leaked key.
|
|
263
|
+
const newest = await zs.requests.list({ limit: 200 }, { signal });
|
|
264
|
+
const addresses = [...new Set(newest.items.map((r) => r.address).filter((a) => Boolean(a)))];
|
|
265
|
+
if (addresses.length > 0) {
|
|
266
|
+
out.push({
|
|
267
|
+
level: "info",
|
|
268
|
+
check: "requests",
|
|
269
|
+
message: `The newest ${plural(newest.items.length, "request")} came from ${plural(addresses.length, "address", "addresses")}: ${list(addresses, 6)}.`,
|
|
270
|
+
action: "If one of them is not a server of yours, rotate the key now.",
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
return out;
|
|
274
|
+
}
|
|
275
|
+
function endpointFindings(endpoint, failures, lastStatus, now) {
|
|
276
|
+
const out = [];
|
|
277
|
+
let host = "an address that does not parse";
|
|
278
|
+
try {
|
|
279
|
+
host = new URL(endpoint.url).host;
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
/* keep the words */
|
|
283
|
+
}
|
|
284
|
+
const name = `Endpoint ${endpoint.id} (${host})`;
|
|
285
|
+
if (endpoint.status === "SUSPENDED") {
|
|
286
|
+
out.push({
|
|
287
|
+
level: "attention",
|
|
288
|
+
check: "webhooks",
|
|
289
|
+
message: `${name} is suspended${endpoint.statusReason ? `: ${endpoint.statusReason}` : ""}. Events sent while it is suspended are dropped, not held.`,
|
|
290
|
+
action: "Fix the receiver, resume the endpoint, then recover since the moment it stopped (zs.webhookEndpoints.recover), or read the event log from your last sequence (zs.events.all).",
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
else if (endpoint.status === "PAUSED") {
|
|
294
|
+
out.push({ level: "info", check: "webhooks", message: `${name} is paused. Its events are held and go out, oldest first, when it is resumed.`, action: "Resume it when your receiver is ready (zs.webhookEndpoints.resume)." });
|
|
295
|
+
}
|
|
296
|
+
else if (endpoint.health.state === "failing") {
|
|
297
|
+
out.push({
|
|
298
|
+
level: "attention",
|
|
299
|
+
check: "webhooks",
|
|
300
|
+
message: `${name} is failing: ${plural(endpoint.health.consecutiveFailures, "delivery", "deliveries")} in a row${endpoint.health.failingSince ? `, since ${ago(endpoint.health.failingSince, now)}` : ""}${endpoint.health.lastErrorMessage ? `. Last error: ${endpoint.health.lastErrorMessage}` : ""}.`,
|
|
301
|
+
action: lastStatus === 400 || lastStatus === 401 || lastStatus === 403
|
|
302
|
+
? `Your receiver answered ${lastStatus}: it is refusing the delivery, most often because the signature did not verify. Verify the RAW body (before any JSON parsing) with this endpoint's current secret; after a rotation the new secret must be in place within 24 hours.`
|
|
303
|
+
: "Your receiver must be reachable on a public https address and answer 2xx within 10 seconds. Answer first, do the work afterwards. An endpoint that fails for 72 hours is suspended.",
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
else if (endpoint.health.lastSuccessAt) {
|
|
307
|
+
out.push({ level: "ok", check: "webhooks", message: `${name} is answering: its last delivery was accepted ${ago(endpoint.health.lastSuccessAt, now)}.` });
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
out.push({ level: "info", check: "webhooks", message: `${name} has not accepted a delivery yet.`, action: "Send it a test (zs.webhookEndpoints.test) and read what your receiver answered in the delivery log." });
|
|
311
|
+
}
|
|
312
|
+
if (endpoint.previousSecretExpiresAt && Date.parse(endpoint.previousSecretExpiresAt) > now.getTime()) {
|
|
313
|
+
out.push({ level: "info", check: "webhooks", message: `${name} is in a secret rotation: deliveries are signed with both secrets until ${endpoint.previousSecretExpiresAt}.`, action: "Put the new secret on your receiver before then." });
|
|
314
|
+
}
|
|
315
|
+
if (endpoint.status === "ACTIVE" && endpoint.health.state !== "failing" && failures.length > 0) {
|
|
316
|
+
const f = failures[0];
|
|
317
|
+
out.push({
|
|
318
|
+
level: "info",
|
|
319
|
+
check: "webhooks",
|
|
320
|
+
message: `${name} has ${plural(failures.length, "failed delivery", "failed deliveries")} in its log; the newest is a ${f.eventType} of ${ago(f.occurredAt, now)}${f.lastError ? ` (${f.lastError})` : ""}.`,
|
|
321
|
+
action: "Send one again with zs.webhookEndpoints.deliveries.redeliver, or read the event log from your last sequence: nothing is lost.",
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
if (!endpoint.eventTypes.some((t) => t.startsWith("channel.booking."))) {
|
|
325
|
+
out.push({ level: "info", check: "webhooks", message: `${name} does not listen to OTA bookings (it takes: ${list(endpoint.eventTypes)}).` });
|
|
326
|
+
}
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
async function webhookFindings(zs, keyKind, now, signal) {
|
|
330
|
+
if (keyKind === "hotel") {
|
|
331
|
+
return [{ level: "info", check: "webhooks", message: "A hotel's own key cannot read webhook endpoints.", action: "The hotel's owner sees them, with every delivery, under Admin → Developers → Webhooks." }];
|
|
332
|
+
}
|
|
333
|
+
let endpoints;
|
|
334
|
+
try {
|
|
335
|
+
endpoints = (await zs.webhookEndpoints.list({ signal })).items;
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
if (err instanceof ZimmerStackError && err.code === "SCOPE_MISSING") {
|
|
339
|
+
return [{ level: "info", check: "webhooks", message: "This key does not hold the scope webhooks:manage, so the doctor cannot look at your webhook endpoints.", action: `See them in ${PORTAL}, or make a company key with "Also manage webhooks" ticked.` }];
|
|
340
|
+
}
|
|
341
|
+
return [refusalFinding("webhooks", "The webhook endpoints", err)];
|
|
342
|
+
}
|
|
343
|
+
if (endpoints.length === 0) {
|
|
344
|
+
return [{ level: "info", check: "webhooks", message: "No webhook endpoint of this key's mode exists: your software hears of bookings only when it reads the event log.", action: "Create one with zs.webhookEndpoints.create, or read zs.events.all on a schedule." }];
|
|
345
|
+
}
|
|
346
|
+
const out = [];
|
|
347
|
+
for (const endpoint of endpoints) {
|
|
348
|
+
let failures = [];
|
|
349
|
+
let lastStatus = null;
|
|
350
|
+
try {
|
|
351
|
+
failures = (await zs.webhookEndpoints.deliveries.list(endpoint.id, { status: "FAILED", limit: 5 }, { signal })).items;
|
|
352
|
+
const newest = failures[0];
|
|
353
|
+
if (newest && endpoint.health.state === "failing") {
|
|
354
|
+
// What the receiver answered on the newest failed delivery: a 401 reads very differently from a timeout.
|
|
355
|
+
const detail = await zs.webhookEndpoints.deliveries.get(endpoint.id, newest.id, { signal });
|
|
356
|
+
lastStatus = detail.attempts_log[detail.attempts_log.length - 1]?.responseStatus ?? null;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
out.push(refusalFinding("webhooks", `Endpoint ${endpoint.id}'s delivery log`, err));
|
|
361
|
+
}
|
|
362
|
+
out.push(...endpointFindings(endpoint, failures, lastStatus, now));
|
|
363
|
+
}
|
|
364
|
+
return out;
|
|
365
|
+
}
|
|
366
|
+
async function hotelFindings(zs, hotel, keyKind, now, signal, budgets) {
|
|
367
|
+
const out = [];
|
|
368
|
+
const propertyId = hotel.id;
|
|
369
|
+
const who = `${hotel.name} (#${hotel.id})`;
|
|
370
|
+
/* which scopes, and whether its writes go anywhere */
|
|
371
|
+
let scopes = [];
|
|
372
|
+
let writesRefused = false;
|
|
373
|
+
try {
|
|
374
|
+
const property = await zs.property.get({ signal });
|
|
375
|
+
scopes = property.scopes ?? [];
|
|
376
|
+
const may = scopes.map((s) => SCOPE_DOES[s] ?? s);
|
|
377
|
+
out.push({
|
|
378
|
+
level: "info",
|
|
379
|
+
check: "hotels",
|
|
380
|
+
message: `${who}${property.sandbox ? ", a sandbox" : ""}: this key may ${may.length ? list(may, 12) : "only read which hotel it is for"}.`,
|
|
381
|
+
propertyId,
|
|
382
|
+
});
|
|
383
|
+
if (!property.sandbox && scopes.includes("ari:write") && property.ariAuthoritative === false) {
|
|
384
|
+
writesRefused = true;
|
|
385
|
+
try {
|
|
386
|
+
// No scope is needed to read it, and it calls no channel.
|
|
387
|
+
out.push(...readinessFindings(who, await zs.readiness.get({ signal }), propertyId));
|
|
388
|
+
}
|
|
389
|
+
catch (err) {
|
|
390
|
+
out.push({
|
|
391
|
+
level: "attention",
|
|
392
|
+
check: "hotels",
|
|
393
|
+
message: `${who} is not live yet: your software is not its source of truth, so what you send is refused (ARI_NOT_AUTHORITATIVE).`,
|
|
394
|
+
action: "zs.readiness.get() says what is missing and zs.readiness.goLive() switches it on.",
|
|
395
|
+
propertyId,
|
|
396
|
+
});
|
|
397
|
+
out.push(refusalFinding("hotels", `${who}'s readiness report`, err, propertyId));
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (property.products && property.products.channelManager === false) {
|
|
401
|
+
out.push({ level: "info", check: "hotels", message: `${who} is not on the channel manager yet.`, action: "The first room type you save for it (zs.roomTypes.save) puts it there.", propertyId });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
catch (err) {
|
|
405
|
+
out.push(refusalFinding("hotels", `${who}'s details`, err, propertyId));
|
|
406
|
+
}
|
|
407
|
+
/* every budget */
|
|
408
|
+
try {
|
|
409
|
+
const limits = await zs.limits.get({ signal });
|
|
410
|
+
const rows = budgetRows(limits);
|
|
411
|
+
budgets.push(...rows);
|
|
412
|
+
out.push(...limitFindings(limits, rows, propertyId));
|
|
413
|
+
}
|
|
414
|
+
catch (err) {
|
|
415
|
+
out.push(refusalFinding("limits", `${who}'s budgets`, err, propertyId));
|
|
416
|
+
}
|
|
417
|
+
/* how far what was sent has travelled, and what the last nightly read found */
|
|
418
|
+
if (scopes.includes("ari:read")) {
|
|
419
|
+
try {
|
|
420
|
+
const sync = await zs.sync.get({ signal });
|
|
421
|
+
const before = out.length;
|
|
422
|
+
if (sync.inventory.state === "OUT_OF_SYNC") {
|
|
423
|
+
out.push({
|
|
424
|
+
level: "attention",
|
|
425
|
+
check: "sync",
|
|
426
|
+
message: `${who}: room counts are not reaching the channels${sync.inventory.outOfSyncSince ? `, since ${ago(sync.inventory.outOfSyncSince, now)}` : ""}${sync.inventory.lastError ? `. Last error: ${sync.inventory.lastError}` : ""}.`,
|
|
427
|
+
action: "ZimmerStack keeps trying and nothing you sent is lost. If it has lasted more than an hour, write to support@zimmerstack.com with the hotel's id.",
|
|
428
|
+
propertyId,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
else if (sync.inventory.state === "PENDING") {
|
|
432
|
+
out.push({ level: "info", check: "sync", message: `${who}: ${plural(sync.inventory.pendingCells, "room count")} on the way to the channels.`, propertyId });
|
|
433
|
+
}
|
|
434
|
+
else if (sync.inventory.state === "DISABLED" && !writesRefused && !sync.sandbox) {
|
|
435
|
+
out.push({ level: "info", check: "sync", message: `${who}: room counts are not being sent to any channel.`, action: "That is expected until a booking site is connected and selling.", propertyId });
|
|
436
|
+
}
|
|
437
|
+
if (sync.rates.parkedCells > 0) {
|
|
438
|
+
out.push({
|
|
439
|
+
level: "attention",
|
|
440
|
+
check: "sync",
|
|
441
|
+
message: `${who}: ${plural(sync.rates.parkedCells, "price or stay-rule night")} were refused by the channel manager and are held: they are not on sale as you sent them.`,
|
|
442
|
+
action: "Send a corrected value for those nights. The batch that carried them reads failed (zs.batches.get), and channel.sync.alert named the refusal.",
|
|
443
|
+
propertyId,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
const erroredAfterLastPush = sync.rates.lastErrorAt && (!sync.rates.lastPushAt || Date.parse(sync.rates.lastErrorAt) > Date.parse(sync.rates.lastPushAt));
|
|
447
|
+
if (erroredAfterLastPush) {
|
|
448
|
+
out.push({
|
|
449
|
+
level: "attention",
|
|
450
|
+
check: "sync",
|
|
451
|
+
message: `${who}: the last send of prices failed ${ago(sync.rates.lastErrorAt, now)}${sync.rates.lastError ? `: ${sync.rates.lastError}` : ""}.`,
|
|
452
|
+
action: "ZimmerStack retries by itself. If the newest pending batch stays pending for more than a few minutes, write to support@zimmerstack.com.",
|
|
453
|
+
propertyId,
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
else if (sync.rates.dirtyCells > 0) {
|
|
457
|
+
out.push({ level: "info", check: "sync", message: `${who}: ${plural(sync.rates.dirtyCells, "price or stay-rule night")} on the way to the channels.`, propertyId });
|
|
458
|
+
}
|
|
459
|
+
if ((sync.rates.driftCells ?? 0) > 0) {
|
|
460
|
+
out.push({
|
|
461
|
+
level: "info",
|
|
462
|
+
check: "sync",
|
|
463
|
+
message: `${who}: the last nightly read found ${plural(sync.rates.driftCells ?? 0, "night")} where the channel manager held something other than what you sent${sync.rates.driftSeenAt ? ` (read ${ago(sync.rates.driftSeenAt, now)})` : ""}. Someone changed a price or a stay rule on the channel manager's side.`,
|
|
464
|
+
action: "Your value is sent again by itself unless the hotel switched that repair off; channel.drift.detected named the nights and channel.drift.healed follows when a later read agrees. If the number is still here tomorrow, send those nights again.",
|
|
465
|
+
propertyId,
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
const unreachable = sync.newestPendingBatch?.unreachable ?? [];
|
|
469
|
+
if (unreachable.length > 0) {
|
|
470
|
+
out.push({
|
|
471
|
+
level: "attention",
|
|
472
|
+
check: "sync",
|
|
473
|
+
message: `${who}: the newest write named ${plural(unreachable.length, "room type or rate plan", "room types or rate plans")} that reach no channel, so those values were written and sent nowhere.`,
|
|
474
|
+
action: "zs.catalog.get() shows each one's sync state. Save the room type or rate plan again (zs.roomTypes.save, zs.ratePlans.save) so it is linked, then send the nights again.",
|
|
475
|
+
propertyId,
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
if (out.length === before)
|
|
479
|
+
out.push({ level: "ok", check: "sync", message: `${who}: everything you sent is ${sync.sandbox ? "in the sandbox's record" : "on the channels"}, and the last nightly read agreed with it.`, propertyId });
|
|
480
|
+
const channels = await zs.channels.list({ signal });
|
|
481
|
+
const issues = [...channels.channels.flatMap((c) => c.openIssues.map((i) => ({ ...i, on: c.kind }))), ...channels.propertyIssues.map((i) => ({ ...i, on: "the hotel" }))];
|
|
482
|
+
for (const issue of issues) {
|
|
483
|
+
out.push({
|
|
484
|
+
level: "attention",
|
|
485
|
+
check: "sync",
|
|
486
|
+
message: `${who}: an open channel problem on ${issue.on}: ${issue.event}, raised ${ago(issue.raisedAt, now)}.`,
|
|
487
|
+
action: "The hotel sees it on its Channels screen with what to do. channel.sync.recovered is sent when it ends.",
|
|
488
|
+
propertyId,
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
if (!sync.sandbox && channels.channels.length === 0) {
|
|
492
|
+
out.push({ level: "info", check: "sync", message: `${who}: no booking site is connected yet, so nothing you send is on sale anywhere.`, action: keyKind === "company" ? "Send the hotel a one-time connect link (zs.connectLinks.create, scope channels:connect), or connect one on the hotel's page in the partner portal." : "Connect one in the Channels app (https://channels.zimmerstack.com).", propertyId });
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
catch (err) {
|
|
496
|
+
out.push(refusalFinding("sync", `${who}'s sync state`, err, propertyId));
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
out.push({ level: "info", check: "sync", message: `${who}: the sync state was not read, because this key does not hold ari:read.`, propertyId });
|
|
501
|
+
}
|
|
502
|
+
return out;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Run every check and return what was found. Reads only; never throws for something the API answered
|
|
506
|
+
* (that is a finding). `apiKey` defaults to the environment variable ZIMMERSTACK_CONNECT_KEY.
|
|
507
|
+
*
|
|
508
|
+
* @example
|
|
509
|
+
* const report = await diagnose();
|
|
510
|
+
* if (!report.ok) console.error(formatDoctorReport(report));
|
|
511
|
+
*/
|
|
512
|
+
export async function diagnose(options = {}) {
|
|
513
|
+
const now = options.now?.() ?? new Date();
|
|
514
|
+
const report = { ok: true, checkedAt: now.toISOString(), mode: null, keyKind: null, hotels: [], findings: [], budgets: [] };
|
|
515
|
+
const done = () => {
|
|
516
|
+
report.ok = !report.findings.some((f) => f.level === "attention");
|
|
517
|
+
return report;
|
|
518
|
+
};
|
|
519
|
+
const key = options.apiKey ?? (typeof process !== "undefined" && process.env ? process.env.ZIMMERSTACK_CONNECT_KEY : undefined);
|
|
520
|
+
/* 1. the key's shape, offline */
|
|
521
|
+
const shape = checkKey(key);
|
|
522
|
+
report.mode = shape.mode;
|
|
523
|
+
if (!shape.ok) {
|
|
524
|
+
report.findings.push({
|
|
525
|
+
level: "attention",
|
|
526
|
+
check: "key",
|
|
527
|
+
message: shape.message,
|
|
528
|
+
action: shape.problem === "empty"
|
|
529
|
+
? `Put the key in the environment variable ZIMMERSTACK_CONNECT_KEY on your server (or in the project's .env while you build). A software company makes one in ${PORTAL}; a hotel's owner under ${OWNER}.`
|
|
530
|
+
: "Nothing was sent. Copy the key again, whole, from where it was shown when it was made; a key is shown once, so if it is gone, make a new one.",
|
|
531
|
+
});
|
|
532
|
+
return done();
|
|
533
|
+
}
|
|
534
|
+
report.findings.push({ level: shape.format === "legacy" ? "info" : "ok", check: "key", message: shape.message });
|
|
535
|
+
let zs;
|
|
536
|
+
try {
|
|
537
|
+
// Short waits and one retry: a doctor that hangs is no help. Reads only, so a live key is fine anywhere.
|
|
538
|
+
zs = new ZimmerStack({ apiKey: key, fetch: options.fetch, baseUrl: options.baseUrl, timeoutMs: 20_000, maxRetries: 1, maxWaitSeconds: 15 });
|
|
539
|
+
}
|
|
540
|
+
catch (err) {
|
|
541
|
+
report.findings.push({ level: "attention", check: "key", message: err instanceof ZimmerStackUsageError ? err.message : "The client could not be made with this key." });
|
|
542
|
+
return done();
|
|
543
|
+
}
|
|
544
|
+
/* 2. does it answer, and whose is it */
|
|
545
|
+
let hotels;
|
|
546
|
+
try {
|
|
547
|
+
const listed = await zs.properties.list({ signal: options.signal });
|
|
548
|
+
report.keyKind = listed.keyKind === "company" ? "company" : "hotel";
|
|
549
|
+
hotels = listed.properties.map((p) => ({ id: p.id, name: p.name, sandbox: p.sandbox === true }));
|
|
550
|
+
report.findings.push({
|
|
551
|
+
level: "ok",
|
|
552
|
+
check: "reach",
|
|
553
|
+
message: report.keyKind === "company"
|
|
554
|
+
? `The key answers. It is a company key that reaches ${plural(hotels.length, "hotel")}${hotels.length ? `: ${list(hotels.map((h) => `${h.name} (#${h.id})`), 6)}` : ""}.`
|
|
555
|
+
: `The key answers. It is the key of one hotel: ${hotels[0] ? `${hotels[0].name} (#${hotels[0].id})` : "which it could not name"}.`,
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
catch (err) {
|
|
559
|
+
const code = err instanceof ZimmerStackError ? err.code : "";
|
|
560
|
+
const say = (message, action) => report.findings.push({ level: "attention", check: "reach", message, action });
|
|
561
|
+
if (code === "API_KEY_INVALID")
|
|
562
|
+
say("The API does not know this key.", `It may belong to another environment, or have been deleted. Make a new one in ${PORTAL} (a hotel's owner: ${OWNER}).`);
|
|
563
|
+
else if (code === "API_KEY_REVOKED")
|
|
564
|
+
say("This key was revoked: replaced by a rotation whose 24 hours have passed, revoked by a person, or reported as found in a public place.", "Make a new key, put it in your server's settings (never in code), and check where the old one was kept.");
|
|
565
|
+
else if (code === "API_KEY_EXPIRED")
|
|
566
|
+
say("This key is past the end of life it was given.", "Make a new key, or ask whoever made it to give it a later end.");
|
|
567
|
+
else if (code === "IP_NOT_ALLOWED")
|
|
568
|
+
say("The key is valid, but this machine's address is not on its allowlist.", "Run the doctor from your server, or add this address to the key (the allowlist is edited without rotating).");
|
|
569
|
+
else if (code === "NETWORK_ERROR" || code === "TIMEOUT")
|
|
570
|
+
say("ZimmerStack could not be reached from this machine.", "Check that this machine may make outgoing https requests to api.zimmerstack.com (a proxy or a firewall), then run the doctor again.");
|
|
571
|
+
else
|
|
572
|
+
report.findings.push(refusalFinding("reach", "The key's hotels", err));
|
|
573
|
+
return done();
|
|
574
|
+
}
|
|
575
|
+
/* is something wrong on ZimmerStack's side: asked before anything about the hotels, because it explains much of what follows */
|
|
576
|
+
try {
|
|
577
|
+
report.findings.push(...statusFindings(await zs.status.get({ signal: options.signal }), now));
|
|
578
|
+
}
|
|
579
|
+
catch (err) {
|
|
580
|
+
report.findings.push(refusalFinding("status", "ZimmerStack's status", err));
|
|
581
|
+
}
|
|
582
|
+
/* 3 to 6. each hotel: scopes, budgets, sync */
|
|
583
|
+
const company = report.keyKind === "company";
|
|
584
|
+
let chosen = hotels;
|
|
585
|
+
if (company) {
|
|
586
|
+
if (options.propertyId !== undefined) {
|
|
587
|
+
chosen = hotels.filter((h) => h.id === options.propertyId);
|
|
588
|
+
if (chosen.length === 0) {
|
|
589
|
+
report.findings.push({ level: "attention", check: "hotels", message: `This key does not reach a hotel with the id ${options.propertyId}.`, action: "zs.properties.list() names the hotels it reaches. A hotel's owner can end a partner's access at any time." });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
else {
|
|
593
|
+
const max = Math.max(1, options.maxHotels ?? 5);
|
|
594
|
+
chosen = hotels.slice(0, max);
|
|
595
|
+
if (hotels.length > max)
|
|
596
|
+
report.findings.push({ level: "info", check: "hotels", message: `The first ${max} of ${hotels.length} hotels were looked at.`, action: "Name another with --property <id>." });
|
|
597
|
+
}
|
|
598
|
+
if (hotels.length === 0) {
|
|
599
|
+
report.findings.push({ level: "info", check: "hotels", message: "This company key reaches no hotel yet.", action: "Add one with zs.properties.create (scope properties:write) or in the partner portal; a test key makes a sandbox." });
|
|
600
|
+
// A company key's own budgets, with no hotel named.
|
|
601
|
+
try {
|
|
602
|
+
const limits = await zs.limits.get({ signal: options.signal });
|
|
603
|
+
const rows = budgetRows(limits);
|
|
604
|
+
report.budgets.push(...rows);
|
|
605
|
+
report.findings.push(...limitFindings(limits, rows, undefined));
|
|
606
|
+
}
|
|
607
|
+
catch (err) {
|
|
608
|
+
report.findings.push(refusalFinding("limits", "The key's budgets", err));
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
report.hotels = chosen;
|
|
613
|
+
for (const hotel of chosen) {
|
|
614
|
+
report.findings.push(...(await hotelFindings(company ? zs.forProperty(hotel.id) : zs, hotel, report.keyKind, now, options.signal, report.budgets)));
|
|
615
|
+
}
|
|
616
|
+
/* one night, when one was named */
|
|
617
|
+
if (options.night) {
|
|
618
|
+
const { roomTypeId, date, ratePlanId } = options.night;
|
|
619
|
+
const hotel = chosen.length === 1 ? chosen[0] : undefined;
|
|
620
|
+
if (!Number.isInteger(roomTypeId) || roomTypeId <= 0 || !/^\d{4}-\d{2}-\d{2}$/.test(String(date))) {
|
|
621
|
+
report.findings.push({ level: "attention", check: "night", message: "The night to explain needs a room type's numeric id and a date as YYYY-MM-DD.", action: "npx @zimmerstack/connect doctor --room-type 412 --night 2026-12-31 (zs.roomTypes.list() names the ids)." });
|
|
622
|
+
}
|
|
623
|
+
else if (!hotel) {
|
|
624
|
+
report.findings.push({ level: "attention", check: "night", message: "The night was not explained: a room type belongs to one hotel, and this key reaches more than one.", action: "Name the hotel too: --property <id>." });
|
|
625
|
+
}
|
|
626
|
+
else {
|
|
627
|
+
const who = `${hotel.name} (#${hotel.id})`;
|
|
628
|
+
try {
|
|
629
|
+
const night = await (company ? zs.forProperty(hotel.id) : zs).explain.night({ roomTypeId, date, ...(ratePlanId === undefined ? {} : { ratePlanId }) }, { signal: options.signal });
|
|
630
|
+
report.findings.push(...nightFindings(who, night, now, hotel.id));
|
|
631
|
+
}
|
|
632
|
+
catch (err) {
|
|
633
|
+
report.findings.push(refusalFinding("night", `${who}'s night ${date}`, err, hotel.id));
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
/* the last day's refused requests */
|
|
638
|
+
try {
|
|
639
|
+
report.findings.push(...(await requestFindings(zs, now, options.signal)));
|
|
640
|
+
}
|
|
641
|
+
catch (err) {
|
|
642
|
+
report.findings.push(refusalFinding("requests", "The key's request log", err));
|
|
643
|
+
}
|
|
644
|
+
/* the webhook endpoints */
|
|
645
|
+
report.findings.push(...(await webhookFindings(zs, report.keyKind, now, options.signal)));
|
|
646
|
+
return done();
|
|
647
|
+
}
|
|
648
|
+
const MARK = { ok: "ok ", info: "note ", attention: "FIX " };
|
|
649
|
+
const TITLES = {
|
|
650
|
+
key: "The key",
|
|
651
|
+
reach: "Does it answer",
|
|
652
|
+
status: "Is it ZimmerStack",
|
|
653
|
+
hotels: "Hotels and scopes",
|
|
654
|
+
limits: "Budgets",
|
|
655
|
+
requests: "Refused requests, last 24 hours",
|
|
656
|
+
webhooks: "Webhook endpoints",
|
|
657
|
+
sync: "Sync and drift",
|
|
658
|
+
night: "This night",
|
|
659
|
+
};
|
|
660
|
+
/** The report as text for a terminal: one section per check, each finding with what to do. Never contains the key. */
|
|
661
|
+
export function formatDoctorReport(report) {
|
|
662
|
+
const lines = [`ZimmerStack doctor · ${report.mode === "test" ? "sandbox key" : report.mode === "live" ? "live key" : "no usable key"}${report.keyKind ? ` · ${report.keyKind} key` : ""} · ${report.checkedAt}`, ""];
|
|
663
|
+
for (const check of Object.keys(TITLES)) {
|
|
664
|
+
const found = report.findings.filter((f) => f.check === check);
|
|
665
|
+
if (found.length === 0)
|
|
666
|
+
continue;
|
|
667
|
+
lines.push(TITLES[check]);
|
|
668
|
+
for (const f of found) {
|
|
669
|
+
lines.push(` ${MARK[f.level]}${f.message}`);
|
|
670
|
+
if (f.action)
|
|
671
|
+
lines.push(` → ${f.action}`);
|
|
672
|
+
}
|
|
673
|
+
if (check === "limits" && report.budgets.length > 0) {
|
|
674
|
+
lines.push(" Every budget (used of quota):");
|
|
675
|
+
for (const b of report.budgets) {
|
|
676
|
+
const fill = b.used === null ? "not counted on this route" : `${b.used.toLocaleString("en-US")} of ${b.quota.toLocaleString("en-US")} ${b.unit}${b.percentUsed === null ? "" : ` (${b.percentUsed}%)`}`;
|
|
677
|
+
lines.push(` ${b.propertyId === null ? "" : `#${b.propertyId} `}${b.scope}: ${fill} · ${b.window}, per ${b.per}`);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
lines.push("");
|
|
681
|
+
}
|
|
682
|
+
const attention = report.findings.filter((f) => f.level === "attention").length;
|
|
683
|
+
lines.push(attention === 0 ? "Nothing needs attention." : `${plural(attention, "thing")} ${attention === 1 ? "needs" : "need"} attention (marked FIX).`);
|
|
684
|
+
return lines.join("\n");
|
|
685
|
+
}
|