@blazeo.com/appointment-client 1.0.10 → 1.0.13

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.
@@ -0,0 +1,335 @@
1
+ import { useState } from "react";
2
+ import {
3
+ ensureBlazeoHttpReady,
4
+ fetchLeadByEmail,
5
+ fetchLeadDetails,
6
+ fetchLeadsByCompany,
7
+ } from "appointment-client";
8
+ import {
9
+ configureBlazeoFromEffective,
10
+ useBlazeoConnection,
11
+ } from "./BlazeoConnectionSettings.jsx";
12
+ import { mapBlazeoDemoError } from "./blazeoDemoError.js";
13
+
14
+ /** Browser `fetch` often surfaces blocked requests as TypeError "Failed to fetch" (e.g. CORS). */
15
+ function explainFetchFailure(err, configuredBaseUrl) {
16
+ const msg = err instanceof Error ? err.message : String(err);
17
+ const isNetwork =
18
+ msg === "Failed to fetch" ||
19
+ msg === "Load failed" ||
20
+ (err instanceof TypeError && (/fetch/i.test(msg) || /network/i.test(msg)));
21
+ if (!isNetwork) return mapBlazeoDemoError(msg);
22
+
23
+ const isRemote =
24
+ configuredBaseUrl &&
25
+ /^https?:\/\//i.test(configuredBaseUrl) &&
26
+ !/localhost|127\.0\.0\.1/i.test(configuredBaseUrl);
27
+
28
+ const proxyHint =
29
+ "Dev workaround (Vite proxy): create sample/.env.development with\n" +
30
+ " VITE_DEV_PROXY_TARGET=https://YOUR_API_ORIGIN\n" +
31
+ "restart npm run dev, then set Base URL to:\n" +
32
+ " http://localhost:5173/blazeo-api\n" +
33
+ "Consumer header stays the same.";
34
+
35
+ if (isRemote) {
36
+ return `${msg}\n\nLikely CORS / blocked browser cross-origin request.\nFix API CORS for http://localhost:5173, OR:\n${proxyHint}`;
37
+ }
38
+ return `${msg}\n\n${proxyHint}`;
39
+ }
40
+
41
+ function toDisplayJson(value) {
42
+ try {
43
+ return JSON.stringify(value, null, 2);
44
+ } catch {
45
+ return String(value);
46
+ }
47
+ }
48
+
49
+ export function LeadTab() {
50
+ const { effective, connectionOpts } = useBlazeoConnection();
51
+ const [leadId, setLeadId] = useState("");
52
+ const [email, setEmail] = useState("");
53
+ const [companyKey, setCompanyKey] = useState("");
54
+ const [listCompanyKey, setListCompanyKey] = useState("");
55
+ const [skip, setSkip] = useState("");
56
+ const [take, setTake] = useState("");
57
+ const [busy, setBusy] = useState(false);
58
+ const [error, setError] = useState("");
59
+ const [note, setNote] = useState("");
60
+ const [output, setOutput] = useState("");
61
+
62
+ function ensureBaseConfigured() {
63
+ if (!effective.baseUrl) {
64
+ setError("Set Base URL in the connection card above or in `blazeoClientDefaults.ts`.");
65
+ return false;
66
+ }
67
+ return true;
68
+ }
69
+
70
+ async function handleFetchById(e) {
71
+ e.preventDefault();
72
+ setError("");
73
+ setNote("");
74
+ setOutput("");
75
+ const id = leadId.trim();
76
+ if (!id) {
77
+ setError("Enter a lead id.");
78
+ return;
79
+ }
80
+ if (!ensureBaseConfigured()) return;
81
+ configureBlazeoFromEffective(effective);
82
+ ensureBlazeoHttpReady({
83
+ baseUrl: effective.baseUrl,
84
+ ...(effective.consumer ? { consumer: effective.consumer } : {}),
85
+ });
86
+
87
+ setBusy(true);
88
+ try {
89
+ const res = await fetchLeadDetails(id, {
90
+ ...connectionOpts,
91
+ baseUrl: effective.baseUrl,
92
+ ...(effective.consumer ? { consumer: effective.consumer } : {}),
93
+ });
94
+ if (!res.ok) {
95
+ setError(mapBlazeoDemoError(res.detail ?? ""));
96
+ return;
97
+ }
98
+ setNote("LeadModel.get + getRaw → GET /lead/get (lead mapped snapshot + raw envelope).");
99
+ setOutput(toDisplayJson({ lead: res.lead, rawGet: res.rawGet }));
100
+ } catch (err) {
101
+ setError(explainFetchFailure(err, effective.baseUrl));
102
+ } finally {
103
+ setBusy(false);
104
+ }
105
+ }
106
+
107
+ async function handleFetchByEmail(e) {
108
+ e.preventDefault();
109
+ setError("");
110
+ setNote("");
111
+ setOutput("");
112
+ const em = email.trim();
113
+ const ck = companyKey.trim();
114
+ if (!em || !ck) {
115
+ setError("Enter email and company key.");
116
+ return;
117
+ }
118
+ if (!ensureBaseConfigured()) return;
119
+ configureBlazeoFromEffective(effective);
120
+ ensureBlazeoHttpReady({
121
+ baseUrl: effective.baseUrl,
122
+ ...(effective.consumer ? { consumer: effective.consumer } : {}),
123
+ });
124
+
125
+ setBusy(true);
126
+ try {
127
+ const res = await fetchLeadByEmail(em, ck, {
128
+ ...connectionOpts,
129
+ baseUrl: effective.baseUrl,
130
+ ...(effective.consumer ? { consumer: effective.consumer } : {}),
131
+ });
132
+ if (!res.ok) {
133
+ setError(mapBlazeoDemoError(res.detail ?? ""));
134
+ return;
135
+ }
136
+ setNote("LeadModel.getByEmail → GET /lead/getbyemail.");
137
+ setOutput(toDisplayJson({ lead: res.lead }));
138
+ } catch (err) {
139
+ setError(explainFetchFailure(err, effective.baseUrl));
140
+ } finally {
141
+ setBusy(false);
142
+ }
143
+ }
144
+
145
+ async function handleFetchByCompany(e) {
146
+ e.preventDefault();
147
+ setError("");
148
+ setNote("");
149
+ setOutput("");
150
+ const ck = listCompanyKey.trim();
151
+ if (!ck) {
152
+ setError("Enter company key for the list.");
153
+ return;
154
+ }
155
+ if (!ensureBaseConfigured()) return;
156
+ configureBlazeoFromEffective(effective);
157
+ ensureBlazeoHttpReady({
158
+ baseUrl: effective.baseUrl,
159
+ ...(effective.consumer ? { consumer: effective.consumer } : {}),
160
+ });
161
+
162
+ const listOpts = {};
163
+ const s = skip.trim();
164
+ const t = take.trim();
165
+ if (s !== "") {
166
+ const n = Number(s);
167
+ if (!Number.isFinite(n)) {
168
+ setError("Skip must be a number.");
169
+ return;
170
+ }
171
+ listOpts.skip = n;
172
+ }
173
+ if (t !== "") {
174
+ const n = Number(t);
175
+ if (!Number.isFinite(n)) {
176
+ setError("Take must be a number.");
177
+ return;
178
+ }
179
+ listOpts.take = n;
180
+ }
181
+
182
+ setBusy(true);
183
+ try {
184
+ const res = await fetchLeadsByCompany(ck, listOpts, {
185
+ ...connectionOpts,
186
+ baseUrl: effective.baseUrl,
187
+ ...(effective.consumer ? { consumer: effective.consumer } : {}),
188
+ });
189
+ if (!res.ok) {
190
+ setError(mapBlazeoDemoError(res.detail ?? ""));
191
+ return;
192
+ }
193
+ setNote(
194
+ `LeadModel.getByCompany → GET /lead/company/get (${res.leads.length} row(s), MST snapshots as plain objects).`
195
+ );
196
+ setOutput(toDisplayJson({ leads: res.leads }));
197
+ } catch (err) {
198
+ setError(explainFetchFailure(err, effective.baseUrl));
199
+ } finally {
200
+ setBusy(false);
201
+ }
202
+ }
203
+
204
+ return (
205
+ <>
206
+ <div className="card">
207
+ <h2>Lead by id</h2>
208
+ <p className="muted small">
209
+ Uses <code>fetchLeadDetails(leadId)</code> from <code>appointment-client</code>, which wraps{" "}
210
+ <code>LeadModel.getRaw</code> + <code>LeadModel.get</code> (<code>GET /lead/get</code>). Output shows both the
211
+ mapped lead snapshot and the raw API envelope.
212
+ </p>
213
+ <form onSubmit={handleFetchById} className="form">
214
+ <label className="form__label">
215
+ <span>Lead id</span>
216
+ <input
217
+ type="text"
218
+ className="form__input"
219
+ placeholder="lead_id"
220
+ value={leadId}
221
+ onChange={(e) => setLeadId(e.target.value)}
222
+ autoComplete="off"
223
+ />
224
+ </label>
225
+ <button type="submit" className="btn btn--primary" disabled={busy}>
226
+ {busy ? "Loading…" : "Fetch lead"}
227
+ </button>
228
+ </form>
229
+ </div>
230
+
231
+ <div className="card">
232
+ <h2>Lead by email + company</h2>
233
+ <p className="muted small">
234
+ <code>fetchLeadByEmail</code> → <code>LeadModel.getByEmail</code> (<code>GET /lead/getbyemail</code>).
235
+ </p>
236
+ <form onSubmit={handleFetchByEmail} className="form">
237
+ <label className="form__label">
238
+ <span>Email</span>
239
+ <input
240
+ type="email"
241
+ className="form__input"
242
+ placeholder="user@example.com"
243
+ value={email}
244
+ onChange={(e) => setEmail(e.target.value)}
245
+ autoComplete="off"
246
+ />
247
+ </label>
248
+ <label className="form__label">
249
+ <span>Company key</span>
250
+ <input
251
+ type="text"
252
+ className="form__input"
253
+ placeholder="company_key"
254
+ value={companyKey}
255
+ onChange={(e) => setCompanyKey(e.target.value)}
256
+ autoComplete="off"
257
+ />
258
+ </label>
259
+ <button type="submit" className="btn btn--secondary" disabled={busy}>
260
+ {busy ? "Loading…" : "Fetch lead"}
261
+ </button>
262
+ </form>
263
+ </div>
264
+
265
+ <div className="card">
266
+ <h2>Leads by company</h2>
267
+ <p className="muted small">
268
+ <code>fetchLeadsByCompany</code> → <code>LeadModel.getByCompany</code> (<code>GET /lead/company/get</code>).
269
+ Optional <code>skip</code> / <code>take</code> map to query params (see calendar-client).
270
+ </p>
271
+ <form onSubmit={handleFetchByCompany} className="form">
272
+ <label className="form__label">
273
+ <span>Company key</span>
274
+ <input
275
+ type="text"
276
+ className="form__input"
277
+ placeholder="company_key"
278
+ value={listCompanyKey}
279
+ onChange={(e) => setListCompanyKey(e.target.value)}
280
+ autoComplete="off"
281
+ />
282
+ </label>
283
+ <label className="form__label">
284
+ <span>Skip (optional)</span>
285
+ <input
286
+ type="text"
287
+ className="form__input"
288
+ inputMode="numeric"
289
+ placeholder="e.g. 0"
290
+ value={skip}
291
+ onChange={(e) => setSkip(e.target.value)}
292
+ autoComplete="off"
293
+ />
294
+ </label>
295
+ <label className="form__label">
296
+ <span>Take (optional)</span>
297
+ <input
298
+ type="text"
299
+ className="form__input"
300
+ inputMode="numeric"
301
+ placeholder="e.g. 50"
302
+ value={take}
303
+ onChange={(e) => setTake(e.target.value)}
304
+ autoComplete="off"
305
+ />
306
+ </label>
307
+ <button type="submit" className="btn btn--secondary" disabled={busy}>
308
+ {busy ? "Loading…" : "Fetch leads"}
309
+ </button>
310
+ </form>
311
+ </div>
312
+
313
+ {note ? (
314
+ <div className="card">
315
+ <h2>Note</h2>
316
+ <p className="muted small">{note}</p>
317
+ </div>
318
+ ) : null}
319
+
320
+ {error ? (
321
+ <div className="card card--error" role="alert">
322
+ <h2>Error</h2>
323
+ <pre className="pre-block">{error}</pre>
324
+ </div>
325
+ ) : null}
326
+
327
+ {output ? (
328
+ <div className="card">
329
+ <h2>JSON</h2>
330
+ <pre className="pre-block">{output}</pre>
331
+ </div>
332
+ ) : null}
333
+ </>
334
+ );
335
+ }
@@ -91,19 +91,37 @@ function dayOrderIndex(d: string): number {
91
91
  return i >= 0 ? i : 999;
92
92
  }
