arky-sdk 0.3.77 → 0.3.78

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/dist/index.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var nanostores = require('nanostores');
4
+
3
5
  // src/types/index.ts
4
6
  var PaymentMethodType = /* @__PURE__ */ ((PaymentMethodType2) => {
5
7
  PaymentMethodType2["Cash"] = "CASH";
@@ -980,7 +982,21 @@ var createEshopApi = (apiConfig) => {
980
982
 
981
983
  // src/api/reservation.ts
982
984
  var createReservationApi = (apiConfig) => {
985
+ let cart = [];
983
986
  return {
987
+ // ===== CART =====
988
+ addToCart(slot) {
989
+ cart.push(slot);
990
+ },
991
+ removeFromCart(slotId) {
992
+ cart = cart.filter((s) => s.id !== slotId);
993
+ },
994
+ getCart() {
995
+ return [...cart];
996
+ },
997
+ clearCart() {
998
+ cart = [];
999
+ },
984
1000
  // ===== RESERVATIONS =====
985
1001
  async createReservation(params, options) {
986
1002
  const payload = {
@@ -999,16 +1015,25 @@ var createReservationApi = (apiConfig) => {
999
1015
  );
1000
1016
  },
1001
1017
  async checkout(params, options) {
1018
+ const items = params?.items || cart.map((s) => ({
1019
+ serviceId: s.serviceId,
1020
+ providerId: s.providerId,
1021
+ from: s.from,
1022
+ to: s.to
1023
+ }));
1002
1024
  const payload = {
1003
1025
  businessId: apiConfig.businessId,
1004
1026
  market: apiConfig.market,
1005
- ...params
1027
+ ...params,
1028
+ items
1006
1029
  };
1007
- return apiConfig.httpClient.post(
1030
+ const result = await apiConfig.httpClient.post(
1008
1031
  `/v1/reservations/checkout`,
1009
1032
  payload,
1010
1033
  options
1011
1034
  );
1035
+ cart = [];
1036
+ return result;
1012
1037
  },
1013
1038
  async getReservation(params, options) {
1014
1039
  return apiConfig.httpClient.get(`/v1/reservations/${params.id}`, {
@@ -1095,19 +1120,6 @@ var createReservationApi = (apiConfig) => {
1095
1120
  }
1096
1121
  );
1097
1122
  },
1098
- async getAvailableSlots(params, options) {
1099
- const { serviceId, ...queryParams } = params;
1100
- return apiConfig.httpClient.get(
1101
- `/v1/businesses/${apiConfig.businessId}/services/${serviceId}/available-slots`,
1102
- {
1103
- ...options,
1104
- params: {
1105
- ...queryParams,
1106
- limit: queryParams.limit || 1e3
1107
- }
1108
- }
1109
- );
1110
- },
1111
1123
  async getServiceProviders(params, options) {
1112
1124
  const { serviceId, ...queryParams } = params;
1113
1125
  return apiConfig.httpClient.get(
@@ -1688,9 +1700,328 @@ async function injectSvgIntoElement(mediaObject, targetElement, className) {
1688
1700
  console.error("Error injecting SVG:", error);
1689
1701
  }
1690
1702
  }
1703
+ function formatTime(ts, tz) {
1704
+ return new Date(ts * 1e3).toLocaleTimeString([], {
1705
+ hour: "2-digit",
1706
+ minute: "2-digit",
1707
+ timeZone: tz
1708
+ });
1709
+ }
1710
+ function formatSlotTime(from, to, tz) {
1711
+ return `${formatTime(from, tz)} \u2013 ${formatTime(to, tz)}`;
1712
+ }
1713
+ function getTzOffset(date, tz) {
1714
+ const utc = new Date(date.toLocaleString("en-US", { timeZone: "UTC" }));
1715
+ const local = new Date(date.toLocaleString("en-US", { timeZone: tz }));
1716
+ return (utc.getTime() - local.getTime()) / 6e4;
1717
+ }
1718
+ function toUtcTimestamp(year, month, day, mins, tz) {
1719
+ const midnight = new Date(Date.UTC(year, month - 1, day));
1720
+ const offset = getTzOffset(midnight, tz);
1721
+ return Math.floor(midnight.getTime() / 1e3) + (mins + offset) * 60;
1722
+ }
1723
+ function isBlocked(from, to, timeline, limit) {
1724
+ const before = timeline.filter((p) => p.timestamp <= from).sort((a, b) => b.timestamp - a.timestamp);
1725
+ if (before.length > 0 && before[0].concurrent >= limit) return true;
1726
+ for (const p of timeline) {
1727
+ if (p.timestamp >= from && p.timestamp < to && p.concurrent >= limit) return true;
1728
+ }
1729
+ return false;
1730
+ }
1731
+ function getTotalDuration(durations) {
1732
+ return durations.reduce((sum, d) => sum + d.duration, 0);
1733
+ }
1734
+ function getWorkingHoursForDate(wt, date, tz) {
1735
+ if (!wt) return [];
1736
+ const dayName = date.toLocaleDateString("en-US", { weekday: "long", timeZone: tz }).toLowerCase();
1737
+ const m = date.getMonth() + 1;
1738
+ const d = date.getDate();
1739
+ const ts = Math.floor(date.getTime() / 1e3);
1740
+ const specific = wt.specificDates?.find((s) => s.date === ts);
1741
+ if (specific) return specific.workingHours || [];
1742
+ const outcast = wt.outcastDates?.find((o) => o.month === m && o.day === d);
1743
+ if (outcast) return outcast.workingHours || [];
1744
+ return wt.workingDays?.find((w) => w.day === dayName)?.workingHours || [];
1745
+ }
1746
+ function computeSlotsForDate(opts) {
1747
+ const { providers, date, durations, timezone, slotInterval } = opts;
1748
+ const total = getTotalDuration(durations);
1749
+ const interval = slotInterval || total;
1750
+ const slots = [];
1751
+ const nowTs = Math.floor(Date.now() / 1e3);
1752
+ const today = /* @__PURE__ */ new Date();
1753
+ today.setHours(0, 0, 0, 0);
1754
+ if (date < today) return [];
1755
+ const [year, month, day] = date.toLocaleDateString("en-CA", { timeZone: timezone }).split("-").map(Number);
1756
+ for (const p of providers) {
1757
+ for (const wh of getWorkingHoursForDate(p.workingTime, date, timezone)) {
1758
+ for (let m = wh.from; m + total <= wh.to; m += interval) {
1759
+ const from = toUtcTimestamp(year, month, day, m, timezone);
1760
+ const to = from + total * 60;
1761
+ if (from < nowTs) continue;
1762
+ if (!isBlocked(from, to, p.timeline, p.concurrentLimit)) {
1763
+ slots.push({ from, to, providerId: p.id });
1764
+ }
1765
+ }
1766
+ }
1767
+ }
1768
+ return slots.sort((a, b) => a.from - b.from);
1769
+ }
1770
+ function hasAvailableSlots(opts) {
1771
+ return computeSlotsForDate(opts).length > 0;
1772
+ }
1773
+ var createInitialState = (timezone) => ({
1774
+ service: null,
1775
+ providers: [],
1776
+ selectedProvider: null,
1777
+ selectedMethod: null,
1778
+ currentMonth: new Date((/* @__PURE__ */ new Date()).getFullYear(), (/* @__PURE__ */ new Date()).getMonth(), 1),
1779
+ calendar: [],
1780
+ selectedDate: null,
1781
+ startDate: null,
1782
+ endDate: null,
1783
+ slots: [],
1784
+ selectedSlot: null,
1785
+ cart: [],
1786
+ timezone,
1787
+ loading: false
1788
+ });
1789
+ var createReservationEngine = (api, config = {}) => {
1790
+ const timezone = config.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
1791
+ const store = nanostores.map(createInitialState(timezone));
1792
+ const getServiceDurations = () => {
1793
+ const state = store.get();
1794
+ if (!state.service?.durations?.length) return [{ duration: 60, isPause: false }];
1795
+ return state.service.durations.map((d) => ({
1796
+ duration: d.duration,
1797
+ isPause: d.isPause || d.is_pause || false
1798
+ }));
1799
+ };
1800
+ const buildCalendar = () => {
1801
+ const state = store.get();
1802
+ const { currentMonth, selectedDate, startDate, endDate, providers, selectedProvider, timezone: timezone2 } = state;
1803
+ const year = currentMonth.getFullYear();
1804
+ const month = currentMonth.getMonth();
1805
+ const first = new Date(year, month, 1);
1806
+ const last = new Date(year, month + 1, 0);
1807
+ const today = /* @__PURE__ */ new Date();
1808
+ today.setHours(0, 0, 0, 0);
1809
+ const cells = [];
1810
+ const pad = (first.getDay() + 6) % 7;
1811
+ for (let i = 0; i < pad; i++) {
1812
+ cells.push({ date: /* @__PURE__ */ new Date(0), iso: "", available: false, isSelected: false, isInRange: false, isToday: false, blank: true });
1813
+ }
1814
+ const activeProviders = selectedProvider ? providers.filter((p) => p.id === selectedProvider.id) : providers;
1815
+ const durations = getServiceDurations();
1816
+ for (let d = 1; d <= last.getDate(); d++) {
1817
+ const date = new Date(year, month, d);
1818
+ const iso = `${year}-${String(month + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
1819
+ const available = activeProviders.length > 0 && hasAvailableSlots({ providers: activeProviders, date, durations, timezone: timezone2 });
1820
+ const isToday = date.getTime() === today.getTime();
1821
+ const isSelected = iso === selectedDate || iso === startDate || iso === endDate;
1822
+ let isInRange = false;
1823
+ if (startDate && endDate) {
1824
+ const t = date.getTime();
1825
+ isInRange = t > new Date(startDate).getTime() && t < new Date(endDate).getTime();
1826
+ }
1827
+ cells.push({ date, iso, available, isSelected, isInRange, isToday, blank: false });
1828
+ }
1829
+ const suffix = (7 - cells.length % 7) % 7;
1830
+ for (let i = 0; i < suffix; i++) {
1831
+ cells.push({ date: /* @__PURE__ */ new Date(0), iso: "", available: false, isSelected: false, isInRange: false, isToday: false, blank: true });
1832
+ }
1833
+ return cells;
1834
+ };
1835
+ const computeSlots = (dateStr) => {
1836
+ const state = store.get();
1837
+ const { providers, selectedProvider, timezone: timezone2, service } = state;
1838
+ const date = /* @__PURE__ */ new Date(dateStr + "T00:00:00");
1839
+ const activeProviders = selectedProvider ? providers.filter((p) => p.id === selectedProvider.id) : providers;
1840
+ const raw = computeSlotsForDate({ providers: activeProviders, date, durations: getServiceDurations(), timezone: timezone2 });
1841
+ return raw.map((s, i) => ({
1842
+ id: `${service?.id}-${s.from}-${i}`,
1843
+ serviceId: service?.id || "",
1844
+ providerId: s.providerId,
1845
+ from: s.from,
1846
+ to: s.to,
1847
+ timeText: formatSlotTime(s.from, s.to, timezone2),
1848
+ dateText: new Date(s.from * 1e3).toLocaleDateString([], { weekday: "short", month: "short", day: "numeric", timeZone: timezone2 })
1849
+ }));
1850
+ };
1851
+ const actions = {
1852
+ setTimezone(tz) {
1853
+ store.setKey("timezone", tz);
1854
+ store.setKey("calendar", buildCalendar());
1855
+ const state = store.get();
1856
+ if (state.selectedDate) {
1857
+ store.setKey("slots", computeSlots(state.selectedDate));
1858
+ store.setKey("selectedSlot", null);
1859
+ }
1860
+ },
1861
+ async setService(serviceId) {
1862
+ store.setKey("loading", true);
1863
+ try {
1864
+ const service = await api.getService({ id: serviceId });
1865
+ store.set({
1866
+ ...store.get(),
1867
+ service,
1868
+ selectedMethod: service.reservationMethods?.length === 1 ? service.reservationMethods[0] : null,
1869
+ selectedProvider: null,
1870
+ providers: [],
1871
+ selectedDate: null,
1872
+ startDate: null,
1873
+ endDate: null,
1874
+ slots: [],
1875
+ selectedSlot: null,
1876
+ currentMonth: new Date((/* @__PURE__ */ new Date()).getFullYear(), (/* @__PURE__ */ new Date()).getMonth(), 1),
1877
+ loading: false
1878
+ });
1879
+ await actions.loadMonth();
1880
+ } catch (e) {
1881
+ store.setKey("loading", false);
1882
+ throw e;
1883
+ }
1884
+ },
1885
+ async loadMonth() {
1886
+ const state = store.get();
1887
+ if (!state.service) return;
1888
+ store.setKey("loading", true);
1889
+ try {
1890
+ const { currentMonth, service } = state;
1891
+ const year = currentMonth.getFullYear();
1892
+ const month = currentMonth.getMonth();
1893
+ const from = Math.floor(new Date(year, month, 1).getTime() / 1e3);
1894
+ const to = Math.floor(new Date(year, month + 1, 0, 23, 59, 59).getTime() / 1e3);
1895
+ const providers = await api.getServiceProviders({ serviceId: service.id, from, to });
1896
+ store.setKey("providers", providers || []);
1897
+ store.setKey("calendar", buildCalendar());
1898
+ } finally {
1899
+ store.setKey("loading", false);
1900
+ }
1901
+ },
1902
+ prevMonth() {
1903
+ const { currentMonth } = store.get();
1904
+ store.setKey("currentMonth", new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1));
1905
+ actions.loadMonth();
1906
+ },
1907
+ nextMonth() {
1908
+ const { currentMonth } = store.get();
1909
+ store.setKey("currentMonth", new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1));
1910
+ actions.loadMonth();
1911
+ },
1912
+ selectMethod(method) {
1913
+ store.set({
1914
+ ...store.get(),
1915
+ selectedMethod: method,
1916
+ selectedProvider: null,
1917
+ selectedDate: null,
1918
+ startDate: null,
1919
+ endDate: null,
1920
+ slots: [],
1921
+ selectedSlot: null
1922
+ });
1923
+ store.setKey("calendar", buildCalendar());
1924
+ },
1925
+ selectProvider(provider) {
1926
+ store.set({
1927
+ ...store.get(),
1928
+ selectedProvider: provider,
1929
+ selectedDate: null,
1930
+ startDate: null,
1931
+ endDate: null,
1932
+ slots: [],
1933
+ selectedSlot: null
1934
+ });
1935
+ store.setKey("calendar", buildCalendar());
1936
+ },
1937
+ selectDate(day) {
1938
+ if (day.blank || !day.available) return;
1939
+ const state = store.get();
1940
+ const slots = computeSlots(day.iso);
1941
+ store.set({ ...state, selectedDate: day.iso, slots, selectedSlot: null });
1942
+ store.setKey("calendar", buildCalendar());
1943
+ },
1944
+ selectSlot(slot) {
1945
+ store.setKey("selectedSlot", slot);
1946
+ },
1947
+ findFirstAvailable() {
1948
+ const state = store.get();
1949
+ for (const day of state.calendar) {
1950
+ if (!day.blank && day.available) {
1951
+ actions.selectDate(day);
1952
+ return;
1953
+ }
1954
+ }
1955
+ },
1956
+ updateCalendar() {
1957
+ store.setKey("calendar", buildCalendar());
1958
+ },
1959
+ addToCart() {
1960
+ const state = store.get();
1961
+ if (!state.selectedSlot) return;
1962
+ store.set({
1963
+ ...state,
1964
+ cart: [...state.cart, state.selectedSlot],
1965
+ selectedDate: null,
1966
+ startDate: null,
1967
+ endDate: null,
1968
+ slots: [],
1969
+ selectedSlot: null
1970
+ });
1971
+ store.setKey("calendar", buildCalendar());
1972
+ },
1973
+ removeFromCart(slotId) {
1974
+ const state = store.get();
1975
+ store.setKey("cart", state.cart.filter((s) => s.id !== slotId));
1976
+ },
1977
+ clearCart() {
1978
+ store.setKey("cart", []);
1979
+ },
1980
+ async checkout(options = {}) {
1981
+ const state = store.get();
1982
+ if (!state.cart.length) throw new Error("Cart is empty");
1983
+ store.setKey("loading", true);
1984
+ try {
1985
+ const result = await api.checkout({
1986
+ items: state.cart.map((s) => ({
1987
+ serviceId: s.serviceId,
1988
+ providerId: s.providerId,
1989
+ from: s.from,
1990
+ to: s.to,
1991
+ blocks: s.serviceBlocks || [],
1992
+ reservationMethod: s.reservationMethod || state.selectedMethod || "STANDARD"
1993
+ })),
1994
+ paymentMethod: options.paymentMethod,
1995
+ promoCode: options.promoCode ?? null,
1996
+ blocks: options.blocks || []
1997
+ });
1998
+ store.setKey("cart", []);
1999
+ return result;
2000
+ } finally {
2001
+ store.setKey("loading", false);
2002
+ }
2003
+ },
2004
+ async getQuote(options = {}) {
2005
+ const state = store.get();
2006
+ if (!state.cart.length) return null;
2007
+ return api.getQuote({
2008
+ items: state.cart.map((s) => ({ serviceId: s.serviceId })),
2009
+ paymentMethod: options.paymentMethod || "CASH",
2010
+ promoCode: options.promoCode
2011
+ });
2012
+ },
2013
+ async getProvidersList() {
2014
+ const state = store.get();
2015
+ if (!state.service) return [];
2016
+ const response = await api.getProviders({ serviceId: state.service.id, limit: 100 });
2017
+ return response?.items || [];
2018
+ }
2019
+ };
2020
+ return { store, ...actions };
2021
+ };
1691
2022
 
1692
2023
  // src/index.ts
1693
- var SDK_VERSION = "0.3.73";
2024
+ var SDK_VERSION = "0.3.78";
1694
2025
  var SUPPORTED_FRAMEWORKS = [
1695
2026
  "astro",
1696
2027
  "react",
@@ -1740,6 +2071,11 @@ async function createArkySDK(config) {
1740
2071
  reservation: createReservationApi(apiConfig),
1741
2072
  database: createDatabaseApi(apiConfig),
1742
2073
  featureFlags: createFeatureFlagsApi(apiConfig),
2074
+ // High-level reservation engine
2075
+ reservationEngine: (engineConfig) => {
2076
+ const reservationApi = createReservationApi(apiConfig);
2077
+ return createReservationEngine(reservationApi, engineConfig);
2078
+ },
1743
2079
  setBusinessId: (businessId) => {
1744
2080
  apiConfig.businessId = businessId;
1745
2081
  },