tripstorekrabi-shared 1.25.6 → 1.25.8

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/availability.js CHANGED
@@ -13,14 +13,15 @@ dayjs.extend(isSameOrAfter);
13
13
  dayjs.extend(utc);
14
14
  dayjs.extend(timezone);
15
15
 
16
- const WEEKDAYS = new Array(7);
17
- WEEKDAYS[0] = "Sunday";
18
- WEEKDAYS[1] = "Monday";
19
- WEEKDAYS[2] = "Tuesday";
20
- WEEKDAYS[3] = "Wednesday";
21
- WEEKDAYS[4] = "Thursday";
22
- WEEKDAYS[5] = "Friday";
23
- WEEKDAYS[6] = "Saturday";
16
+ const WEEKDAYS = [
17
+ "Sunday",
18
+ "Monday",
19
+ "Tuesday",
20
+ "Wednesday",
21
+ "Thursday",
22
+ "Friday",
23
+ "Saturday"
24
+ ];
24
25
 
25
26
  export const INACTIVE = "inactive";
26
27
  export const SINGLE_DATES = "singleDates";
@@ -28,9 +29,9 @@ export const BLOCKOUT = "blockout";
28
29
  export const SCHEDULE_MODES = [INACTIVE, SINGLE_DATES, BLOCKOUT];
29
30
 
