@oneclick.dev/cms-core-modules 0.0.82 → 0.0.84
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/{ContentEditor-Dk-iDEjl.mjs → ContentEditor-DPhhOkx3.mjs} +7085 -5936
- package/dist/{ContentEditor-4e80zFyn.js → ContentEditor-DrxtH_Hq.js} +42 -42
- package/dist/{Create-DtFzwxn_.mjs → Create-6uT9HWar.mjs} +35 -35
- package/dist/{Create-CRn2sMHp.js → Create-DuZ5nZrX.js} +1 -1
- package/dist/{DateFormatter-DfIwyrnF.mjs → DateFormatter-2B0R-DY4.mjs} +213 -406
- package/dist/DateFormatter-DbtOLV0L.js +1 -0
- package/dist/{Detail-Bxi7lG9x.js → Detail-BZ-iE9vf.js} +1 -1
- package/dist/{Detail-B4b_FLDa.mjs → Detail-C1Blq61w.mjs} +90 -90
- package/dist/{Detail-BayNaAg9.js → Detail-C8wQiDcv.js} +1 -1
- package/dist/{Detail-BwDnY42G.mjs → Detail-CJVMJDP7.mjs} +17 -17
- package/dist/{Detail-CnK-qbhE.js → Detail-CPqug27l.js} +1 -1
- package/dist/Detail-CjuhjPby.js +1 -0
- package/dist/{Detail-U0mgLKt6.mjs → Detail-CtItxMX4.mjs} +62 -63
- package/dist/{Detail-CVgWHbMC.mjs → Detail-Dnpnmy4-.mjs} +158 -158
- package/dist/{Entries-D7MHylQE.mjs → Entries-BkOPae4R.mjs} +49 -49
- package/dist/Entries-CcEW98F5.js +1 -0
- package/dist/{NewReservationDialog.vue_vue_type_script_setup_true_lang-Ds7z0qeH.mjs → NewReservationDialog.vue_vue_type_script_setup_true_lang-Bc946oSc.mjs} +1 -1
- package/dist/{NewReservationDialog.vue_vue_type_script_setup_true_lang-C5YczjNb.js → NewReservationDialog.vue_vue_type_script_setup_true_lang-CqERfyYb.js} +1 -1
- package/dist/{Overview-CwCAeBnX.js → Overview-CA8wh_BI.js} +1 -1
- package/dist/{Overview-CgViRnNc.mjs → Overview-D4MFwRI_.mjs} +67 -68
- package/dist/{Overview-pCO_47Zt.js → Overview-Da0XexiT.js} +1 -1
- package/dist/Overview-DeQQ0FY3.js +1 -0
- package/dist/{Overview--XpvBbqz.mjs → Overview-DoOASlNz.mjs} +1 -3
- package/dist/{Overview-CuCQgqVp.mjs → Overview-gJSvftdE.mjs} +34 -34
- package/dist/{ReservationDetailDialog.vue_vue_type_script_setup_true_lang-B7ks5mbf.mjs → ReservationDetailDialog.vue_vue_type_script_setup_true_lang-Cohhnd5x.mjs} +0 -1
- package/dist/{ReservationDetailDialog.vue_vue_type_script_setup_true_lang-Vxubki_v.js → ReservationDetailDialog.vue_vue_type_script_setup_true_lang-VWVIxIr6.js} +1 -1
- package/dist/{SeoHealth-CC0rW1AG.mjs → SeoHealth-Bc5chnaa.mjs} +14 -14
- package/dist/{SeoHealth-EZzDmPDM.js → SeoHealth-BkpJ1F2Y.js} +1 -1
- package/dist/TableView-BPWAx--G.mjs +5743 -0
- package/dist/TableView-D63QrVlK.js +4 -0
- package/dist/View-BL70u98U.js +1 -0
- package/dist/{View-DDXN0tKD.mjs → View-BO5N911y.mjs} +5 -5
- package/dist/{agenda-XqvbrU72.mjs → agenda-C5grvzSa.mjs} +166 -169
- package/dist/agenda-DXMwVWpN.js +1 -0
- package/dist/{availability-B-tRp8hB.mjs → availability-C1NqOFsQ.mjs} +81 -81
- package/dist/{availability-BiBbzEIM.js → availability-D_wnfLsH.js} +1 -1
- package/dist/cms-core-modules.css +1 -1
- package/dist/{exceptions-CLgeeUSy.mjs → exceptions-BIwMhYa4.mjs} +1 -1
- package/dist/{exceptions-wEQEVzIs.js → exceptions-Cn7zooEu.js} +1 -1
- package/dist/{index-DTzdHh6g.js → index-C9pSS15N.js} +2 -2
- package/dist/{index-N0NoDEsI.mjs → index-MwjeLHPP.mjs} +3 -3
- package/dist/index.cjs.js +1 -1
- package/dist/index.mjs +50 -36
- package/dist/orders-CG1QUCN8.js +1 -0
- package/dist/orders-CeixEBcU.mjs +396 -0
- package/dist/server-handlers.cjs.js +1 -1
- package/dist/server-handlers.mjs +292 -256
- package/dist/src/contentManager/config.d.ts +28 -0
- package/dist/src/contentManager/index.d.ts +28 -0
- package/dist/src/contentManager/server.d.ts +7 -0
- package/dist/src/server-handlers.d.ts +1 -0
- package/package.json +2 -2
- package/dist/DateFormatter-C9qfmQnP.js +0 -1
- package/dist/Detail-BcboL7NF.js +0 -1
- package/dist/Entries-BPkZ7Jg5.js +0 -1
- package/dist/Overview-B-8TLLjh.js +0 -1
- package/dist/TableView-Ce8H65pL.js +0 -586
- package/dist/TableView-DRQvOW85.mjs +0 -89190
- package/dist/View-DfzaVOzS.js +0 -1
- package/dist/agenda-wNFDKn0G.js +0 -1
- package/dist/floating-ui.dom-BO2Hr6mz.mjs +0 -1292
- package/dist/floating-ui.dom-CAr9LGoC.js +0 -1
- package/dist/index-DYpruS-A-CA2jEOA3.js +0 -88
- package/dist/index-DYpruS-A-D38FBcI3.mjs +0 -4211
- package/dist/index-YMaY4uuk-BgpTtr73.js +0 -1
- package/dist/index-YMaY4uuk-C_xV5K9Z.mjs +0 -1300
- package/dist/orders-Bqa3Z3tH.mjs +0 -356
- package/dist/orders-D5GJOZXN.js +0 -1
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import { defineComponent as ee, ref as w, computed as b, provide as te, onMounted as se, watch as oe, resolveComponent as x, openBlock as c, createElementBlock as m, Fragment as U, createVNode as r, withCtx as f, createElementVNode as s, unref as o, createTextVNode as C, createBlock as j, toDisplayString as d, createCommentVNode as I, normalizeClass as ne, isRef as ae, renderList as re, normalizeStyle as ie, nextTick as le } from "vue";
|
|
2
|
+
import { useRoute as ce, useRouter as de, useModuleRoute as ue, useModule as me, useFirebaseIntegration as pe } from "@oneclick.dev/cms-kit";
|
|
3
|
+
import { ShoppingBag as L, Users as V, ChevronLeft as fe, ChevronRight as ge, RefreshCw as ve, Search as _e, X as xe, Calendar as he, Clock as ye } from "lucide-vue-next";
|
|
4
|
+
import { F as De, _ as we } from "./ReservationDetailDialog.vue_vue_type_script_setup_true_lang-Cohhnd5x.mjs";
|
|
5
|
+
import { _ as ke } from "./EditLayout.vue_vue_type_script_setup_true_lang-CcysXzmW.mjs";
|
|
6
|
+
const be = { class: "space-y-6" }, Ce = { class: "flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4" }, Ie = { class: "text-2xl font-semibold tracking-tight flex items-center gap-2" }, Se = { class: "flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4" }, Pe = { class: "flex items-center gap-1" }, Oe = { class: "flex items-center gap-1" }, Te = { class: "flex items-center gap-2" }, ze = { class: "flex items-center gap-1" }, Ne = { class: "text-sm text-muted-foreground mt-2" }, Ae = { class: "relative mb-4" }, Re = {
|
|
7
|
+
key: 0,
|
|
8
|
+
class: "mb-3 text-sm text-muted-foreground"
|
|
9
|
+
}, Be = {
|
|
10
|
+
key: 1,
|
|
11
|
+
class: "flex items-center justify-center py-8"
|
|
12
|
+
}, Fe = {
|
|
13
|
+
key: 2,
|
|
14
|
+
class: "text-center py-8 text-muted-foreground"
|
|
15
|
+
}, Ue = {
|
|
16
|
+
key: 3,
|
|
17
|
+
class: "text-center py-8 text-muted-foreground"
|
|
18
|
+
}, je = {
|
|
19
|
+
key: 4,
|
|
20
|
+
class: "space-y-2"
|
|
21
|
+
}, Le = ["onClick"], Ve = { class: "flex items-start justify-between" }, Ee = { class: "flex-1" }, $e = { class: "font-medium" }, He = { class: "text-sm text-muted-foreground" }, Me = { class: "text-sm text-muted-foreground" }, qe = { class: "flex items-center gap-4 flex-wrap mt-1" }, Ye = { class: "flex items-center gap-2 text-xs text-muted-foreground" }, Qe = { class: "flex items-center gap-2 text-xs text-muted-foreground" }, Xe = {
|
|
22
|
+
key: 0,
|
|
23
|
+
class: "flex items-center gap-1 text-xs text-muted-foreground"
|
|
24
|
+
}, Ge = { class: "flex items-center gap-2 mt-1 text-xs text-muted-foreground" }, Je = { class: "text-right" }, Ke = {
|
|
25
|
+
key: 0,
|
|
26
|
+
class: "inline-block px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
|
|
27
|
+
}, We = {
|
|
28
|
+
key: 1,
|
|
29
|
+
class: "inline-block px-2 py-1 text-xs rounded-full bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400"
|
|
30
|
+
}, Ze = {
|
|
31
|
+
key: 2,
|
|
32
|
+
class: "inline-block px-2 py-1 text-xs rounded-full bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"
|
|
33
|
+
}, et = {
|
|
34
|
+
key: 3,
|
|
35
|
+
class: "inline-block px-2 py-1 text-xs rounded-full bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"
|
|
36
|
+
}, tt = {
|
|
37
|
+
key: 4,
|
|
38
|
+
class: "inline-block px-2 py-1 text-xs rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"
|
|
39
|
+
}, st = {
|
|
40
|
+
key: 5,
|
|
41
|
+
class: "text-sm font-medium mt-1"
|
|
42
|
+
}, dt = /* @__PURE__ */ ee({
|
|
43
|
+
__name: "orders",
|
|
44
|
+
setup(ot) {
|
|
45
|
+
const z = ce();
|
|
46
|
+
de();
|
|
47
|
+
const { params: F } = ue(), { config: S } = me(), N = pe(S.project), g = w([]), P = w([]), k = w(!0), _ = w(""), A = w(null), h = /* @__PURE__ */ new Date(), p = w(/* @__PURE__ */ new Date()), E = b(() => ({
|
|
48
|
+
date: Q(p.value),
|
|
49
|
+
resource: null
|
|
50
|
+
}));
|
|
51
|
+
te("event", E);
|
|
52
|
+
const $ = b(() => {
|
|
53
|
+
const e = new Date(h);
|
|
54
|
+
e.setDate(h.getDate() - 1);
|
|
55
|
+
const t = new Date(h);
|
|
56
|
+
return t.setDate(h.getDate() + 1), p.value.toDateString() === h.toDateString() ? "Today" : p.value.toDateString() === e.toDateString() ? "Yesterday" : p.value.toDateString() === t.toDateString() ? "Tomorrow" : p.value.toLocaleDateString("en-US", {
|
|
57
|
+
weekday: "long",
|
|
58
|
+
month: "long",
|
|
59
|
+
day: "numeric",
|
|
60
|
+
year: "numeric"
|
|
61
|
+
});
|
|
62
|
+
}), H = () => {
|
|
63
|
+
const e = new Date(p.value);
|
|
64
|
+
e.setDate(e.getDate() - 1), p.value = e;
|
|
65
|
+
}, M = () => {
|
|
66
|
+
const e = new Date(p.value);
|
|
67
|
+
e.setDate(e.getDate() + 1), e <= h && (p.value = e);
|
|
68
|
+
}, q = b(() => {
|
|
69
|
+
const e = new Date(p.value);
|
|
70
|
+
return e.setDate(e.getDate() + 1), e <= h;
|
|
71
|
+
}), Y = () => {
|
|
72
|
+
p.value = /* @__PURE__ */ new Date();
|
|
73
|
+
}, Q = (e) => {
|
|
74
|
+
const t = e.getFullYear(), a = String(e.getMonth() + 1).padStart(2, "0"), i = String(e.getDate()).padStart(2, "0");
|
|
75
|
+
return `${t}-${a}-${i}`;
|
|
76
|
+
}, X = (e) => e ? new Date(e).toLocaleTimeString("en-US", {
|
|
77
|
+
hour: "2-digit",
|
|
78
|
+
minute: "2-digit",
|
|
79
|
+
hour12: !1
|
|
80
|
+
}) : "", G = (e) => e ? new Date(e).toLocaleDateString("en-US", {
|
|
81
|
+
weekday: "short",
|
|
82
|
+
month: "short",
|
|
83
|
+
day: "numeric"
|
|
84
|
+
}) : "", R = b(() => _.value.trim() ? new De(g.value, {
|
|
85
|
+
keys: [
|
|
86
|
+
"customerInfo.firstName",
|
|
87
|
+
"customerInfo.lastName",
|
|
88
|
+
"customerInfo.email",
|
|
89
|
+
"customerInfo.phone",
|
|
90
|
+
"resourceName"
|
|
91
|
+
],
|
|
92
|
+
threshold: 0.3,
|
|
93
|
+
ignoreLocation: !0
|
|
94
|
+
}).search(_.value).map((t) => t.item) : g.value), O = b(() => ({
|
|
95
|
+
spots: g.value.reduce((e, t) => e + (t.spots || 0), 0),
|
|
96
|
+
bookings: g.value.length,
|
|
97
|
+
revenue: g.value.reduce((e, t) => e + (t.reservationPrice || 0), 0)
|
|
98
|
+
})), J = () => {
|
|
99
|
+
_.value = "";
|
|
100
|
+
}, K = async () => {
|
|
101
|
+
try {
|
|
102
|
+
const e = F.value.id, t = await N.get(S.agendaCollection, e);
|
|
103
|
+
P.value = t?.resources?.filter((a) => a.isActive) || [];
|
|
104
|
+
} catch (e) {
|
|
105
|
+
console.error("Error loading resources:", e), P.value = [];
|
|
106
|
+
}
|
|
107
|
+
}, y = async () => {
|
|
108
|
+
k.value = !0, g.value = [];
|
|
109
|
+
try {
|
|
110
|
+
const e = F.value.id, t = new Date(p.value);
|
|
111
|
+
t.setHours(0, 0, 0, 0);
|
|
112
|
+
const a = new Date(p.value);
|
|
113
|
+
a.setHours(23, 59, 59, 999);
|
|
114
|
+
const i = await N.find(S.reservationsCollection, {
|
|
115
|
+
filters: [
|
|
116
|
+
{ field: "agendaId", operator: "==", value: e },
|
|
117
|
+
{ field: "createdAt", operator: ">=", value: t.toISOString() },
|
|
118
|
+
{ field: "createdAt", operator: "<=", value: a.toISOString() }
|
|
119
|
+
]
|
|
120
|
+
});
|
|
121
|
+
let v = [];
|
|
122
|
+
i.forEach((l) => {
|
|
123
|
+
(l.reservations || []).forEach((u) => {
|
|
124
|
+
const T = P.value.find((B) => B.id === u.resourceId);
|
|
125
|
+
v.push({
|
|
126
|
+
customerInfo: l.customerInfo,
|
|
127
|
+
amountDue: l.amountDue,
|
|
128
|
+
amountPaid: l.amountPaid,
|
|
129
|
+
status: l.status,
|
|
130
|
+
reservationStatus: u.status,
|
|
131
|
+
subtotal: l.subtotal,
|
|
132
|
+
total: l.total,
|
|
133
|
+
discount: l.discount,
|
|
134
|
+
id: l.id,
|
|
135
|
+
res_id: u.id,
|
|
136
|
+
resourceId: u.resourceId,
|
|
137
|
+
spots: u.spots,
|
|
138
|
+
date: u.date,
|
|
139
|
+
createdAt: l.createdAt,
|
|
140
|
+
startTime: u.timeslot?.startTime,
|
|
141
|
+
endTime: u.timeslot?.endTime,
|
|
142
|
+
reservationPrice: u.totalPrice,
|
|
143
|
+
reservationBasePrice: u.basePrice,
|
|
144
|
+
reservationAddOnsPrice: u.addOnsPrice,
|
|
145
|
+
pricingOptionId: u.pricingOptionId,
|
|
146
|
+
pricingOption: u.pricingOption,
|
|
147
|
+
resourceName: T?.name || "Unknown",
|
|
148
|
+
resourceColor: T?.color
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
}), g.value = v.sort((l, D) => (D.createdAt || "").localeCompare(l.createdAt || ""));
|
|
152
|
+
} catch (e) {
|
|
153
|
+
console.error("Error loading orders:", e), g.value = [];
|
|
154
|
+
} finally {
|
|
155
|
+
k.value = !1;
|
|
156
|
+
}
|
|
157
|
+
}, W = async () => {
|
|
158
|
+
await K(), await y();
|
|
159
|
+
}, Z = async (e, t) => {
|
|
160
|
+
const a = await N.get(S.reservationsCollection, e), i = a?.reservations?.find((v) => v.id === t);
|
|
161
|
+
if (i) {
|
|
162
|
+
const v = P.value.find((D) => D.id === i.resourceId), l = {
|
|
163
|
+
customerInfo: a.customerInfo,
|
|
164
|
+
amountDue: a.amountDue,
|
|
165
|
+
amountPaid: a.amountPaid,
|
|
166
|
+
status: a.status,
|
|
167
|
+
reservationStatus: i.status,
|
|
168
|
+
subtotal: a.subtotal,
|
|
169
|
+
total: a.total,
|
|
170
|
+
discount: a.discount,
|
|
171
|
+
id: a.id,
|
|
172
|
+
res_id: i.id,
|
|
173
|
+
resourceId: i.resourceId,
|
|
174
|
+
spots: i.spots,
|
|
175
|
+
date: i.date,
|
|
176
|
+
createdAt: a.createdAt,
|
|
177
|
+
startTime: i.timeslot?.startTime,
|
|
178
|
+
endTime: i.timeslot?.endTime,
|
|
179
|
+
reservationPrice: i.totalPrice,
|
|
180
|
+
reservationBasePrice: i.basePrice,
|
|
181
|
+
reservationAddOnsPrice: i.addOnsPrice,
|
|
182
|
+
pricingOptionId: i.pricingOptionId,
|
|
183
|
+
pricingOption: i.pricingOption,
|
|
184
|
+
resourceName: v?.name || "Unknown",
|
|
185
|
+
resourceColor: v?.color
|
|
186
|
+
};
|
|
187
|
+
await le(), A.value?.openDialog(l);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
return W(), se(async () => {
|
|
191
|
+
if (z.query.orderId) {
|
|
192
|
+
const e = z.query.orderId, t = z.query.reservationId, a = new URL(window.location.href);
|
|
193
|
+
a.searchParams.delete("orderId"), a.searchParams.delete("reservationId"), window.history.replaceState(window.history.state, "", a.toString()), await Z(e, t);
|
|
194
|
+
}
|
|
195
|
+
}), oe(p, () => {
|
|
196
|
+
y();
|
|
197
|
+
}), (e, t) => {
|
|
198
|
+
const a = x("Badge"), i = x("CardTitle"), v = x("CardDescription"), l = x("Button"), D = x("CardHeader"), u = x("Input"), T = x("CardContent"), B = x("Card");
|
|
199
|
+
return c(), m(U, null, [
|
|
200
|
+
r(ke, null, {
|
|
201
|
+
default: f(() => [
|
|
202
|
+
s("div", be, [
|
|
203
|
+
s("div", Ce, [
|
|
204
|
+
s("div", null, [
|
|
205
|
+
s("h1", Ie, [
|
|
206
|
+
r(o(L), { class: "size-6" }),
|
|
207
|
+
t[1] || (t[1] = C(" Orders ", -1))
|
|
208
|
+
]),
|
|
209
|
+
t[2] || (t[2] = s("p", { class: "text-muted-foreground text-sm mt-1" }, " View orders by when they were placed ", -1))
|
|
210
|
+
])
|
|
211
|
+
]),
|
|
212
|
+
r(B, null, {
|
|
213
|
+
default: f(() => [
|
|
214
|
+
r(D, null, {
|
|
215
|
+
default: f(() => [
|
|
216
|
+
s("div", Se, [
|
|
217
|
+
s("div", null, [
|
|
218
|
+
r(i, { class: "flex items-center gap-2" }, {
|
|
219
|
+
default: f(() => [
|
|
220
|
+
t[3] || (t[3] = C(" Orders received ", -1)),
|
|
221
|
+
o(O).bookings > 0 ? (c(), j(a, {
|
|
222
|
+
key: 0,
|
|
223
|
+
variant: "secondary"
|
|
224
|
+
}, {
|
|
225
|
+
default: f(() => [
|
|
226
|
+
C(d(o(O).bookings), 1)
|
|
227
|
+
]),
|
|
228
|
+
_: 1
|
|
229
|
+
})) : I("", !0)
|
|
230
|
+
]),
|
|
231
|
+
_: 1
|
|
232
|
+
}),
|
|
233
|
+
r(v, { class: "flex items-center gap-4 mt-1" }, {
|
|
234
|
+
default: f(() => [
|
|
235
|
+
s("span", Pe, [
|
|
236
|
+
r(o(V), { size: 14 }),
|
|
237
|
+
C(" " + d(o(O).spots) + " spots ", 1)
|
|
238
|
+
]),
|
|
239
|
+
s("span", Oe, " €" + d(o(O).revenue.toFixed(2)) + " revenue ", 1)
|
|
240
|
+
]),
|
|
241
|
+
_: 1
|
|
242
|
+
})
|
|
243
|
+
]),
|
|
244
|
+
s("div", Te, [
|
|
245
|
+
s("div", ze, [
|
|
246
|
+
r(l, {
|
|
247
|
+
variant: "ghost",
|
|
248
|
+
size: "icon",
|
|
249
|
+
class: "size-8",
|
|
250
|
+
onClick: H
|
|
251
|
+
}, {
|
|
252
|
+
default: f(() => [
|
|
253
|
+
r(o(fe), { size: 16 })
|
|
254
|
+
]),
|
|
255
|
+
_: 1
|
|
256
|
+
}),
|
|
257
|
+
r(l, {
|
|
258
|
+
variant: "ghost",
|
|
259
|
+
size: "sm",
|
|
260
|
+
class: "h-8 px-3 text-xs",
|
|
261
|
+
onClick: Y
|
|
262
|
+
}, {
|
|
263
|
+
default: f(() => [...t[4] || (t[4] = [
|
|
264
|
+
C(" Today ", -1)
|
|
265
|
+
])]),
|
|
266
|
+
_: 1
|
|
267
|
+
}),
|
|
268
|
+
r(l, {
|
|
269
|
+
variant: "ghost",
|
|
270
|
+
size: "icon",
|
|
271
|
+
class: "size-8",
|
|
272
|
+
onClick: M,
|
|
273
|
+
disabled: !o(q)
|
|
274
|
+
}, {
|
|
275
|
+
default: f(() => [
|
|
276
|
+
r(o(ge), { size: 16 })
|
|
277
|
+
]),
|
|
278
|
+
_: 1
|
|
279
|
+
}, 8, ["disabled"])
|
|
280
|
+
]),
|
|
281
|
+
r(l, {
|
|
282
|
+
variant: "ghost",
|
|
283
|
+
size: "icon",
|
|
284
|
+
onClick: y,
|
|
285
|
+
disabled: o(k)
|
|
286
|
+
}, {
|
|
287
|
+
default: f(() => [
|
|
288
|
+
r(o(ve), {
|
|
289
|
+
size: 16,
|
|
290
|
+
class: ne({ "animate-spin": o(k) })
|
|
291
|
+
}, null, 8, ["class"])
|
|
292
|
+
]),
|
|
293
|
+
_: 1
|
|
294
|
+
}, 8, ["disabled"])
|
|
295
|
+
])
|
|
296
|
+
]),
|
|
297
|
+
s("div", Ne, d(o($)), 1)
|
|
298
|
+
]),
|
|
299
|
+
_: 1
|
|
300
|
+
}),
|
|
301
|
+
r(T, null, {
|
|
302
|
+
default: f(() => [
|
|
303
|
+
s("div", Ae, [
|
|
304
|
+
r(o(_e), {
|
|
305
|
+
size: 16,
|
|
306
|
+
class: "absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
|
|
307
|
+
}),
|
|
308
|
+
r(u, {
|
|
309
|
+
modelValue: o(_),
|
|
310
|
+
"onUpdate:modelValue": t[0] || (t[0] = (n) => ae(_) ? _.value = n : null),
|
|
311
|
+
placeholder: "Search by name, email, or phone...",
|
|
312
|
+
class: "pl-9 pr-9"
|
|
313
|
+
}, null, 8, ["modelValue"]),
|
|
314
|
+
o(_) ? (c(), j(l, {
|
|
315
|
+
key: 0,
|
|
316
|
+
variant: "ghost",
|
|
317
|
+
size: "icon",
|
|
318
|
+
class: "absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7",
|
|
319
|
+
onClick: J
|
|
320
|
+
}, {
|
|
321
|
+
default: f(() => [
|
|
322
|
+
r(o(xe), { size: 14 })
|
|
323
|
+
]),
|
|
324
|
+
_: 1
|
|
325
|
+
})) : I("", !0)
|
|
326
|
+
]),
|
|
327
|
+
o(_) ? (c(), m("div", Re, " Showing " + d(o(R).length) + " of " + d(o(g).length) + " orders ", 1)) : I("", !0),
|
|
328
|
+
o(k) ? (c(), m("div", Be, [...t[5] || (t[5] = [
|
|
329
|
+
s("div", { class: "animate-spin rounded-full h-8 w-8 border-b-2 border-primary" }, null, -1)
|
|
330
|
+
])])) : o(g).length === 0 ? (c(), m("div", Fe, [
|
|
331
|
+
r(o(L), { class: "size-12 mx-auto mb-3 opacity-50" }),
|
|
332
|
+
t[6] || (t[6] = s("p", null, "No orders received on this day", -1))
|
|
333
|
+
])) : o(R).length === 0 ? (c(), m("div", Ue, " No orders match your search ")) : (c(), m("div", je, [
|
|
334
|
+
(c(!0), m(U, null, re(o(R), (n) => (c(), m("div", {
|
|
335
|
+
key: n.res_id || n.id,
|
|
336
|
+
class: "p-3 border rounded-lg hover:bg-muted/50 transition-colors cursor-pointer",
|
|
337
|
+
onClick: (nt) => o(A)?.openDialog(n)
|
|
338
|
+
}, [
|
|
339
|
+
s("div", Ve, [
|
|
340
|
+
s("div", Ee, [
|
|
341
|
+
s("div", $e, d(n.customerInfo?.firstName) + " " + d(n.customerInfo?.lastName || "Unknown Customer"), 1),
|
|
342
|
+
s("div", He, d(n.customerInfo?.email), 1),
|
|
343
|
+
s("div", Me, d(n.customerInfo?.phone), 1),
|
|
344
|
+
s("div", qe, [
|
|
345
|
+
s("div", Ye, [
|
|
346
|
+
r(o(he), { size: 12 }),
|
|
347
|
+
s("span", null, d(G(n.date)) + " · " + d(n.startTime) + " - " + d(n.endTime), 1)
|
|
348
|
+
]),
|
|
349
|
+
s("div", Qe, [
|
|
350
|
+
r(o(V), { size: 12 }),
|
|
351
|
+
s("span", null, d(n.spots) + " spots", 1)
|
|
352
|
+
]),
|
|
353
|
+
n.resourceName ? (c(), m("div", Xe, [
|
|
354
|
+
s("div", {
|
|
355
|
+
class: "w-3 h-3 rounded-full",
|
|
356
|
+
style: ie({ backgroundColor: n.resourceColor || "#6b7280" })
|
|
357
|
+
}, null, 4),
|
|
358
|
+
s("span", null, d(n.resourceName), 1)
|
|
359
|
+
])) : I("", !0)
|
|
360
|
+
]),
|
|
361
|
+
s("div", Ge, [
|
|
362
|
+
r(o(ye), { size: 12 }),
|
|
363
|
+
s("span", null, "Ordered at " + d(X(n.createdAt)), 1)
|
|
364
|
+
])
|
|
365
|
+
]),
|
|
366
|
+
s("div", Je, [
|
|
367
|
+
n.reservationStatus === "needs_approval" ? (c(), m("span", Ke, "Needs Approval")) : n.reservationStatus === "approved" ? (c(), m("span", We, "Approved")) : n.reservationStatus === "rejected" ? (c(), m("span", Ze, "Rejected")) : n.reservationStatus === "cancelled" ? (c(), m("span", et, "Cancelled")) : (c(), m("span", tt, "Pending")),
|
|
368
|
+
n.reservationPrice || n.reservationPrice === 0 ? (c(), m("div", st, " €" + d(n.reservationPrice.toFixed(2)), 1)) : I("", !0)
|
|
369
|
+
])
|
|
370
|
+
])
|
|
371
|
+
], 8, Le))), 128))
|
|
372
|
+
]))
|
|
373
|
+
]),
|
|
374
|
+
_: 1
|
|
375
|
+
})
|
|
376
|
+
]),
|
|
377
|
+
_: 1
|
|
378
|
+
})
|
|
379
|
+
])
|
|
380
|
+
]),
|
|
381
|
+
_: 1
|
|
382
|
+
}),
|
|
383
|
+
r(we, {
|
|
384
|
+
ref_key: "reservationDetailDialog",
|
|
385
|
+
ref: A,
|
|
386
|
+
onCancelled: y,
|
|
387
|
+
onConfirmed: y,
|
|
388
|
+
onRejected: y
|
|
389
|
+
}, null, 512)
|
|
390
|
+
], 64);
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
export {
|
|
395
|
+
dt as default
|
|
396
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("h3");require("vue");function M(f){const{initFirebase:E,normalizeTimestamps:D}=f,g=r.createRouter();async function l(u){const{supabase:d,instanceId:y}=u.context.module,{data:e,error:n}=await d.from("project_modules").select("config").eq("id",y).single();if(n||!e?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const o=e.config,t=o.project,s=o.productCollection||"products";if(!t)throw r.createError({statusCode:400,statusMessage:"Products module has no Firebase integration configured."});return{firebase:await E(u,t),collection:s}}return g.get("/products",r.defineEventHandler(async u=>{try{const{firebase:d,collection:y}=await l(u);return(await d.firestore().collection(y).get()).docs.map(n=>D({id:n.id,...n.data()}))}catch(d){throw console.error("Products handler — list error:",d),r.createError({statusCode:d.statusCode||500,statusMessage:d.statusMessage||"Failed to list products"})}})),g.get("/products/:productId",r.defineEventHandler(async u=>{const d=r.getRouterParam(u,"productId");if(!d)throw r.createError({statusCode:400,statusMessage:"Product ID is required."});try{const{firebase:y,collection:e}=await l(u),n=await y.firestore().collection(e).doc(d).get();if(!n.exists)throw r.createError({statusCode:404,statusMessage:"Product not found."});return D({id:n.id,...n.data()})}catch(y){throw console.error("Products handler — get error:",y),r.createError({statusCode:y.statusCode||500,statusMessage:y.statusMessage||"Failed to get product"})}})),g.get("/empty-stock",r.defineEventHandler(async u=>{const y=r.getQuery(u).category;try{const{firebase:e,collection:n}=await l(u);let o=e.firestore().collection(n).where("stock","==",0);y&&(o=o.where("collections","array-contains",y));const s=(await o.get()).docs.map(a=>D({id:a.id,...a.data()}));return{count:s.length,products:s.map(a=>({id:a.id,title:a.title,slug:a.slug,stock:a.stock,price:a.price,currency:a.currency,status:a.status}))}}catch(e){throw console.error("Products handler — empty-stock error:",e),r.createError({statusCode:e.statusCode||500,statusMessage:e.statusMessage||"Failed to query empty stock"})}})),g.handler}function T(f){const{initFirebase:E,normalizeTimestamps:D}=f,g=r.createRouter();async function l(d){const{supabase:y,instanceId:e}=d.context.module,{data:n,error:o}=await y.from("project_modules").select("config").eq("id",e).single();if(o||!n?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const t=n.config,s=t.project,a=t.reservationsCollection||"bookings_orders",i=t.agendaCollection||"agendas";if(!s)throw r.createError({statusCode:400,statusMessage:"Appointments module has no Firebase integration configured."});return{firebase:await E(d,s),reservationsCollection:a,agendaCollection:i}}function u(d){return(d.reservations||[]).map(e=>({orderId:d.id,reservationId:e.id,customerInfo:d.customerInfo,date:e.date,startTime:e.timeslot?.startTime,endTime:e.timeslot?.endTime,spots:e.spots,status:d.status,reservationStatus:e.status,resourceId:e.resourceId,reservationPrice:e.totalPrice,reservationBasePrice:e.basePrice,reservationAddOnsPrice:e.addOnsPrice,pricingOption:e.pricingOption,amountDue:d.amountDue,amountPaid:d.amountPaid,createdAt:d.createdAt}))}return g.get("/appointments",r.defineEventHandler(async d=>{const y=r.getQuery(d),e=Math.min(Number(y.quantity)||20,100);try{const{firebase:n,reservationsCollection:o}=await l(d),s=(await n.firestore().collection(o).orderBy("createdAt","desc").limit(e).get()).docs.flatMap(a=>u(D({id:a.id,...a.data()})));return{count:s.length,appointments:s}}catch(n){throw console.error("Appointments handler — list error:",n),r.createError({statusCode:n.statusCode||500,statusMessage:n.statusMessage||"Failed to list appointments"})}})),g.get("/appointments/find",r.defineEventHandler(async d=>{const y=r.getQuery(d),e=(y.name||"").toLowerCase().trim(),n=(y.email||"").toLowerCase().trim(),o=y.date;try{const{firebase:t,reservationsCollection:s}=await l(d);let a=t.firestore().collection(s);n&&(a=a.where("customerInfo.email","==",n));let c=(await a.orderBy("createdAt","desc").limit(200).get()).docs.flatMap(m=>u(D({id:m.id,...m.data()})));return o&&(c=c.filter(m=>m.date===o)),e&&(c=c.filter(m=>{const p=(m.customerInfo?.firstName||"").toLowerCase(),w=(m.customerInfo?.lastName||"").toLowerCase();return p.includes(e)||w.includes(e)||`${p} ${w}`.includes(e)})),{count:c.length,appointments:c}}catch(t){throw console.error("Appointments handler — find error:",t),r.createError({statusCode:t.statusCode||500,statusMessage:t.statusMessage||"Failed to find appointments"})}})),g.get("/appointments/:appointmentId",r.defineEventHandler(async d=>{const y=r.getRouterParam(d,"appointmentId");if(!y)throw r.createError({statusCode:400,statusMessage:"Appointment ID is required."});try{const{firebase:e,reservationsCollection:n}=await l(d);console.log("Fetching appointment with ID:",y,n);const o=await e.firestore().collection(n).doc(y).get();if(!o.exists)throw r.createError({statusCode:404,statusMessage:"Appointment not found."});const t=D({id:o.id,...o.data()});return{...t,reservations:u(t)}}catch(e){throw console.error("Appointments handler — get error:",e),r.createError({statusCode:e.statusCode||500,statusMessage:e.statusMessage||"Failed to get appointment"})}})),g.handler}const S="https://analyticsdata.googleapis.com/v1beta",N=["https://www.googleapis.com/auth/analytics.readonly","https://www.googleapis.com/auth/webmasters.readonly"],I="https://searchconsole.googleapis.com/webmasters/v3";function U(f){const{decrypt:E,getGoogleAccessToken:D}=f,g=r.createRouter();async function l(e){const{supabase:n,instanceId:o}=e.context.module,{data:t,error:s}=await n.from("project_modules").select("config").eq("id",o).single();if(s||!t?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const a=t.config,i=a.propertyId,c=a.serviceAccount,m=a.siteUrl||"";if(!c)throw r.createError({statusCode:400,statusMessage:"No Google Service Account configured for this module."});if(!i)throw r.createError({statusCode:400,statusMessage:"No GA4 Property ID configured for this module."});const{data:p,error:w}=await n.from("integrations").select("config").eq("id",c).single();let h=p?.config;if(w||!h){const{data:P,error:q}=await n.from("agency_integrations").select("config").eq("id",c).single();if(q||!P?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load Google Service Account credentials."});h=P.config}const A=E(h.clientEmail),v=E(h.privateKey),R=E(h.projectId);return{accessToken:await D({clientEmail:A,privateKey:v,projectId:R},N),propertyId:i,siteUrl:m}}async function u(e,n,o){const t=await fetch(`${S}/properties/${n}:runReport`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){const s=await t.json().catch(()=>({}));throw console.error("GA4 runReport failed:",s),r.createError({statusCode:t.status,statusMessage:s?.error?.message||"GA4 API request failed"})}return t.json()}g.get("/report",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=s.match(/^(\d+)daysAgo$/),c=i?parseInt(i[1],10):30,m=`${c*2}daysAgo`,p=`${c+1}daysAgo`,w=[{name:"sessions"},{name:"totalUsers"},{name:"screenPageViews"},{name:"bounceRate"},{name:"averageSessionDuration"},{name:"newUsers"},{name:"engagementRate"},{name:"sessionsPerUser"},{name:"screenPageViewsPerSession"}];let h,A=!0;try{h=await u(n,o,{dateRanges:[{startDate:s,endDate:a,name:"current"},{startDate:m,endDate:p,name:"previous"}],dimensions:[{name:"date"}],metrics:w,metricAggregations:["TOTAL"],orderBys:[{dimension:{dimensionName:"date"}}]})}catch{A=!1,h=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"date"}],metrics:w,metricAggregations:["TOTAL"],orderBys:[{dimension:{dimensionName:"date"}}]})}return b(h,A)})),g.get("/realtime",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=await fetch(`${S}/properties/${o}:runRealtimeReport`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({dimensions:[{name:"unifiedScreenName"}],metrics:[{name:"activeUsers"}],orderBys:[{metric:{metricName:"activeUsers"},desc:!0}],limit:5})});if(!t.ok){const c=await t.json().catch(()=>({}));throw r.createError({statusCode:t.status,statusMessage:c?.error?.message||"Realtime API failed"})}const s=await t.json(),a=(s?.rows||[]).reduce((c,m)=>c+parseInt(m.metricValues?.[0]?.value||"0",10),0),i=(s?.rows||[]).map(c=>({page:c.dimensionValues?.[0]?.value||"(not set)",activeUsers:parseInt(c.metricValues?.[0]?.value||"0",10)}));return{activeUsers:a,activePages:i}})),g.get("/top-pages",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=parseInt(t.limit||"10",10),c=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"pagePath"}],metrics:[{name:"screenPageViews"},{name:"totalUsers"},{name:"averageSessionDuration"}],orderBys:[{metric:{metricName:"screenPageViews"},desc:!0}],limit:i*2}),m=C(c,"pagePath"),p=new Map;for(const h of m.rows){const A=h.pagePath.toLowerCase().replace(/\/+$/,""),v=p.get(A);if(v){v.screenPageViews+=h.screenPageViews||0,v.totalUsers+=h.totalUsers||0;const R=v.screenPageViews;R>0&&(v.averageSessionDuration=(v.averageSessionDuration*(R-(h.screenPageViews||0))+(h.averageSessionDuration||0)*(h.screenPageViews||0))/R)}else p.set(A,{...h})}return{rows:[...p.values()].sort((h,A)=>(A.screenPageViews||0)-(h.screenPageViews||0)).slice(0,i),rowCount:m.rowCount}})),g.get("/top-sources",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"sessionSource"}],metrics:[{name:"sessions"},{name:"totalUsers"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:10});return C(i,"sessionSource")})),g.get("/devices",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"deviceCategory"}],metrics:[{name:"sessions"},{name:"totalUsers"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}]});return C(i,"deviceCategory")})),g.get("/countries",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"country"}],metrics:[{name:"sessions"},{name:"totalUsers"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:10});return C(i,"country")})),g.get("/acquisition/channels",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"sessionDefaultChannelGroup"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"newUsers"},{name:"engagementRate"},{name:"averageSessionDuration"},{name:"screenPageViewsPerSession"},{name:"conversions"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:15});return C(i,"sessionDefaultChannelGroup")})),g.get("/acquisition/source-medium",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"sessionSourceMedium"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"newUsers"},{name:"bounceRate"},{name:"averageSessionDuration"},{name:"conversions"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:20});return C(i,"sessionSourceMedium")})),g.get("/acquisition/referrals",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"sessionSource"}],dimensionFilter:{filter:{fieldName:"sessionMedium",stringFilter:{value:"referral"}}},metrics:[{name:"sessions"},{name:"totalUsers"},{name:"engagementRate"},{name:"averageSessionDuration"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:20});return C(i,"sessionSource")})),g.get("/acquisition/campaigns",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"sessionCampaignName"}],dimensionFilter:{notExpression:{filter:{fieldName:"sessionCampaignName",stringFilter:{value:"(not set)"}}}},metrics:[{name:"sessions"},{name:"totalUsers"},{name:"conversions"},{name:"engagementRate"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:20});return C(i,"sessionCampaignName")})),g.get("/content/all-pages",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=parseInt(t.limit||"50",10),c=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"pagePath"}],metrics:[{name:"screenPageViews"},{name:"totalUsers"},{name:"averageSessionDuration"},{name:"bounceRate"},{name:"engagementRate"},{name:"sessions"},{name:"userEngagementDuration"}],orderBys:[{metric:{metricName:"screenPageViews"},desc:!0}],limit:i});return C(c,"pagePath")})),g.get("/content/landing-pages",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"landingPagePlusQueryString"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"bounceRate"},{name:"averageSessionDuration"},{name:"screenPageViews"},{name:"engagementRate"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:30});return C(i,"landingPagePlusQueryString")})),g.get("/content/exit-pages",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"pagePath"}],metrics:[{name:"sessions"},{name:"screenPageViews"},{name:"totalUsers"},{name:"bounceRate"}],orderBys:[{metric:{metricName:"screenPageViews"},desc:!0}],limit:20}),c=C(i,"pagePath");return c.rows=c.rows.map(m=>({...m,exitRate:m.bounceRate||0})),c})),g.get("/content/search-terms",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o,siteUrl:t}=await l(e),s=r.getQuery(e),a=s.startDate||"30daysAgo",i=s.endDate||"today";if(t)try{const p=`${I}/sites/${encodeURIComponent(t)}/searchAnalytics/query`;console.log("[GA Module] Attempting Search Console query for site:",t);const w=await fetch(p,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({startDate:d(a),endDate:d(i),dimensions:["query"],rowLimit:30})});if(w.ok){const A=((await w.json()).rows||[]).map(v=>({query:v.keys[0],clicks:v.clicks,impressions:v.impressions,ctr:v.ctr,position:v.position}));if(A.length>0)return console.log(`[GA Module] Search Console returned ${A.length} keyword rows`),{rows:A,rowCount:A.length,source:"search_console"};console.log("[GA Module] Search Console returned 0 rows, falling through")}else{const h=await w.text().catch(()=>"");console.error(`[GA Module] Search Console API error (${w.status}):`,h)}}catch(p){console.error("[GA Module] Search Console request failed:",p?.message||p)}else console.log("[GA Module] No siteUrl configured, skipping Search Console");try{const p=await u(n,o,{dateRanges:[{startDate:a,endDate:i}],dimensions:[{name:"sessionGoogleAdsQuery"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"engagementRate"}],dimensionFilter:{andGroup:{expressions:[{notExpression:{filter:{fieldName:"sessionGoogleAdsQuery",stringFilter:{value:"(not set)"}}}},{notExpression:{filter:{fieldName:"sessionGoogleAdsQuery",stringFilter:{value:"(not provided)"}}}}]}},orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:30}),w=C(p,"sessionGoogleAdsQuery");if(w.rows.length>0)return{...w,source:"google_ads"}}catch{}const c=await u(n,o,{dateRanges:[{startDate:a,endDate:i}],dimensions:[{name:"landingPagePlusQueryString"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"engagementRate"}],dimensionFilter:{andGroup:{expressions:[{filter:{fieldName:"sessionMedium",stringFilter:{matchType:"EXACT",value:"organic"}}},{notExpression:{filter:{fieldName:"landingPagePlusQueryString",stringFilter:{value:"(not set)"}}}}]}},orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:30});return{...C(c,"landingPagePlusQueryString"),source:"organic_landing_pages"}})),g.get("/audience/overview",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"newVsReturning"}],metrics:[{name:"totalUsers"},{name:"sessions"},{name:"engagementRate"},{name:"averageSessionDuration"},{name:"screenPageViewsPerSession"}],metricAggregations:["TOTAL"]});return C(i,"newVsReturning")})),g.get("/audience/technology",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=t.dimension||"browser",m=["browser","operatingSystem","screenResolution"].includes(i)?i:"browser",p=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:m}],metrics:[{name:"totalUsers"},{name:"sessions"},{name:"engagementRate"}],orderBys:[{metric:{metricName:"totalUsers"},desc:!0}],limit:10});return C(p,m)})),g.get("/audience/languages",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"language"}],metrics:[{name:"totalUsers"},{name:"sessions"}],orderBys:[{metric:{metricName:"totalUsers"},desc:!0}],limit:15});return C(i,"language")})),g.get("/audience/hours",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"dayOfWeekName"},{name:"hour"}],metrics:[{name:"sessions"}],orderBys:[{dimension:{dimensionName:"dayOfWeekName"}},{dimension:{dimensionName:"hour"}}],limit:168});return k(i,["dayOfWeekName","hour"])})),g.get("/audience/cities",r.defineEventHandler(async e=>{const{accessToken:n,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",a=t.endDate||"today",i=await u(n,o,{dateRanges:[{startDate:s,endDate:a}],dimensions:[{name:"city"},{name:"country"}],metrics:[{name:"totalUsers"},{name:"sessions"}],dimensionFilter:{notExpression:{filter:{fieldName:"city",stringFilter:{value:"(not set)"}}}},orderBys:[{metric:{metricName:"totalUsers"},desc:!0}],limit:20});return k(i,["city","country"])}));function d(e){const n=e.match(/^(\d+)daysAgo$/);if(n){const o=new Date;return o.setDate(o.getDate()-parseInt(n[1],10)),o.toISOString().slice(0,10)}if(e==="today")return new Date().toISOString().slice(0,10);if(e==="yesterday"){const o=new Date;return o.setDate(o.getDate()-1),o.toISOString().slice(0,10)}return e}async function y(e,n,o){const t=`${I}/sites/${encodeURIComponent(n)}/searchAnalytics/query`,s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const a=await s.json().catch(()=>({}));throw r.createError({statusCode:s.status,statusMessage:a?.error?.message||"Search Console API request failed"})}return s.json()}return g.get("/seo/keywords",r.defineEventHandler(async e=>{const{accessToken:n,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured. Add it in module settings."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),a=d(t.endDate||"today"),i=Math.min(parseInt(t.limit)||50,100),c=await y(n,o,{startDate:s,endDate:a,dimensions:["query"],rowLimit:i});return{rows:(c.rows||[]).map(m=>({query:m.keys[0],clicks:m.clicks,impressions:m.impressions,ctr:m.ctr,position:m.position})),rowCount:c.rows?.length||0}})),g.get("/seo/pages",r.defineEventHandler(async e=>{const{accessToken:n,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),a=d(t.endDate||"today"),i=Math.min(parseInt(t.limit)||50,100),c=await y(n,o,{startDate:s,endDate:a,dimensions:["page"],rowLimit:i});return{rows:(c.rows||[]).map(m=>({page:m.keys[0],clicks:m.clicks,impressions:m.impressions,ctr:m.ctr,position:m.position})),rowCount:c.rows?.length||0}})),g.get("/seo/trends",r.defineEventHandler(async e=>{const{accessToken:n,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),a=d(t.endDate||"today"),c=((await y(n,o,{startDate:s,endDate:a,dimensions:["date"],rowLimit:500})).rows||[]).map(p=>({date:p.keys[0],clicks:p.clicks,impressions:p.impressions,ctr:p.ctr,position:p.position})).sort((p,w)=>p.date.localeCompare(w.date)),m=c.reduce((p,w)=>({clicks:p.clicks+w.clicks,impressions:p.impressions+w.impressions}),{clicks:0,impressions:0});return m.ctr=m.impressions>0?m.clicks/m.impressions:0,m.avgPosition=c.length>0?c.reduce((p,w)=>p+w.position,0)/c.length:0,{rows:c,totals:m,rowCount:c.length}})),g.get("/seo/query-pages",r.defineEventHandler(async e=>{const{accessToken:n,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),a=d(t.endDate||"today"),i=await y(n,o,{startDate:s,endDate:a,dimensions:["query","page"],rowLimit:100});return{rows:(i.rows||[]).map(c=>({query:c.keys[0],page:c.keys[1],clicks:c.clicks,impressions:c.impressions,ctr:c.ctr,position:c.position})),rowCount:i.rows?.length||0}})),g.handler}function b(f,E=!0){const D=(f.metricHeaders||[]).map(s=>s.name),l=(f.dimensionHeaders||[]).map(s=>s.name).indexOf("date"),u=[];(f.rows||[]).forEach(s=>{const a=l>=0?s.dimensionValues[l]?.value:s.dimensionValues[0]?.value;if(!a||a.length<8)return;const c={date:`${a.slice(0,4)}-${a.slice(4,6)}-${a.slice(6,8)}`};D.forEach((m,p)=>{c[m]=parseFloat(s.metricValues[p]?.value||"0")}),u.push(c)});const d={},y={};f.totals&&f.totals.length>=2?D.forEach((s,a)=>{d[s]=parseFloat(f.totals[0]?.metricValues?.[a]?.value||"0"),y[s]=parseFloat(f.totals[1]?.metricValues?.[a]?.value||"0")}):f.totals&&f.totals.length===1&&D.forEach((s,a)=>{d[s]=parseFloat(f.totals[0]?.metricValues?.[a]?.value||"0")});const e={};D.forEach(s=>{const a=d[s]||0,i=y[s];i!==void 0&&i!==0?e[s]=(a-i)/i*100:e[s]=null});const n=new Map;for(const s of u)n.has(s.date)||n.set(s.date,s);const o=Array.from(n.values()).sort((s,a)=>s.date.localeCompare(a.date)),t=E&&f.totals&&f.totals.length>=2?o.slice(-Math.ceil(o.length/2)):o;return{rows:t,totals:d,previousTotals:y,changes:e,rowCount:t.length}}function C(f,E){const D=(f.metricHeaders||[]).map(l=>l.name),g=(f.rows||[]).map(l=>{const u={[E]:l.dimensionValues[0].value};return D.forEach((d,y)=>{u[d]=parseFloat(l.metricValues[y].value)}),u});return{rows:g,rowCount:f.rowCount||g.length}}function k(f,E){const D=(f.metricHeaders||[]).map(l=>l.name),g=(f.rows||[]).map(l=>{const u={};return E.forEach((d,y)=>{u[d]=l.dimensionValues[y]?.value||""}),D.forEach((d,y)=>{u[d]=parseFloat(l.metricValues[y].value)}),u});return{rows:g,rowCount:f.rowCount||g.length}}exports.appointments=T;exports.googleAnalytics=U;exports.products=M;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("h3");require("vue");function b(f){const{initFirebase:v,normalizeTimestamps:D}=f,y=r.createRouter();async function l(u){const{supabase:d,instanceId:g}=u.context.module,{data:e,error:a}=await d.from("project_modules").select("config").eq("id",g).single();if(a||!e?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const o=e.config,t=o.project,s=o.productCollection||"products";if(!t)throw r.createError({statusCode:400,statusMessage:"Products module has no Firebase integration configured."});return{firebase:await v(u,t),collection:s}}return y.get("/products",r.defineEventHandler(async u=>{try{const{firebase:d,collection:g}=await l(u);return(await d.firestore().collection(g).get()).docs.map(a=>D({id:a.id,...a.data()}))}catch(d){throw console.error("Products handler — list error:",d),r.createError({statusCode:d.statusCode||500,statusMessage:d.statusMessage||"Failed to list products"})}})),y.get("/products/:productId",r.defineEventHandler(async u=>{const d=r.getRouterParam(u,"productId");if(!d)throw r.createError({statusCode:400,statusMessage:"Product ID is required."});try{const{firebase:g,collection:e}=await l(u),a=await g.firestore().collection(e).doc(d).get();if(!a.exists)throw r.createError({statusCode:404,statusMessage:"Product not found."});return D({id:a.id,...a.data()})}catch(g){throw console.error("Products handler — get error:",g),r.createError({statusCode:g.statusCode||500,statusMessage:g.statusMessage||"Failed to get product"})}})),y.get("/empty-stock",r.defineEventHandler(async u=>{const g=r.getQuery(u).category;try{const{firebase:e,collection:a}=await l(u);let o=e.firestore().collection(a).where("stock","==",0);g&&(o=o.where("collections","array-contains",g));const s=(await o.get()).docs.map(n=>D({id:n.id,...n.data()}));return{count:s.length,products:s.map(n=>({id:n.id,title:n.title,slug:n.slug,stock:n.stock,price:n.price,currency:n.currency,status:n.status}))}}catch(e){throw console.error("Products handler — empty-stock error:",e),r.createError({statusCode:e.statusCode||500,statusMessage:e.statusMessage||"Failed to query empty stock"})}})),y.handler}function M(f){const{initFirebase:v,normalizeTimestamps:D}=f,y=r.createRouter();async function l(d){const{supabase:g,instanceId:e}=d.context.module,{data:a,error:o}=await g.from("project_modules").select("config").eq("id",e).single();if(o||!a?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const t=a.config,s=t.project,n=t.reservationsCollection||"bookings_orders",i=t.agendaCollection||"agendas";if(!s)throw r.createError({statusCode:400,statusMessage:"Appointments module has no Firebase integration configured."});return{firebase:await v(d,s),reservationsCollection:n,agendaCollection:i}}function u(d){return(d.reservations||[]).map(e=>({orderId:d.id,reservationId:e.id,customerInfo:d.customerInfo,date:e.date,startTime:e.timeslot?.startTime,endTime:e.timeslot?.endTime,spots:e.spots,status:d.status,reservationStatus:e.status,resourceId:e.resourceId,reservationPrice:e.totalPrice,reservationBasePrice:e.basePrice,reservationAddOnsPrice:e.addOnsPrice,pricingOption:e.pricingOption,amountDue:d.amountDue,amountPaid:d.amountPaid,createdAt:d.createdAt}))}return y.get("/appointments",r.defineEventHandler(async d=>{const g=r.getQuery(d),e=Math.min(Number(g.quantity)||20,100);try{const{firebase:a,reservationsCollection:o}=await l(d),s=(await a.firestore().collection(o).orderBy("createdAt","desc").limit(e).get()).docs.flatMap(n=>u(D({id:n.id,...n.data()})));return{count:s.length,appointments:s}}catch(a){throw console.error("Appointments handler — list error:",a),r.createError({statusCode:a.statusCode||500,statusMessage:a.statusMessage||"Failed to list appointments"})}})),y.get("/appointments/find",r.defineEventHandler(async d=>{const g=r.getQuery(d),e=(g.name||"").toLowerCase().trim(),a=(g.email||"").toLowerCase().trim(),o=g.date;try{const{firebase:t,reservationsCollection:s}=await l(d);let n=t.firestore().collection(s);a&&(n=n.where("customerInfo.email","==",a));let c=(await n.orderBy("createdAt","desc").limit(200).get()).docs.flatMap(m=>u(D({id:m.id,...m.data()})));return o&&(c=c.filter(m=>m.date===o)),e&&(c=c.filter(m=>{const p=(m.customerInfo?.firstName||"").toLowerCase(),w=(m.customerInfo?.lastName||"").toLowerCase();return p.includes(e)||w.includes(e)||`${p} ${w}`.includes(e)})),{count:c.length,appointments:c}}catch(t){throw console.error("Appointments handler — find error:",t),r.createError({statusCode:t.statusCode||500,statusMessage:t.statusMessage||"Failed to find appointments"})}})),y.get("/appointments/:appointmentId",r.defineEventHandler(async d=>{const g=r.getRouterParam(d,"appointmentId");if(!g)throw r.createError({statusCode:400,statusMessage:"Appointment ID is required."});try{const{firebase:e,reservationsCollection:a}=await l(d),o=await e.firestore().collection(a).doc(g).get();if(!o.exists)throw r.createError({statusCode:404,statusMessage:"Appointment not found."});const t=D({id:o.id,...o.data()});return{...t,reservations:u(t)}}catch(e){throw console.error("Appointments handler — get error:",e),r.createError({statusCode:e.statusCode||500,statusMessage:e.statusMessage||"Failed to get appointment"})}})),y.handler}const P="https://analyticsdata.googleapis.com/v1beta",T=["https://www.googleapis.com/auth/analytics.readonly","https://www.googleapis.com/auth/webmasters.readonly"],S="https://searchconsole.googleapis.com/webmasters/v3";function N(f){const{decrypt:v,getGoogleAccessToken:D}=f,y=r.createRouter();async function l(e){const{supabase:a,instanceId:o}=e.context.module,{data:t,error:s}=await a.from("project_modules").select("config").eq("id",o).single();if(s||!t?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const n=t.config,i=n.propertyId,c=n.serviceAccount,m=n.siteUrl||"";if(!c)throw r.createError({statusCode:400,statusMessage:"No Google Service Account configured for this module."});if(!i)throw r.createError({statusCode:400,statusMessage:"No GA4 Property ID configured for this module."});const{data:p,error:w}=await a.from("integrations").select("config").eq("id",c).single();let h=p?.config;if(w||!h){const{data:I,error:q}=await a.from("agency_integrations").select("config").eq("id",c).single();if(q||!I?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load Google Service Account credentials."});h=I.config}const A=v(h.clientEmail),E=v(h.privateKey),R=v(h.projectId);return{accessToken:await D({clientEmail:A,privateKey:E,projectId:R},T),propertyId:i,siteUrl:m}}async function u(e,a,o){const t=await fetch(`${P}/properties/${a}:runReport`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){const s=await t.json().catch(()=>({}));throw console.error("GA4 runReport failed:",s),r.createError({statusCode:t.status,statusMessage:s?.error?.message||"GA4 API request failed"})}return t.json()}y.get("/report",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=s.match(/^(\d+)daysAgo$/),c=i?parseInt(i[1],10):30,m=`${c*2}daysAgo`,p=`${c+1}daysAgo`,w=[{name:"sessions"},{name:"totalUsers"},{name:"screenPageViews"},{name:"bounceRate"},{name:"averageSessionDuration"},{name:"newUsers"},{name:"engagementRate"},{name:"sessionsPerUser"},{name:"screenPageViewsPerSession"}];let h,A=!0;try{h=await u(a,o,{dateRanges:[{startDate:s,endDate:n,name:"current"},{startDate:m,endDate:p,name:"previous"}],dimensions:[{name:"date"}],metrics:w,metricAggregations:["TOTAL"],orderBys:[{dimension:{dimensionName:"date"}}]})}catch{A=!1,h=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"date"}],metrics:w,metricAggregations:["TOTAL"],orderBys:[{dimension:{dimensionName:"date"}}]})}return H(h,A)})),y.get("/realtime",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=await fetch(`${P}/properties/${o}:runRealtimeReport`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({dimensions:[{name:"unifiedScreenName"}],metrics:[{name:"activeUsers"}],orderBys:[{metric:{metricName:"activeUsers"},desc:!0}],limit:5})});if(!t.ok){const c=await t.json().catch(()=>({}));throw r.createError({statusCode:t.status,statusMessage:c?.error?.message||"Realtime API failed"})}const s=await t.json(),n=(s?.rows||[]).reduce((c,m)=>c+parseInt(m.metricValues?.[0]?.value||"0",10),0),i=(s?.rows||[]).map(c=>({page:c.dimensionValues?.[0]?.value||"(not set)",activeUsers:parseInt(c.metricValues?.[0]?.value||"0",10)}));return{activeUsers:n,activePages:i}})),y.get("/top-pages",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=parseInt(t.limit||"10",10),c=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"pagePath"}],metrics:[{name:"screenPageViews"},{name:"totalUsers"},{name:"averageSessionDuration"}],orderBys:[{metric:{metricName:"screenPageViews"},desc:!0}],limit:i*2}),m=C(c,"pagePath"),p=new Map;for(const h of m.rows){const A=h.pagePath.toLowerCase().replace(/\/+$/,""),E=p.get(A);if(E){E.screenPageViews+=h.screenPageViews||0,E.totalUsers+=h.totalUsers||0;const R=E.screenPageViews;R>0&&(E.averageSessionDuration=(E.averageSessionDuration*(R-(h.screenPageViews||0))+(h.averageSessionDuration||0)*(h.screenPageViews||0))/R)}else p.set(A,{...h})}return{rows:[...p.values()].sort((h,A)=>(A.screenPageViews||0)-(h.screenPageViews||0)).slice(0,i),rowCount:m.rowCount}})),y.get("/top-sources",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"sessionSource"}],metrics:[{name:"sessions"},{name:"totalUsers"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:10});return C(i,"sessionSource")})),y.get("/devices",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"deviceCategory"}],metrics:[{name:"sessions"},{name:"totalUsers"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}]});return C(i,"deviceCategory")})),y.get("/countries",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"country"}],metrics:[{name:"sessions"},{name:"totalUsers"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:10});return C(i,"country")})),y.get("/acquisition/channels",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"sessionDefaultChannelGroup"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"newUsers"},{name:"engagementRate"},{name:"averageSessionDuration"},{name:"screenPageViewsPerSession"},{name:"conversions"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:15});return C(i,"sessionDefaultChannelGroup")})),y.get("/acquisition/source-medium",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"sessionSourceMedium"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"newUsers"},{name:"bounceRate"},{name:"averageSessionDuration"},{name:"conversions"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:20});return C(i,"sessionSourceMedium")})),y.get("/acquisition/referrals",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"sessionSource"}],dimensionFilter:{filter:{fieldName:"sessionMedium",stringFilter:{value:"referral"}}},metrics:[{name:"sessions"},{name:"totalUsers"},{name:"engagementRate"},{name:"averageSessionDuration"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:20});return C(i,"sessionSource")})),y.get("/acquisition/campaigns",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"sessionCampaignName"}],dimensionFilter:{notExpression:{filter:{fieldName:"sessionCampaignName",stringFilter:{value:"(not set)"}}}},metrics:[{name:"sessions"},{name:"totalUsers"},{name:"conversions"},{name:"engagementRate"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:20});return C(i,"sessionCampaignName")})),y.get("/content/all-pages",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=parseInt(t.limit||"50",10),c=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"pagePath"}],metrics:[{name:"screenPageViews"},{name:"totalUsers"},{name:"averageSessionDuration"},{name:"bounceRate"},{name:"engagementRate"},{name:"sessions"},{name:"userEngagementDuration"}],orderBys:[{metric:{metricName:"screenPageViews"},desc:!0}],limit:i});return C(c,"pagePath")})),y.get("/content/landing-pages",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"landingPagePlusQueryString"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"bounceRate"},{name:"averageSessionDuration"},{name:"screenPageViews"},{name:"engagementRate"}],orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:30});return C(i,"landingPagePlusQueryString")})),y.get("/content/exit-pages",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"pagePath"}],metrics:[{name:"sessions"},{name:"screenPageViews"},{name:"totalUsers"},{name:"bounceRate"}],orderBys:[{metric:{metricName:"screenPageViews"},desc:!0}],limit:20}),c=C(i,"pagePath");return c.rows=c.rows.map(m=>({...m,exitRate:m.bounceRate||0})),c})),y.get("/content/search-terms",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o,siteUrl:t}=await l(e),s=r.getQuery(e),n=s.startDate||"30daysAgo",i=s.endDate||"today";if(t)try{const p=`${S}/sites/${encodeURIComponent(t)}/searchAnalytics/query`,w=await fetch(p,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({startDate:d(n),endDate:d(i),dimensions:["query"],rowLimit:30})});if(w.ok){const A=((await w.json()).rows||[]).map(E=>({query:E.keys[0],clicks:E.clicks,impressions:E.impressions,ctr:E.ctr,position:E.position}));if(A.length>0)return{rows:A,rowCount:A.length,source:"search_console"}}else{const h=await w.text().catch(()=>"");console.error(`[GA Module] Search Console API error (${w.status}):`,h)}}catch(p){console.error("[GA Module] Search Console request failed:",p?.message||p)}else console.log("[GA Module] No siteUrl configured, skipping Search Console");try{const p=await u(a,o,{dateRanges:[{startDate:n,endDate:i}],dimensions:[{name:"sessionGoogleAdsQuery"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"engagementRate"}],dimensionFilter:{andGroup:{expressions:[{notExpression:{filter:{fieldName:"sessionGoogleAdsQuery",stringFilter:{value:"(not set)"}}}},{notExpression:{filter:{fieldName:"sessionGoogleAdsQuery",stringFilter:{value:"(not provided)"}}}}]}},orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:30}),w=C(p,"sessionGoogleAdsQuery");if(w.rows.length>0)return{...w,source:"google_ads"}}catch{}const c=await u(a,o,{dateRanges:[{startDate:n,endDate:i}],dimensions:[{name:"landingPagePlusQueryString"}],metrics:[{name:"sessions"},{name:"totalUsers"},{name:"engagementRate"}],dimensionFilter:{andGroup:{expressions:[{filter:{fieldName:"sessionMedium",stringFilter:{matchType:"EXACT",value:"organic"}}},{notExpression:{filter:{fieldName:"landingPagePlusQueryString",stringFilter:{value:"(not set)"}}}}]}},orderBys:[{metric:{metricName:"sessions"},desc:!0}],limit:30});return{...C(c,"landingPagePlusQueryString"),source:"organic_landing_pages"}})),y.get("/audience/overview",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"newVsReturning"}],metrics:[{name:"totalUsers"},{name:"sessions"},{name:"engagementRate"},{name:"averageSessionDuration"},{name:"screenPageViewsPerSession"}],metricAggregations:["TOTAL"]});return C(i,"newVsReturning")})),y.get("/audience/technology",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=t.dimension||"browser",m=["browser","operatingSystem","screenResolution"].includes(i)?i:"browser",p=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:m}],metrics:[{name:"totalUsers"},{name:"sessions"},{name:"engagementRate"}],orderBys:[{metric:{metricName:"totalUsers"},desc:!0}],limit:10});return C(p,m)})),y.get("/audience/languages",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"language"}],metrics:[{name:"totalUsers"},{name:"sessions"}],orderBys:[{metric:{metricName:"totalUsers"},desc:!0}],limit:15});return C(i,"language")})),y.get("/audience/hours",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"dayOfWeekName"},{name:"hour"}],metrics:[{name:"sessions"}],orderBys:[{dimension:{dimensionName:"dayOfWeekName"}},{dimension:{dimensionName:"hour"}}],limit:168});return k(i,["dayOfWeekName","hour"])})),y.get("/audience/cities",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=r.getQuery(e),s=t.startDate||"30daysAgo",n=t.endDate||"today",i=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:"city"},{name:"country"}],metrics:[{name:"totalUsers"},{name:"sessions"}],dimensionFilter:{notExpression:{filter:{fieldName:"city",stringFilter:{value:"(not set)"}}}},orderBys:[{metric:{metricName:"totalUsers"},desc:!0}],limit:20});return k(i,["city","country"])}));function d(e){const a=e.match(/^(\d+)daysAgo$/);if(a){const o=new Date;return o.setDate(o.getDate()-parseInt(a[1],10)),o.toISOString().slice(0,10)}if(e==="today")return new Date().toISOString().slice(0,10);if(e==="yesterday"){const o=new Date;return o.setDate(o.getDate()-1),o.toISOString().slice(0,10)}return e}async function g(e,a,o){const t=`${S}/sites/${encodeURIComponent(a)}/searchAnalytics/query`,s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){const n=await s.json().catch(()=>({}));throw r.createError({statusCode:s.status,statusMessage:n?.error?.message||"Search Console API request failed"})}return s.json()}return y.get("/seo/keywords",r.defineEventHandler(async e=>{const{accessToken:a,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured. Add it in module settings."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),n=d(t.endDate||"today"),i=Math.min(parseInt(t.limit)||50,100),c=await g(a,o,{startDate:s,endDate:n,dimensions:["query"],rowLimit:i});return{rows:(c.rows||[]).map(m=>({query:m.keys[0],clicks:m.clicks,impressions:m.impressions,ctr:m.ctr,position:m.position})),rowCount:c.rows?.length||0}})),y.get("/seo/pages",r.defineEventHandler(async e=>{const{accessToken:a,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),n=d(t.endDate||"today"),i=Math.min(parseInt(t.limit)||50,100),c=await g(a,o,{startDate:s,endDate:n,dimensions:["page"],rowLimit:i});return{rows:(c.rows||[]).map(m=>({page:m.keys[0],clicks:m.clicks,impressions:m.impressions,ctr:m.ctr,position:m.position})),rowCount:c.rows?.length||0}})),y.get("/seo/trends",r.defineEventHandler(async e=>{const{accessToken:a,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),n=d(t.endDate||"today"),c=((await g(a,o,{startDate:s,endDate:n,dimensions:["date"],rowLimit:500})).rows||[]).map(p=>({date:p.keys[0],clicks:p.clicks,impressions:p.impressions,ctr:p.ctr,position:p.position})).sort((p,w)=>p.date.localeCompare(w.date)),m=c.reduce((p,w)=>({clicks:p.clicks+w.clicks,impressions:p.impressions+w.impressions}),{clicks:0,impressions:0});return m.ctr=m.impressions>0?m.clicks/m.impressions:0,m.avgPosition=c.length>0?c.reduce((p,w)=>p+w.position,0)/c.length:0,{rows:c,totals:m,rowCount:c.length}})),y.get("/seo/query-pages",r.defineEventHandler(async e=>{const{accessToken:a,siteUrl:o}=await l(e);if(!o)throw r.createError({statusCode:400,statusMessage:"Search Console Site URL is not configured."});const t=r.getQuery(e),s=d(t.startDate||"30daysAgo"),n=d(t.endDate||"today"),i=await g(a,o,{startDate:s,endDate:n,dimensions:["query","page"],rowLimit:100});return{rows:(i.rows||[]).map(c=>({query:c.keys[0],page:c.keys[1],clicks:c.clicks,impressions:c.impressions,ctr:c.ctr,position:c.position})),rowCount:i.rows?.length||0}})),y.handler}function H(f,v=!0){const D=(f.metricHeaders||[]).map(s=>s.name),l=(f.dimensionHeaders||[]).map(s=>s.name).indexOf("date"),u=[];(f.rows||[]).forEach(s=>{const n=l>=0?s.dimensionValues[l]?.value:s.dimensionValues[0]?.value;if(!n||n.length<8)return;const c={date:`${n.slice(0,4)}-${n.slice(4,6)}-${n.slice(6,8)}`};D.forEach((m,p)=>{c[m]=parseFloat(s.metricValues[p]?.value||"0")}),u.push(c)});const d={},g={};f.totals&&f.totals.length>=2?D.forEach((s,n)=>{d[s]=parseFloat(f.totals[0]?.metricValues?.[n]?.value||"0"),g[s]=parseFloat(f.totals[1]?.metricValues?.[n]?.value||"0")}):f.totals&&f.totals.length===1&&D.forEach((s,n)=>{d[s]=parseFloat(f.totals[0]?.metricValues?.[n]?.value||"0")});const e={};D.forEach(s=>{const n=d[s]||0,i=g[s];i!==void 0&&i!==0?e[s]=(n-i)/i*100:e[s]=null});const a=new Map;for(const s of u)a.has(s.date)||a.set(s.date,s);const o=Array.from(a.values()).sort((s,n)=>s.date.localeCompare(n.date)),t=v&&f.totals&&f.totals.length>=2?o.slice(-Math.ceil(o.length/2)):o;return{rows:t,totals:d,previousTotals:g,changes:e,rowCount:t.length}}function C(f,v){const D=(f.metricHeaders||[]).map(l=>l.name),y=(f.rows||[]).map(l=>{const u={[v]:l.dimensionValues[0].value};return D.forEach((d,g)=>{u[d]=parseFloat(l.metricValues[g].value)}),u});return{rows:y,rowCount:f.rowCount||y.length}}function k(f,v){const D=(f.metricHeaders||[]).map(l=>l.name),y=(f.rows||[]).map(l=>{const u={};return v.forEach((d,g)=>{u[d]=l.dimensionValues[g]?.value||""}),D.forEach((d,g)=>{u[d]=parseFloat(l.metricValues[g].value)}),u});return{rows:y,rowCount:f.rowCount||y.length}}function U(f){const{decrypt:v}=f,D=r.createRouter();async function y(l){const{supabase:u,instanceId:d}=l.context.module,{data:g,error:e}=await u.from("project_modules").select("config").eq("id",d).single();if(e||!g?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const a=g.config,o=a.githubIntegration,t=a.githubRepo,s=a.githubOwner;if(!o||!t||!s)throw r.createError({statusCode:400,statusMessage:"No GitHub integration configured for this module."});const{data:n,error:i}=await u.from("integrations").select("config").eq("id",o).single();let c=n?.config;if(i||!c){const{data:p,error:w}=await u.from("agency_integrations").select("config").eq("id",o).single();if(w||!p?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load Github credentials."});c=p.config}return{token:v(c.token),repo:t,owner:s}}return D.post("/github/deploy",r.defineEventHandler(async l=>{try{const{token:u,repo:d,owner:g}=await y(l);await fetch(`https://api.github.com/repos/${g}/${d}/dispatches`,{method:"POST",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},body:JSON.stringify({event_type:"deploy-site"})})}catch(u){throw console.error("Error triggering GitHub deployment:",u),r.createError({statusCode:500,statusMessage:"Failed to trigger deployment."})}})),D.handler}exports.appointments=M;exports.contentManager=U;exports.googleAnalytics=N;exports.products=b;
|