arky-sdk 0.3.77 → 0.3.79

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,312 @@ 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
+ currentMonth: new Date((/* @__PURE__ */ new Date()).getFullYear(), (/* @__PURE__ */ new Date()).getMonth(), 1),
1778
+ calendar: [],
1779
+ selectedDate: null,
1780
+ startDate: null,
1781
+ endDate: null,
1782
+ slots: [],
1783
+ selectedSlot: null,
1784
+ cart: [],
1785
+ timezone,
1786
+ loading: false
1787
+ });
1788
+ var createReservationEngine = (api, config = {}) => {
1789
+ const timezone = config.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
1790
+ const store = nanostores.map(createInitialState(timezone));
1791
+ const getServiceDurations = () => {
1792
+ const state = store.get();
1793
+ if (!state.service?.durations?.length) return [{ duration: 60, isPause: false }];
1794
+ return state.service.durations.map((d) => ({
1795
+ duration: d.duration,
1796
+ isPause: d.isPause || d.is_pause || false
1797
+ }));
1798
+ };
1799
+ const buildCalendar = () => {
1800
+ const state = store.get();
1801
+ const { currentMonth, selectedDate, startDate, endDate, providers, selectedProvider, timezone: timezone2 } = state;
1802
+ const year = currentMonth.getFullYear();
1803
+ const month = currentMonth.getMonth();
1804
+ const first = new Date(year, month, 1);
1805
+ const last = new Date(year, month + 1, 0);
1806
+ const today = /* @__PURE__ */ new Date();
1807
+ today.setHours(0, 0, 0, 0);
1808
+ const cells = [];
1809
+ const pad = (first.getDay() + 6) % 7;
1810
+ for (let i = 0; i < pad; i++) {
1811
+ cells.push({ date: /* @__PURE__ */ new Date(0), iso: "", available: false, isSelected: false, isInRange: false, isToday: false, blank: true });
1812
+ }
1813
+ const activeProviders = selectedProvider ? providers.filter((p) => p.id === selectedProvider.id) : providers;
1814
+ const durations = getServiceDurations();
1815
+ for (let d = 1; d <= last.getDate(); d++) {
1816
+ const date = new Date(year, month, d);
1817
+ const iso = `${year}-${String(month + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
1818
+ const available = activeProviders.length > 0 && hasAvailableSlots({ providers: activeProviders, date, durations, timezone: timezone2 });
1819
+ const isToday = date.getTime() === today.getTime();
1820
+ const isSelected = iso === selectedDate || iso === startDate || iso === endDate;
1821
+ let isInRange = false;
1822
+ if (startDate && endDate) {
1823
+ const t = date.getTime();
1824
+ isInRange = t > new Date(startDate).getTime() && t < new Date(endDate).getTime();
1825
+ }
1826
+ cells.push({ date, iso, available, isSelected, isInRange, isToday, blank: false });
1827
+ }
1828
+ const suffix = (7 - cells.length % 7) % 7;
1829
+ for (let i = 0; i < suffix; i++) {
1830
+ cells.push({ date: /* @__PURE__ */ new Date(0), iso: "", available: false, isSelected: false, isInRange: false, isToday: false, blank: true });
1831
+ }
1832
+ return cells;
1833
+ };
1834
+ const computeSlots = (dateStr) => {
1835
+ const state = store.get();
1836
+ const { providers, selectedProvider, timezone: timezone2, service } = state;
1837
+ const date = /* @__PURE__ */ new Date(dateStr + "T00:00:00");
1838
+ const activeProviders = selectedProvider ? providers.filter((p) => p.id === selectedProvider.id) : providers;
1839
+ const raw = computeSlotsForDate({ providers: activeProviders, date, durations: getServiceDurations(), timezone: timezone2 });
1840
+ return raw.map((s, i) => ({
1841
+ id: `${service?.id}-${s.from}-${i}`,
1842
+ serviceId: service?.id || "",
1843
+ providerId: s.providerId,
1844
+ from: s.from,
1845
+ to: s.to,
1846
+ timeText: formatSlotTime(s.from, s.to, timezone2),
1847
+ dateText: new Date(s.from * 1e3).toLocaleDateString([], { weekday: "short", month: "short", day: "numeric", timeZone: timezone2 })
1848
+ }));
1849
+ };
1850
+ const actions = {
1851
+ setTimezone(tz) {
1852
+ store.setKey("timezone", tz);
1853
+ store.setKey("calendar", buildCalendar());
1854
+ const state = store.get();
1855
+ if (state.selectedDate) {
1856
+ store.setKey("slots", computeSlots(state.selectedDate));
1857
+ store.setKey("selectedSlot", null);
1858
+ }
1859
+ },
1860
+ async setService(serviceId) {
1861
+ store.setKey("loading", true);
1862
+ try {
1863
+ const service = await api.getService({ id: serviceId });
1864
+ store.set({
1865
+ ...store.get(),
1866
+ service,
1867
+ selectedProvider: null,
1868
+ providers: [],
1869
+ selectedDate: null,
1870
+ startDate: null,
1871
+ endDate: null,
1872
+ slots: [],
1873
+ selectedSlot: null,
1874
+ currentMonth: new Date((/* @__PURE__ */ new Date()).getFullYear(), (/* @__PURE__ */ new Date()).getMonth(), 1),
1875
+ loading: false
1876
+ });
1877
+ await actions.loadMonth();
1878
+ } catch (e) {
1879
+ store.setKey("loading", false);
1880
+ throw e;
1881
+ }
1882
+ },
1883
+ async loadMonth() {
1884
+ const state = store.get();
1885
+ if (!state.service) return;
1886
+ store.setKey("loading", true);
1887
+ try {
1888
+ const { currentMonth, service } = state;
1889
+ const year = currentMonth.getFullYear();
1890
+ const month = currentMonth.getMonth();
1891
+ const from = Math.floor(new Date(year, month, 1).getTime() / 1e3);
1892
+ const to = Math.floor(new Date(year, month + 1, 0, 23, 59, 59).getTime() / 1e3);
1893
+ const providers = await api.getServiceProviders({ serviceId: service.id, from, to });
1894
+ store.setKey("providers", providers || []);
1895
+ store.setKey("calendar", buildCalendar());
1896
+ } finally {
1897
+ store.setKey("loading", false);
1898
+ }
1899
+ },
1900
+ prevMonth() {
1901
+ const { currentMonth } = store.get();
1902
+ store.setKey("currentMonth", new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1));
1903
+ actions.loadMonth();
1904
+ },
1905
+ nextMonth() {
1906
+ const { currentMonth } = store.get();
1907
+ store.setKey("currentMonth", new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1));
1908
+ actions.loadMonth();
1909
+ },
1910
+ selectProvider(provider) {
1911
+ store.set({
1912
+ ...store.get(),
1913
+ selectedProvider: provider,
1914
+ selectedDate: null,
1915
+ startDate: null,
1916
+ endDate: null,
1917
+ slots: [],
1918
+ selectedSlot: null
1919
+ });
1920
+ store.setKey("calendar", buildCalendar());
1921
+ },
1922
+ selectDate(day) {
1923
+ if (day.blank || !day.available) return;
1924
+ const state = store.get();
1925
+ const slots = computeSlots(day.iso);
1926
+ store.set({ ...state, selectedDate: day.iso, slots, selectedSlot: null });
1927
+ store.setKey("calendar", buildCalendar());
1928
+ },
1929
+ selectSlot(slot) {
1930
+ store.setKey("selectedSlot", slot);
1931
+ },
1932
+ findFirstAvailable() {
1933
+ const state = store.get();
1934
+ for (const day of state.calendar) {
1935
+ if (!day.blank && day.available) {
1936
+ actions.selectDate(day);
1937
+ return;
1938
+ }
1939
+ }
1940
+ },
1941
+ updateCalendar() {
1942
+ store.setKey("calendar", buildCalendar());
1943
+ },
1944
+ addToCart() {
1945
+ const state = store.get();
1946
+ if (!state.selectedSlot) return;
1947
+ store.set({
1948
+ ...state,
1949
+ cart: [...state.cart, state.selectedSlot],
1950
+ selectedDate: null,
1951
+ startDate: null,
1952
+ endDate: null,
1953
+ slots: [],
1954
+ selectedSlot: null
1955
+ });
1956
+ store.setKey("calendar", buildCalendar());
1957
+ },
1958
+ removeFromCart(slotId) {
1959
+ const state = store.get();
1960
+ store.setKey("cart", state.cart.filter((s) => s.id !== slotId));
1961
+ },
1962
+ clearCart() {
1963
+ store.setKey("cart", []);
1964
+ },
1965
+ async checkout(options = {}) {
1966
+ const state = store.get();
1967
+ if (!state.cart.length) throw new Error("Cart is empty");
1968
+ store.setKey("loading", true);
1969
+ try {
1970
+ const result = await api.checkout({
1971
+ items: state.cart.map((s) => ({
1972
+ serviceId: s.serviceId,
1973
+ providerId: s.providerId,
1974
+ from: s.from,
1975
+ to: s.to,
1976
+ blocks: s.serviceBlocks || []
1977
+ })),
1978
+ paymentMethod: options.paymentMethod,
1979
+ promoCode: options.promoCode ?? null,
1980
+ blocks: options.blocks || []
1981
+ });
1982
+ store.setKey("cart", []);
1983
+ return result;
1984
+ } finally {
1985
+ store.setKey("loading", false);
1986
+ }
1987
+ },
1988
+ async getQuote(options = {}) {
1989
+ const state = store.get();
1990
+ if (!state.cart.length) return null;
1991
+ return api.getQuote({
1992
+ items: state.cart.map((s) => ({ serviceId: s.serviceId })),
1993
+ paymentMethod: options.paymentMethod || "CASH",
1994
+ promoCode: options.promoCode
1995
+ });
1996
+ },
1997
+ async getProvidersList() {
1998
+ const state = store.get();
1999
+ if (!state.service) return [];
2000
+ const response = await api.getProviders({ serviceId: state.service.id, limit: 100 });
2001
+ return response?.items || [];
2002
+ }
2003
+ };
2004
+ return { store, ...actions };
2005
+ };
1691
2006
 
1692
2007
  // src/index.ts
1693
- var SDK_VERSION = "0.3.73";
2008
+ var SDK_VERSION = "0.3.78";
1694
2009
  var SUPPORTED_FRAMEWORKS = [
1695
2010
  "astro",
1696
2011
  "react",
@@ -1740,6 +2055,11 @@ async function createArkySDK(config) {
1740
2055
  reservation: createReservationApi(apiConfig),
1741
2056
  database: createDatabaseApi(apiConfig),
1742
2057
  featureFlags: createFeatureFlagsApi(apiConfig),
2058
+ // High-level reservation engine
2059
+ reservationEngine: (engineConfig) => {
2060
+ const reservationApi = createReservationApi(apiConfig);
2061
+ return createReservationEngine(reservationApi, engineConfig);
2062
+ },
1743
2063
  setBusinessId: (businessId) => {
1744
2064
  apiConfig.businessId = businessId;
1745
2065
  },