93
93
 
94
- /** Merge rows that share participant + time span + off into one row with combined `days`. */
94
+ /** Merge rows that share participant + time span into one row with combined active `days`. */
95
95
  function mergeOpeningHoursBySlot(rows: UnifiedOpeningHourRow[]) {
96
96
  const map = new Map<string, UnifiedOpeningHourRow>();
97
97
  for (const r of rows) {
98
- const key = [r.member, r.startHour, r.startMinute, r.endHour, r.endMinute, r.off].join("|");
98
+ // Key excludes 'off' because we want to merge ON and OFF records for the same time slot
99
+ const key = [r.member, r.startHour, r.startMinute, r.endHour, r.endMinute].join("|");
99
100
  const existing = map.get(key);
101
+
102
+ // We only want to add the day to the 'days' array if it is NOT marked as OFF.
103
+ // If the whole record was marked as OFF, we still process it to establish the slot,
104
+ // but its days won't be listed as 'active'.
105
+ const activeDaysFromThisRow = r.off ? [] : r.days;
106
+
100
107
  if (!existing) {
101
- map.set(key, { ...r, days: [...r.days] });
108
+ map.set(key, { ...r, days: [...activeDaysFromThisRow], off: false });
102
109
  } else {
103
- const set = new Set([...existing.days, ...r.days]);
110
+ const set = new Set([...existing.days, ...activeDaysFromThisRow]);
104
111
  existing.days = Array.from(set).sort((a, b) => dayOrderIndex(a) - dayOrderIndex(b));
112
+ // If we encounter any record that is NOT off, the whole merged slot is NOT off.
113
+ if (!r.off) existing.off = false;
114
+ }
115
+ }
116
+
117
+ // Final Pass: If a slot has NO active days, it should be marked as off: true
118
+ // (though in Plan V2, these usually just disappear from the UI's 'days' list)
119
+ for (const group of map.values()) {
120
+ if (group.days.length === 0) {
121
+ group.off = true;
105
122
  }
106
123
  }
124
+
107
125
  rows.length = 0;
108
126
  rows.push(...map.values());
109
127
  }