30
31
  export function isAvailable(availability, date, schedule, options = {}) {
31
- let available = availability.available;
32
+ let available = Boolean(availability?.available);
32
33
 
33
- if (available && options.viatorApi === true && (!availability.br?.connectedToApi || !availability.br?.available)) {
34
+ if (available && options.viatorApi === true && (availability.viatorConnections ?? []).length === 0) {
34
35
  return false;
35
36
  }
36
37
 
@@ -40,7 +41,7 @@ export function isAvailable(availability, date, schedule, options = {}) {
40
41
 
41
42
  if (available) {
42
43
  if (schedule) {
43
- let scheduleObject = findSchedule(availability, schedule);
44
+ const scheduleObject = findSchedule(availability, schedule);
44
45
  if (scheduleObject) {
45
46
  available = checkAvailability(date, scheduleObject);
46
47
  } else {
@@ -48,33 +49,33 @@ export function isAvailable(availability, date, schedule, options = {}) {
48
49
  }
49
50
  } else if (availability.schedules) {
50
51
  available = Object.values(availability.schedules).every(
51
- (schedule) => checkAvailability(date, schedule)
52
+ (sched) => checkAvailability(date, sched)
52
53
  );
53
54
  } else if (availability.openingHours) {
54
55
  available = Object.values(availability.openingHours).every(
55
- (schedule) => checkAvailability(date, schedule)
56
+ (sched) => checkAvailability(date, sched)
56
57
  );
57
58
  }
58
59
  }
59
60
 
60
61
  if (available) {
61
- date = dayjs(date, "DD.MM.YYYY");
62
- let today = dayjs().startOf('day');
63
- available = date.isSameOrAfter(today);
62
+ const checkDate = dayjs(date, "DD.MM.YYYY");
63
+ const today = dayjs().startOf('day');
64
+ available = checkDate.isSameOrAfter(today);
64
65
  }
65
66
 
66
67
  return available;
67
68
  }
68
69
 
69
70
  function checkAvailability(date, schedule) {
70
- let mode = schedule.mode;
71
+ const mode = schedule?.mode;
71
72
 
72
73
  switch (mode) {
73
74
  case INACTIVE: {
74
75
  return false;
75
76
  }
76
77
  case SINGLE_DATES: {
77
- return schedule.singleDates.includes(date);
78
+ return Array.isArray(schedule.singleDates) && schedule.singleDates.includes(date);
78
79
  }
79
80
  case BLOCKOUT: {
80
81
  let available = true;
@@ -83,17 +84,17 @@ function checkAvailability(date, schedule) {
83
84
  available = !schedule.blockoutDates.includes(date);
84
85
  }
85
86
  if (available && schedule.blockoutPeriods) {
86
- let day = dayjs(date, "DD.MM.YYYY");
87
- let year = day.year();
87
+ const day = dayjs(date, "DD.MM.YYYY");
88
+ const year = day.year();
88
89
  available = !schedule.blockoutPeriods.some((period) => {
89
- let start = dayjs(`${period.start}.${year}`, "DD.MM.YYYY");
90
- let end = dayjs(`${period.end}.${year}`, "DD.MM.YYYY");
90
+ const start = dayjs(`${period.start}.${year}`, "DD.MM.YYYY");
91
+ const end = dayjs(`${period.end}.${year}`, "DD.MM.YYYY");
91
92
  return day.isBetween(start, end, 'day', '[]');
92
93
  });
93
94
  }
94
95
 
95
96
  if (available && schedule.weekDays) {
96
- let weekDay = WEEKDAYS[dayjs(date, "DD.MM.YYYY").day()];
97
+ const weekDay = WEEKDAYS[dayjs(date, "DD.MM.YYYY").day()];
97
98
  available = schedule.weekDays.includes(weekDay);
98
99
  }
99
100
 
@@ -106,9 +107,9 @@ function checkAvailability(date, schedule) {
106
107
  }
107
108
 
108
109
  export function getSchedules(availability) {
109
- if (availability.schedules) {
110
+ if (availability?.schedules) {
110
111
  return Object.keys(availability.schedules).sort();
111
- } else if (availability.openingHours) {
112
+ } else if (availability?.openingHours) {
112
113
  return Object.keys(availability.openingHours).sort();
113
114
  } else {
114
115
  return [];
@@ -116,64 +117,68 @@ export function getSchedules(availability) {
116
117
  }
117
118
 
118
119
  export function findSchedule(availability, schedule) {
119
- if (availability.schedules) {
120
- return availability.schedules[schedule] ?? Object.entries(availability.schedules)[0];
121
- } else if (availability.openingHours) {
122
- return availability.openingHours[schedule] ?? Object.entries(availability.openingHours)[0];
120
+ if (availability?.schedules) {
121
+ return availability.schedules[schedule] ?? Object.entries(availability.schedules)[0]?.[1];
122
+ } else if (availability?.openingHours) {
123
+ return availability.openingHours[schedule] ?? Object.entries(availability.openingHours)[0]?.[1];
123
124
  }
124
125
  }
125
126
 
126
127
  export function getAvailabilityLabel(availability, schedule) {
127
- if (!availability.available) {
128
+ if (!availability?.available) {
128
129
  return "Not available";
129
- } else {
130
- let scheduleObject = findSchedule(availability, schedule);
131
-
132
- if (scheduleObject.mode === INACTIVE) {
133
- return "Not available";
134
- } else if (scheduleObject.mode === SINGLE_DATES) {
135
- return "Available on selected dates";
136
- } else if (scheduleObject.mode === BLOCKOUT) {
137
- if (scheduleObject.blockoutPeriods && scheduleObject.blockoutPeriods.length > 0) {
138
- let starts = [];
139
- let ends = [];
140
- let startPeriod = scheduleObject.blockoutPeriods[0];
141
- let year = dayjs().year();
142
- scheduleObject.blockoutPeriods.forEach((period, i) => {
143
- starts.push(dayjs(`${period.end}.${year}`, "DD.MM.YYYY").add(1, 'day'));
144
- if (i + 1 < scheduleObject.blockoutPeriods.length) {
145
- ends.push(dayjs(`${scheduleObject.blockoutPeriods[i + 1].start}.${year}`, "DD.MM.YYYY").subtract(1, 'day'));
146
- }
147
- });
148
- ends.push(dayjs(`${startPeriod.start}.${year + 1}`, "DD.MM.YYYY").subtract(1, 'day'));
130
+ }
149
131
 
150
- let availability = [];
151
- starts.forEach((start, i) => {
152
- if (ends[i].diff(start, "month") > 1) {
153
- availability.push(start.format("MMM") + " - " + ends[i].format("MMM"));
154
- }
155
- });
132
+ const scheduleObject = findSchedule(availability, schedule);
156
133
 
157
- return availability.join(", ");
158
- } else if (scheduleObject.weekDays) {
159
- return scheduleObject.weekDays.map((item) => item.substring(0, 3)).join(", ");
160
- } else {
161
- return "Daily";
162
- }
134
+ if (!scheduleObject || scheduleObject.mode === INACTIVE) {
135
+ return "Not available";
136
+ } else if (scheduleObject.mode === SINGLE_DATES) {
137
+ return "Available on selected dates";
138
+ } else if (scheduleObject.mode === BLOCKOUT) {
139
+ if (scheduleObject.blockoutPeriods && scheduleObject.blockoutPeriods.length > 0) {
140
+ const starts = [];
141
+ const ends = [];
142
+ const startPeriod = scheduleObject.blockoutPeriods[0];
143
+ const year = dayjs().year();
144
+
145
+ scheduleObject.blockoutPeriods.forEach((period, i) => {
146
+ starts.push(dayjs(`${period.end}.${year}`, "DD.MM.YYYY").add(1, 'day'));
147
+ if (i + 1 < scheduleObject.blockoutPeriods.length) {
148
+ ends.push(dayjs(`${scheduleObject.blockoutPeriods[i + 1].start}.${year}`, "DD.MM.YYYY").subtract(1, 'day'));
149
+ }
150
+ });
151
+ ends.push(dayjs(`${startPeriod.start}.${year + 1}`, "DD.MM.YYYY").subtract(1, 'day'));
152
+
153
+ const availabilityLabels = [];
154
+ starts.forEach((start, i) => {
155
+ if (ends[i].diff(start, "month") > 1) {
156
+ availabilityLabels.push(start.format("MMM") + " - " + ends[i].format("MMM"));
157
+ }
158
+ });
159
+
160
+ return availabilityLabels.join(", ");
161
+ } else if (scheduleObject.weekDays) {
162
+ return scheduleObject.weekDays.map((item) => item.substring(0, 3)).join(", ");
163
+ } else {
164
+ return "Daily";
163
165
  }
164
166
  }
167
+
168
+ return "Available";
165
169
  }
166
170
 
167
171
  export function isLastMinuteDate(dateValue, cutoffTime) {
168
- let date = dayjs(dateValue, "DD.MM.YYYY").tz("Asia/Bangkok");
169
- let now = dayjs().tz("Asia/Bangkok");
172
+ const date = dayjs(dateValue, "DD.MM.YYYY").tz("Asia/Bangkok");
173
+ const now = dayjs().tz("Asia/Bangkok");
170
174
 
171
175
  return now.add(cutoffTime, "hour").isSameOrAfter(date, "day");
172
176
  }
173
177
 
174
178
  export function isPastDate(dateValue, schedule) {
175
- let date = dayjs(dateValue + " " + schedule, "DD.MM.YYYY HH:mm").tz("Asia/Bangkok");
176
- let now = dayjs().tz("Asia/Bangkok");
179
+ const startTime = (schedule || "00:00").split(" - ")[0].slice(0, 5);
180
+ const date = dayjs(`${dateValue} ${startTime}`, "DD.MM.YYYY HH:mm").tz("Asia/Bangkok");
181
+ const now = dayjs().tz("Asia/Bangkok");
177
182
 
178
183
  return date.isSameOrBefore(now);
179
184
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tripstorekrabi-shared",
3
- "version": "1.25.6",
3
+ "version": "1.25.8",
4
4
  "description": "Shared library for Trip Store Krabi",
5
5
  "author": "Stefan Sommer <tonprince@gmail.com>",
6
6
  "repository": {
@@ -17,10 +17,10 @@
17
17
  "./telegram": "./telegram.js"
18
18
  },
19
19
  "dependencies": {
20
- "dayjs": "^1.11.21",
21
- "libphonenumber-js": "^1.13.10",
20
+ "dayjs": "^1.11.23",
21
+ "libphonenumber-js": "^1.13.14",
22
22
  "nanoid": "^6.0.1",
23
- "firebase-admin": "^14.2.0"
23
+ "firebase-admin": "^14.5.0"
24
24
  },
25
25
  "scripts": {
26
26
  "deploy": "npm publish"
package/telegram.js CHANGED
@@ -1,5 +1,7 @@
1
- const ENV_BOT_TOKEN = process.env.TELEGRAM_API_TOKEN;
2
- const ENV_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
1
+ const getEnv = (key) => typeof process !== 'undefined' && process.env ? process.env[key] : undefined;
2
+
3
+ const ENV_BOT_TOKEN = getEnv('TELEGRAM_API_TOKEN') || getEnv('PUBLIC_TELEGRAM_API_TOKEN');
4
+ const ENV_CHAT_ID = getEnv('TELEGRAM_CHAT_ID');
3
5
  const TELEGRAM_MAX_CHARS = 4096;
4
6
 
5
7
  export async function sendTelegramMessage(message, options = {}) {
@@ -8,14 +10,18 @@ export async function sendTelegramMessage(message, options = {}) {
8
10
  chatId,
9
11
  parseMode = 'HTML',
10
12
  prefix = '',
11
- truncate = true
13
+ truncate = true,
14
+ maxRetries = 3,
15
+ throwOnError = true
12
16
  } = options;
13
17
 
14
18
  const BOT_TOKEN = botToken || ENV_BOT_TOKEN;
15
19
  const CHAT_ID = chatId || ENV_CHAT_ID;
16
20
 
17
21
  if (!BOT_TOKEN || !CHAT_ID) {
18
- console.error("FATAL: Telegram secrets are not configured in options or the environment.");
22
+ const errorMsg = "FATAL: Telegram secrets are not configured in options or the environment.";
23
+ console.error(errorMsg);
24
+ if (throwOnError) throw new Error(errorMsg);
19
25
  return false;
20
26
  }
21
27
 
@@ -28,33 +34,72 @@ export async function sendTelegramMessage(message, options = {}) {
28
34
  console.warn(`Message truncated from ${message.length} to ${TELEGRAM_MAX_CHARS} characters.`);
29
35
  }
30
36
 
31
- try {
32
- const telegramApiUrl = `https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`;
33
- const body = {
37
+ const telegramApiUrl = `https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`;
38
+ const fetchOptions = {
39
+ method: 'POST',
40
+ headers: {
41
+ 'Content-Type': 'application/json'
42
+ },
43
+ body: JSON.stringify({
34
44
  chat_id: CHAT_ID,
35
45
  text: finalMessage,
36
46
  parse_mode: parseMode.toUpperCase(),
37
- };
38
-
39
- const res = await fetch(telegramApiUrl, {
40
- method: 'POST',
41
- headers: {
42
- 'Content-Type': 'application/json'
43
- },
44
- body: JSON.stringify(body)
45
- });
46
-
47
- if (!res.ok) {
48
- const errorBody = await res.text();
49
- console.error(`Failed to send Telegram message: HTTP Status ${res.status} ${res.statusText}`);
50
- console.error('Telegram API Detailed Error:', errorBody);
51
- return false;
52
- } else {
53
- console.log('Telegram message sent successfully.');
54
- return true;
47
+ })
48
+ };
49
+
50
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
51
+ try {
52
+ const res = await fetch(telegramApiUrl, fetchOptions);
53
+
54
+ if (res.ok) {
55
+ return true;
56
+ }
57
+
58
+ const json = await res.json().catch(() => null);
59
+
60
+ if (res.status === 429 && json?.parameters?.retry_after) {
61
+ const retryAfterSeconds = json.parameters.retry_after;
62
+ const waitTimeMs = (retryAfterSeconds + 1) * 1000;
63
+
64
+ console.warn(`Telegram Rate Limit hit. Retrying after ${retryAfterSeconds}s...`);
65
+ await new Promise((resolve) => setTimeout(resolve, waitTimeMs));
66
+ continue;
67
+ }
68
+
69
+ let errorMessage = 'Telegram API request failed';
70
+ if (json?.description) {
71
+ errorMessage = json.description;
72
+ } else if (typeof json?.error === 'string') {
73
+ errorMessage = json.error;
74
+ } else if (json?.error?.message) {
75
+ errorMessage = json.error.message;
76
+ } else {
77
+ errorMessage = `HTTP ${res.status}: ${res.statusText || 'Unknown Error'}`;
78
+ }
79
+
80
+ throw new Error(`An error occurred while communicating with Telegram:\n${errorMessage}`);
81
+ } catch (err) {
82
+ const safeError = err instanceof Error ? err : new Error(String(err));
83
+ const msg = safeError.message || '';
84
+
85
+ if (msg.includes('communicating with Telegram') && !msg.includes('429')) {
86
+ if (throwOnError) throw safeError;
87
+ console.error(safeError);
88
+ return false;
89
+ }
90
+
91
+ if (attempt === maxRetries - 1) {
92
+ if (throwOnError) throw safeError;
93
+ console.error(safeError);
94
+ return false;
95
+ }
96
+
97
+ await new Promise((resolve) => setTimeout(resolve, 1000 * (attempt + 1)));
55
98
  }
56
- } catch (e) {
57
- console.error('An error occurred while trying to send a Telegram message:', e);
58
- return false;
59
99
  }
100
+
101
+ const timeoutError = new Error('Telegram request failed: Exceeded maximum retries.');
102
+ if (throwOnError) throw timeoutError;
103
+ console.error(timeoutError);
104
+ return false;
60
105
  }