@@ -132,7 +132,10 @@ async function runMembersAndOpeningHoursAfterCalendarSave(calendar: any, calenda
132
132
  endHour: oh.endHour,
133
133
  endMinute: oh.endMinute,
134
134
  off: isOff,
135
- openingHourId: openingHourId,
135
+ // Plan V2 Optimization: Generate a unique ID for EVERY day record.
136
+ // This prevents the backend from deduplicating/overwriting when multiple
137
+ // records for the same participant + slot are sent in one batch.
138
+ openingHourId: newOpeningHourId(),
136
139
  });
137
140
  }
138
141
  }
@@ -141,6 +144,11 @@ async function runMembersAndOpeningHoursAfterCalendarSave(calendar: any, calenda
141
144
  for (const [participantId, payload] of hoursByParticipant.entries()) {
142
145
  if (payload.length === 0) continue;
143
146
 
147
+ // Plan V2 Optimization: Clear existing records for this participant first.
148
+ // This ensures that when we save the new batch (with unique per-day IDs),
149
+ // we don't leak orphaned records or create duplicates during updates.
150
+ await (calendarNode as any).removeParticipantOpeningHours(participantId);
151
+
144
152
  // Use the batch save method (plural)
145
153
  const res = await saveCalendarOpeningHoursBatch(calendarNode, payload);
146
154
 
@@ -276,9 +276,17 @@ export async function fetchCalendarDetails(
276
276
 
277
277
  if (!calendarView) return null as any;
278
278
 
279
+ // Use the mapper to normalize the final output, ensuring all fields like duration,
280
+ // bookingPageTitle, calendarId, etc. are correctly picked and named.
281
+ const finalView = mapToDesiredCalendarResponse(
282
+ payload,
283
+ calendarView.openingHours,
284
+ calendarView.members
285
+ ) as any;
286
+
279
287
  // Attach metadata as non-enumerable properties so they don't show up in JSON.stringify
280
288
  // but are still accessible for debugging if needed.
281
- Object.defineProperties(calendarView, {
289
+ Object.defineProperties(finalView, {
282
290
  _cal: { value: cal, enumerable: false },
283
291
  _participants: { value: participantList, enumerable: false },
284
292
  _openingHours: { value: openingHours, enumerable: false },
@@ -294,7 +302,7 @@ export async function fetchCalendarDetails(
294
302
  },
295
303
  });
296
304
 
297
- return calendarView as any;
305
+ return finalView as any;
298
306
  }
299
307
 
300
308
  /**
@@ -1,10 +1,11 @@
1
1
  import { CalendarModel, CalendarParticipantModel } from "@blazeo.com/calendar-client";
2
2
  import { ensureBlazeoHttpReady } from "../config/ensureBlazeoHttpReady.js";
3
+ import { mapToDesiredCalendarResponse } from "./mapToDesiredResponse.js";
3
4
 
4
5
  /**
5
6
  * Fetches all calendars for a company and populates each with its members (participants).
6
- * Fetches both Participant List and Participant Info to ensure names and emails are included,
7
- * while still skipping heavy data like opening hours.
7
+ * Uses a highly optimized single-request approach per calendar to ensure speed in list views.
8
+ * Results are normalized via mapToDesiredCalendarResponse.
8
9
  */
9
10
  export async function getCalendarsByCompany(
10
11
  companyKey: string,
@@ -30,96 +31,48 @@ export async function getCalendarsByCompany(
30
31
  if (!calendarId) return null;
31
32
 
32
33
  try {
33
- // We need both List and Info to get the names/emails
34
- const [partsRaw, infoRaw] = await Promise.all([
35
- CalendarParticipantModel.getByCalendar(calendarId),
36
- CalendarParticipantModel.getInfoByCalendar(calendarId)
37
- ]);
38
-
39
- const parts = Array.isArray(partsRaw) ? partsRaw : (partsRaw as any)?.participants ?? [];
34
+ // Optimization: Use only getInfoByCalendar to get names/emails in a single request.
35
+ // This is much faster for a list view than fetching both list and info records.
36
+ const infoRaw = await CalendarParticipantModel.getInfoByCalendar(calendarId);
40
37
  const info = Array.isArray(infoRaw) ? infoRaw : (infoRaw as any)?.info ?? [];
41
38
 
42
39
  // Merge logic to ensure names are matched to IDs
43
40
  const membersMap = new Map<string, any>();
44
-
41
+
45
42
  // Use participantId GUID as the primary key
46
43
  const getAnyId = (obj: any) =>
47
44
  obj.participantId ?? obj.ParticipantId ?? obj.participant_id ?? obj.id ?? obj.Id;
48
45
 
49
- // 1. Initialize with basic participant data
50
- parts.forEach((p: any) => {
51
- const mid = getAnyId(p);
52
- if (mid) {
53
- membersMap.set(String(mid).toLowerCase(), {
54
- id: mid,
55
- name: p.name ?? p.Name ?? "Member",
56
- email: p.email ?? p.Email,
57
- status: p.status ?? p.Status ?? 1,
58
- uuId: mid
59
- });
60
- }
61
- });
62
-
63
- // 2. Enrich with detailed info (Name, Email, Alias)
46
+ // 1. Process info list (Name, Email, Alias)
64
47
  info.forEach((i: any) => {
65
48
  const mid = getAnyId(i);
66
49
  if (!mid) return;
67
50
  const key = String(mid).toLowerCase();
68
- const existing = membersMap.get(key);
69
-
70
- const resolvedEmail = i.email ?? i.Email ?? i.userSsoEmail ?? i.UserSsoEmail ?? existing?.email;
71
51
 
52
+ const resolvedEmail = i.email ?? i.Email ?? i.userSsoEmail ?? i.UserSsoEmail;
72
53
  const memberData = {
73
54
  id: mid,
74
- name: i.name ?? i.Name ?? i.alias ?? i.Alias ?? (existing?.name || "Member"),
55
+ name: i.name ?? i.Name ?? i.alias ?? i.Alias ?? "Member",
75
56
  email: resolvedEmail,
76
- alias: i.alias ?? i.Alias ?? i.name ?? i.Name,
77
- userSsoEmail: resolvedEmail,
78
- uuId: mid,
79
- status: i.status ?? i.Status ?? existing?.status ?? 1
57
+ status: i.status ?? i.Status ?? 1,
80
58
  };
81
59
 
82
- if (!existing) {
60
+ if (!membersMap.has(key)) {
83
61
  membersMap.set(key, memberData);
84
- } else {
85
- Object.assign(existing, memberData);
86
62
  }
87
63
  });
88
64
 
89
65
  const members = Array.from(membersMap.values());
90
66
 
91
- // Map to the EXACT schema requested by the user
92
- return {
93
- id: cal.id ?? cal.Id,
94
- calendarLink: cal.calendarLink ?? cal.CalendarLink ?? "",
95
- uuid: calendarId,
96
- createdOn: cal.createdOn ?? cal.CreatedOn,
97
- name: cal.name ?? cal.Name,
98
- timeZoneId: cal.timeZoneId ?? cal.TimeZoneId,
99
- description: cal.description ?? cal.Description ?? "",
100
- assignmentType: cal.assignmentMethod ?? cal.AssignmentMethod ?? cal.assignmentType,
101
- status: cal.status ?? cal.Status ?? 1,
102
- location: cal.location ?? cal.Location ?? "",
103
- members
104
- };
67
+ // Use the unified mapper to ensure all properties (duration, calendarId, etc.) are included
68
+ return mapToDesiredCalendarResponse(cal, [], members);
105
69
  } catch (err) {
106
70
  console.error(`[getCalendarsByCompany] Error fetching members for ${calendarId}:`, err);
107
- return {
108
- id: cal.id ?? cal.Id,
109
- calendarLink: cal.calendarLink ?? cal.CalendarLink ?? "",
110
- uuid: calendarId,
111
- createdOn: cal.createdOn ?? cal.CreatedOn,
112
- name: cal.name ?? cal.Name,
113
- timeZoneId: cal.timeZoneId ?? cal.TimeZoneId,
114
- description: cal.description ?? cal.Description ?? "",
115
- assignmentType: cal.assignmentMethod ?? cal.AssignmentMethod ?? cal.assignmentType,
116
- status: cal.status ?? cal.Status ?? 1,
117
- location: cal.location ?? cal.Location ?? "",
118
- members: []
119
- };
71
+ // Fallback to minimal mapping if enrichment fails
72
+ return mapToDesiredCalendarResponse(cal, [], []);
120
73
  }
121
74
  })
122
75
  );
123
76
 
124
- return enrichedCalendars.filter(c => c !== null);
77
+ return enrichedCalendars.filter(Boolean);
125
78
  }
@@ -24,22 +24,33 @@ export function mapToDesiredCalendarResponse(payload: any, openingHours: any[] =
24
24
  }));
25
25
 
26
26
  // Map opening hours with typename and raw fields
27
- const mappedOpeningHours = openingHours.map(oh => ({
28
- id: pick(oh, "id", "Id") ?? 0,
29
- createdOn: pick(oh, "createdOn", "CreatedOn", "created_on") ?? "0001-01-01T00:00:00.000Z",
30
- modifiedOn: pick(oh, "modifiedOn", "ModifiedOn", "modified_on") ?? "0001-01-01T00:00:00.000Z",
31
- member: pick(oh, "member", "Member"),
32
- openingHourId: pick(oh, "openingHourId", "OpeningHourId", "opening_hour_id") ?? "",
33
- calendarId: pick(oh, "calendarId", "CalendarId", "calendar_id") ?? "",
34
- participantId: pick(oh, "participantId", "ParticipantId", "participant_id") ?? "",
35
- days: oh.days ?? [],
36
- startHour: oh.startHour ?? pick(oh, "startHour", "StartHour") ?? 0,
37
- startMinute: oh.startMinute ?? pick(oh, "startMinute", "StartMinute") ?? 0,
38
- endHour: oh.endHour ?? pick(oh, "endHour", "EndHour") ?? 0,
39
- endMinute: oh.endMinute ?? pick(oh, "endMinute", "EndMinute") ?? 0,
40
- off: !!(oh.off ?? pick(oh, "off", "Off")),
41
- __typename: "OpeningHour"
42
- }));
27
+ const mappedOpeningHours = openingHours.map(oh => {
28
+ // If it's already a unified object (has day/start/end), preserve it but ensure __typename
29
+ if (oh.day !== undefined && oh.start !== undefined && oh.end !== undefined) {
30
+ return {
31
+ ...oh,
32
+ __typename: "OpeningHour"
33
+ };
34
+ }
35
+
36
+ // Otherwise, map from raw PascalCase or camelCase
37
+ return {
38
+ id: pick(oh, "id", "Id") ?? 0,
39
+ createdOn: pick(oh, "createdOn", "CreatedOn", "created_on") ?? "0001-01-01T00:00:00.000Z",
40
+ modifiedOn: pick(oh, "modifiedOn", "ModifiedOn", "modified_on") ?? "0001-01-01T00:00:00.000Z",
41
+ member: pick(oh, "member", "Member"),
42
+ openingHourId: pick(oh, "openingHourId", "OpeningHourId", "opening_hour_id") ?? "",
43
+ calendarId: pick(oh, "calendarId", "CalendarId", "calendar_id") ?? "",
44
+ participantId: pick(oh, "participantId", "ParticipantId", "participant_id") ?? "",
45
+ days: oh.days ?? [],
46
+ startHour: oh.startHour ?? pick(oh, "startHour", "StartHour") ?? 0,
47
+ startMinute: oh.startMinute ?? pick(oh, "startMinute", "StartMinute") ?? 0,
48
+ endHour: oh.endHour ?? pick(oh, "endHour", "EndHour") ?? 0,
49
+ endMinute: oh.endMinute ?? pick(oh, "endMinute", "EndMinute") ?? 0,
50
+ off: !!(oh.off ?? pick(oh, "off", "Off")),
51
+ __typename: "OpeningHour"
52
+ };
53
+ });
43
54
 
44
55
  // Map theme
45
56
  const rawTheme = pick(payload, "theme", "Theme");
@@ -68,6 +79,8 @@ export function mapToDesiredCalendarResponse(payload: any, openingHours: any[] =
68
79
  __typename: "ReminderChannelStatus"
69
80
  })) : [];
70
81
 
82
+ const uuid = pick(payload, "uuid", "Uuid", "calendarId", "CalendarId");
83
+
71
84
  return {
72
85
  id: n(pick(payload, "id", "Id")),
73
86
  durationUnit: n(pick(payload, "durationUnit", "DurationUnit")),
@@ -80,7 +93,8 @@ export function mapToDesiredCalendarResponse(payload: any, openingHours: any[] =
80
93
  bufferTime: n(pick(payload, "bufferTime", "BufferTime")),
81
94
  bufferTimeUnit: n(pick(payload, "bufferTimeUnit", "BufferTimeUnit")),
82
95
  calendarLink: pick(payload, "calendarLink", "CalendarLink"),
83
- uuid: pick(payload, "uuid", "Uuid", "calendarId", "CalendarId"),
96
+ uuid: uuid,
97
+ calendarId: uuid, // Explicit alias requested by user
84
98
  location: pick(payload, "location", "Location") ?? "",
85
99
  bookingPageTitle: pick(payload, "bookingPageTitle", "BookingPageTitle") ?? null,
86
100
  reminderChannelStatuses,
package/src/index.ts CHANGED
@@ -10,8 +10,7 @@ export type { EnsureBlazeoHttpOptions } from "./config/ensureBlazeoHttpReady.js"
10
10
  export { blazeoClientConfig } from "./config/blazeoClientDefaults.js";
11
11
  export { applyBlazeoClientConfig } from "./config/applyBlazeoDefaults.js";
12
12
  export { createCalendarRoot, CalendarRootModel, CalendarSlotModel, EventModel, ParticipantModel } from "./models/CalendarRootModel.js";
13
- export { fetchCalendarDetails, fetchCalendarBundle, normalizeOpeningHours } from "./calendar/fetchCalendarDetails.js";
14
- export { getCalendarsByCompany } from "./calendar/getCalendarsByCompany.js";
13
+ export { fetchCalendarBundle, normalizeOpeningHours } from "./calendar/fetchCalendarDetails.js";
15
14
  export {
16
15
  buildUnifiedCalendarView,
17
16
  type UnifiedCalendarMember,
@@ -33,9 +32,9 @@ export { addParticipantToCalendar, removeParticipantFromCalendar, saveCalendarOp
33
32
  export { createAppointmentEventAsync, rescheduleAppointmentEventAsync, cancelAppointmentEventAsync } from "./events/appointmentEventFacade.js";
34
33
  export { mapAppointmentToEventSnapshot } from "./events/mapAppointmentToEventSnapshot.js";
35
34
 
36
- import { fetchCalendarDetails, fetchCalendarBundle } from "./calendar/fetchCalendarDetails.js";
37
- import { fetchCalendarWithOpeningHours } from "./calendar/fetchCalendarWithOpeningHours.js";
38
35
  import { getCalendarsByCompany } from "./calendar/getCalendarsByCompany.js";
36
+ import { fetchCalendarDetails } from "./calendar/fetchCalendarDetails.js";
37
+ export { getCalendarsByCompany, fetchCalendarDetails };
39
38
 
40
39
  import {
41
40
  CalendarModel as CoreCalendarModel,
@@ -46,14 +45,14 @@ import {
46
45
  getConfig
47
46
  } from "@blazeo.com/calendar-client";
48
47
 
49
- // Attach new methods to CalendarModel for easier access
50
- (CoreCalendarModel as any).fetchCalendarDetails = fetchCalendarDetails;
51
- (CoreCalendarModel as any).fetchCalendarBundle = fetchCalendarBundle;
52
- (CoreCalendarModel as any).fetchCalendarWithOpeningHours = fetchCalendarWithOpeningHours;
53
- (CoreCalendarModel as any).getCalendarsByCompany = getCalendarsByCompany;
48
+ // Enriched CalendarModel
49
+ export const CalendarModel = {
50
+ ...CoreCalendarModel,
51
+ getCalendarsByCompany,
52
+ fetchCalendarDetails
53
+ };
54
54
 
55
55
  export {
56
- CoreCalendarModel as CalendarModel,
57
56
  CoreEventModel as CoreEventModel,
58
57
  CoreParticipantModel as CoreParticipantModel,
59
58
  CoreCalendarParticipantModel as CalendarParticipantModel,
@@ -61,7 +60,6 @@ export {
61
60
  getConfig
62
61
  };
63
62
 
64
-
65
63
  export const packageName = "@blazeo.com/appointment-client";
66
64
 
67
65
  export class CalendarClient {