@oneclick.dev/cms-core-modules 0.0.82 → 0.0.83
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-4e80zFyn.js → ContentEditor-CRFkD4tE.js} +33 -33
- package/dist/{ContentEditor-Dk-iDEjl.mjs → ContentEditor-CxKirDdL.mjs} +2861 -2854
- package/dist/{Create-DtFzwxn_.mjs → Create-CsqVYhPO.mjs} +1 -1
- package/dist/{Create-CRn2sMHp.js → Create-ip0MnS0o.js} +1 -1
- package/dist/{DateFormatter-DfIwyrnF.mjs → DateFormatter-CvOfaUnU.mjs} +137 -134
- package/dist/DateFormatter-ls6HfWpS.js +1 -0
- package/dist/{Detail-BwDnY42G.mjs → Detail-CbLk1v37.mjs} +1 -1
- package/dist/{Detail-Bxi7lG9x.js → Detail-RMXFuSRQ.js} +1 -1
- package/dist/{NewReservationDialog.vue_vue_type_script_setup_true_lang-Ds7z0qeH.mjs → NewReservationDialog.vue_vue_type_script_setup_true_lang-CDc8MIq2.mjs} +1 -1
- package/dist/{NewReservationDialog.vue_vue_type_script_setup_true_lang-C5YczjNb.js → NewReservationDialog.vue_vue_type_script_setup_true_lang-StaNp-3y.js} +1 -1
- package/dist/{Overview-pCO_47Zt.js → Overview-B2bFNGhH.js} +1 -1
- package/dist/{Overview-CuCQgqVp.mjs → Overview-Cczt_dcE.mjs} +1 -1
- package/dist/{SeoHealth-EZzDmPDM.js → SeoHealth-DFZ0LLBH.js} +1 -1
- package/dist/{SeoHealth-CC0rW1AG.mjs → SeoHealth-ZpvB7CS2.mjs} +1 -1
- package/dist/{TableView-DRQvOW85.mjs → TableView-BUPPcHUW.mjs} +28920 -28605
- package/dist/{TableView-Ce8H65pL.js → TableView-CksiPsTL.js} +152 -152
- package/dist/{agenda-XqvbrU72.mjs → agenda-Cl3s_FIE.mjs} +2 -2
- package/dist/{agenda-wNFDKn0G.js → agenda-rlFma_wn.js} +1 -1
- package/dist/{exceptions-wEQEVzIs.js → exceptions-BA3PsW4n.js} +1 -1
- package/dist/{exceptions-CLgeeUSy.mjs → exceptions-DQPSFSj7.mjs} +1 -1
- package/dist/floating-ui.dom-B9WYoHj2.js +1 -0
- package/dist/{floating-ui.dom-BO2Hr6mz.mjs → floating-ui.dom-fpIfhXTZ.mjs} +400 -401
- package/dist/{index-DTzdHh6g.js → index-CBC9dWZ9.js} +1 -1
- package/dist/{index-DYpruS-A-D38FBcI3.mjs → index-DYpruS-A-Cw57iwdY.mjs} +2 -3
- package/dist/{index-DYpruS-A-CA2jEOA3.js → index-DYpruS-A-DwDXo9Tq.js} +5 -5
- package/dist/{index-N0NoDEsI.mjs → index-YOOlBEZB.mjs} +2 -2
- package/dist/index.cjs.js +1 -1
- package/dist/index.mjs +38 -24
- package/dist/orders-DZzdsHOW.mjs +397 -0
- package/dist/orders-tP4WdF5q.js +1 -0
- package/dist/server-handlers.cjs.js +1 -1
- package/dist/server-handlers.mjs +334 -293
- 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/floating-ui.dom-CAr9LGoC.js +0 -1
- package/dist/orders-Bqa3Z3tH.mjs +0 -356
- package/dist/orders-D5GJOZXN.js +0 -1
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { defineComponent as ee, ref as w, computed as C, 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 g, createElementVNode as s, unref as o, createTextVNode as I, createBlock as j, toDisplayString as d, createCommentVNode as S, 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 ge, ChevronRight as fe, 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-B7ks5mbf.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" }, Oe = { class: "flex items-center gap-1" }, Pe = { 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 N = ce();
|
|
46
|
+
de();
|
|
47
|
+
const { params: F } = ue(), { config: O } = me(), A = pe(O.project), f = w([]), P = w([]), k = w(!0), _ = w(""), b = w(null), h = /* @__PURE__ */ new Date(), p = w(/* @__PURE__ */ new Date()), E = C(() => ({
|
|
48
|
+
date: Q(p.value),
|
|
49
|
+
resource: null
|
|
50
|
+
}));
|
|
51
|
+
te("event", E);
|
|
52
|
+
const $ = C(() => {
|
|
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 = C(() => {
|
|
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 = C(() => _.value.trim() ? new De(f.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) : f.value), T = C(() => ({
|
|
95
|
+
spots: f.value.reduce((e, t) => e + (t.spots || 0), 0),
|
|
96
|
+
bookings: f.value.length,
|
|
97
|
+
revenue: f.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 A.get(O.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, f.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 A.find(O.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
|
+
console.log("allOrders", i);
|
|
122
|
+
let v = [];
|
|
123
|
+
i.forEach((l) => {
|
|
124
|
+
(l.reservations || []).forEach((u) => {
|
|
125
|
+
const z = P.value.find((B) => B.id === u.resourceId);
|
|
126
|
+
v.push({
|
|
127
|
+
customerInfo: l.customerInfo,
|
|
128
|
+
amountDue: l.amountDue,
|
|
129
|
+
amountPaid: l.amountPaid,
|
|
130
|
+
status: l.status,
|
|
131
|
+
reservationStatus: u.status,
|
|
132
|
+
subtotal: l.subtotal,
|
|
133
|
+
total: l.total,
|
|
134
|
+
discount: l.discount,
|
|
135
|
+
id: l.id,
|
|
136
|
+
res_id: u.id,
|
|
137
|
+
resourceId: u.resourceId,
|
|
138
|
+
spots: u.spots,
|
|
139
|
+
date: u.date,
|
|
140
|
+
createdAt: l.createdAt,
|
|
141
|
+
startTime: u.timeslot?.startTime,
|
|
142
|
+
endTime: u.timeslot?.endTime,
|
|
143
|
+
reservationPrice: u.totalPrice,
|
|
144
|
+
reservationBasePrice: u.basePrice,
|
|
145
|
+
reservationAddOnsPrice: u.addOnsPrice,
|
|
146
|
+
pricingOptionId: u.pricingOptionId,
|
|
147
|
+
pricingOption: u.pricingOption,
|
|
148
|
+
resourceName: z?.name || "Unknown",
|
|
149
|
+
resourceColor: z?.color
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
}), f.value = v.sort((l, D) => (D.createdAt || "").localeCompare(l.createdAt || ""));
|
|
153
|
+
} catch (e) {
|
|
154
|
+
console.error("Error loading orders:", e), f.value = [];
|
|
155
|
+
} finally {
|
|
156
|
+
k.value = !1;
|
|
157
|
+
}
|
|
158
|
+
}, W = async () => {
|
|
159
|
+
await K(), await y();
|
|
160
|
+
}, Z = async (e, t) => {
|
|
161
|
+
const a = await A.get(O.reservationsCollection, e), i = a?.reservations?.find((v) => v.id === t);
|
|
162
|
+
if (i) {
|
|
163
|
+
const v = P.value.find((D) => D.id === i.resourceId), l = {
|
|
164
|
+
customerInfo: a.customerInfo,
|
|
165
|
+
amountDue: a.amountDue,
|
|
166
|
+
amountPaid: a.amountPaid,
|
|
167
|
+
status: a.status,
|
|
168
|
+
reservationStatus: i.status,
|
|
169
|
+
subtotal: a.subtotal,
|
|
170
|
+
total: a.total,
|
|
171
|
+
discount: a.discount,
|
|
172
|
+
id: a.id,
|
|
173
|
+
res_id: i.id,
|
|
174
|
+
resourceId: i.resourceId,
|
|
175
|
+
spots: i.spots,
|
|
176
|
+
date: i.date,
|
|
177
|
+
createdAt: a.createdAt,
|
|
178
|
+
startTime: i.timeslot?.startTime,
|
|
179
|
+
endTime: i.timeslot?.endTime,
|
|
180
|
+
reservationPrice: i.totalPrice,
|
|
181
|
+
reservationBasePrice: i.basePrice,
|
|
182
|
+
reservationAddOnsPrice: i.addOnsPrice,
|
|
183
|
+
pricingOptionId: i.pricingOptionId,
|
|
184
|
+
pricingOption: i.pricingOption,
|
|
185
|
+
resourceName: v?.name || "Unknown",
|
|
186
|
+
resourceColor: v?.color
|
|
187
|
+
};
|
|
188
|
+
await le(), console.log("Showing order in dialog:", l, b.value, b.value?.openDialog), b.value?.openDialog(l);
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
return W(), se(async () => {
|
|
192
|
+
if (N.query.orderId) {
|
|
193
|
+
const e = N.query.orderId, t = N.query.reservationId, a = new URL(window.location.href);
|
|
194
|
+
a.searchParams.delete("orderId"), a.searchParams.delete("reservationId"), window.history.replaceState(window.history.state, "", a.toString()), await Z(e, t);
|
|
195
|
+
}
|
|
196
|
+
}), oe(p, () => {
|
|
197
|
+
y();
|
|
198
|
+
}), (e, t) => {
|
|
199
|
+
const a = x("Badge"), i = x("CardTitle"), v = x("CardDescription"), l = x("Button"), D = x("CardHeader"), u = x("Input"), z = x("CardContent"), B = x("Card");
|
|
200
|
+
return c(), m(U, null, [
|
|
201
|
+
r(ke, null, {
|
|
202
|
+
default: g(() => [
|
|
203
|
+
s("div", be, [
|
|
204
|
+
s("div", Ce, [
|
|
205
|
+
s("div", null, [
|
|
206
|
+
s("h1", Ie, [
|
|
207
|
+
r(o(L), { class: "size-6" }),
|
|
208
|
+
t[1] || (t[1] = I(" Orders ", -1))
|
|
209
|
+
]),
|
|
210
|
+
t[2] || (t[2] = s("p", { class: "text-muted-foreground text-sm mt-1" }, " View orders by when they were placed ", -1))
|
|
211
|
+
])
|
|
212
|
+
]),
|
|
213
|
+
r(B, null, {
|
|
214
|
+
default: g(() => [
|
|
215
|
+
r(D, null, {
|
|
216
|
+
default: g(() => [
|
|
217
|
+
s("div", Se, [
|
|
218
|
+
s("div", null, [
|
|
219
|
+
r(i, { class: "flex items-center gap-2" }, {
|
|
220
|
+
default: g(() => [
|
|
221
|
+
t[3] || (t[3] = I(" Orders received ", -1)),
|
|
222
|
+
o(T).bookings > 0 ? (c(), j(a, {
|
|
223
|
+
key: 0,
|
|
224
|
+
variant: "secondary"
|
|
225
|
+
}, {
|
|
226
|
+
default: g(() => [
|
|
227
|
+
I(d(o(T).bookings), 1)
|
|
228
|
+
]),
|
|
229
|
+
_: 1
|
|
230
|
+
})) : S("", !0)
|
|
231
|
+
]),
|
|
232
|
+
_: 1
|
|
233
|
+
}),
|
|
234
|
+
r(v, { class: "flex items-center gap-4 mt-1" }, {
|
|
235
|
+
default: g(() => [
|
|
236
|
+
s("span", Oe, [
|
|
237
|
+
r(o(V), { size: 14 }),
|
|
238
|
+
I(" " + d(o(T).spots) + " spots ", 1)
|
|
239
|
+
]),
|
|
240
|
+
s("span", Pe, " €" + d(o(T).revenue.toFixed(2)) + " revenue ", 1)
|
|
241
|
+
]),
|
|
242
|
+
_: 1
|
|
243
|
+
})
|
|
244
|
+
]),
|
|
245
|
+
s("div", Te, [
|
|
246
|
+
s("div", ze, [
|
|
247
|
+
r(l, {
|
|
248
|
+
variant: "ghost",
|
|
249
|
+
size: "icon",
|
|
250
|
+
class: "size-8",
|
|
251
|
+
onClick: H
|
|
252
|
+
}, {
|
|
253
|
+
default: g(() => [
|
|
254
|
+
r(o(ge), { size: 16 })
|
|
255
|
+
]),
|
|
256
|
+
_: 1
|
|
257
|
+
}),
|
|
258
|
+
r(l, {
|
|
259
|
+
variant: "ghost",
|
|
260
|
+
size: "sm",
|
|
261
|
+
class: "h-8 px-3 text-xs",
|
|
262
|
+
onClick: Y
|
|
263
|
+
}, {
|
|
264
|
+
default: g(() => [...t[4] || (t[4] = [
|
|
265
|
+
I(" Today ", -1)
|
|
266
|
+
])]),
|
|
267
|
+
_: 1
|
|
268
|
+
}),
|
|
269
|
+
r(l, {
|
|
270
|
+
variant: "ghost",
|
|
271
|
+
size: "icon",
|
|
272
|
+
class: "size-8",
|
|
273
|
+
onClick: M,
|
|
274
|
+
disabled: !o(q)
|
|
275
|
+
}, {
|
|
276
|
+
default: g(() => [
|
|
277
|
+
r(o(fe), { size: 16 })
|
|
278
|
+
]),
|
|
279
|
+
_: 1
|
|
280
|
+
}, 8, ["disabled"])
|
|
281
|
+
]),
|
|
282
|
+
r(l, {
|
|
283
|
+
variant: "ghost",
|
|
284
|
+
size: "icon",
|
|
285
|
+
onClick: y,
|
|
286
|
+
disabled: o(k)
|
|
287
|
+
}, {
|
|
288
|
+
default: g(() => [
|
|
289
|
+
r(o(ve), {
|
|
290
|
+
size: 16,
|
|
291
|
+
class: ne({ "animate-spin": o(k) })
|
|
292
|
+
}, null, 8, ["class"])
|
|
293
|
+
]),
|
|
294
|
+
_: 1
|
|
295
|
+
}, 8, ["disabled"])
|
|
296
|
+
])
|
|
297
|
+
]),
|
|
298
|
+
s("div", Ne, d(o($)), 1)
|
|
299
|
+
]),
|
|
300
|
+
_: 1
|
|
301
|
+
}),
|
|
302
|
+
r(z, null, {
|
|
303
|
+
default: g(() => [
|
|
304
|
+
s("div", Ae, [
|
|
305
|
+
r(o(_e), {
|
|
306
|
+
size: 16,
|
|
307
|
+
class: "absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
|
|
308
|
+
}),
|
|
309
|
+
r(u, {
|
|
310
|
+
modelValue: o(_),
|
|
311
|
+
"onUpdate:modelValue": t[0] || (t[0] = (n) => ae(_) ? _.value = n : null),
|
|
312
|
+
placeholder: "Search by name, email, or phone...",
|
|
313
|
+
class: "pl-9 pr-9"
|
|
314
|
+
}, null, 8, ["modelValue"]),
|
|
315
|
+
o(_) ? (c(), j(l, {
|
|
316
|
+
key: 0,
|
|
317
|
+
variant: "ghost",
|
|
318
|
+
size: "icon",
|
|
319
|
+
class: "absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7",
|
|
320
|
+
onClick: J
|
|
321
|
+
}, {
|
|
322
|
+
default: g(() => [
|
|
323
|
+
r(o(xe), { size: 14 })
|
|
324
|
+
]),
|
|
325
|
+
_: 1
|
|
326
|
+
})) : S("", !0)
|
|
327
|
+
]),
|
|
328
|
+
o(_) ? (c(), m("div", Re, " Showing " + d(o(R).length) + " of " + d(o(f).length) + " orders ", 1)) : S("", !0),
|
|
329
|
+
o(k) ? (c(), m("div", Be, [...t[5] || (t[5] = [
|
|
330
|
+
s("div", { class: "animate-spin rounded-full h-8 w-8 border-b-2 border-primary" }, null, -1)
|
|
331
|
+
])])) : o(f).length === 0 ? (c(), m("div", Fe, [
|
|
332
|
+
r(o(L), { class: "size-12 mx-auto mb-3 opacity-50" }),
|
|
333
|
+
t[6] || (t[6] = s("p", null, "No orders received on this day", -1))
|
|
334
|
+
])) : o(R).length === 0 ? (c(), m("div", Ue, " No orders match your search ")) : (c(), m("div", je, [
|
|
335
|
+
(c(!0), m(U, null, re(o(R), (n) => (c(), m("div", {
|
|
336
|
+
key: n.res_id || n.id,
|
|
337
|
+
class: "p-3 border rounded-lg hover:bg-muted/50 transition-colors cursor-pointer",
|
|
338
|
+
onClick: (nt) => o(b)?.openDialog(n)
|
|
339
|
+
}, [
|
|
340
|
+
s("div", Ve, [
|
|
341
|
+
s("div", Ee, [
|
|
342
|
+
s("div", $e, d(n.customerInfo?.firstName) + " " + d(n.customerInfo?.lastName || "Unknown Customer"), 1),
|
|
343
|
+
s("div", He, d(n.customerInfo?.email), 1),
|
|
344
|
+
s("div", Me, d(n.customerInfo?.phone), 1),
|
|
345
|
+
s("div", qe, [
|
|
346
|
+
s("div", Ye, [
|
|
347
|
+
r(o(he), { size: 12 }),
|
|
348
|
+
s("span", null, d(G(n.date)) + " · " + d(n.startTime) + " - " + d(n.endTime), 1)
|
|
349
|
+
]),
|
|
350
|
+
s("div", Qe, [
|
|
351
|
+
r(o(V), { size: 12 }),
|
|
352
|
+
s("span", null, d(n.spots) + " spots", 1)
|
|
353
|
+
]),
|
|
354
|
+
n.resourceName ? (c(), m("div", Xe, [
|
|
355
|
+
s("div", {
|
|
356
|
+
class: "w-3 h-3 rounded-full",
|
|
357
|
+
style: ie({ backgroundColor: n.resourceColor || "#6b7280" })
|
|
358
|
+
}, null, 4),
|
|
359
|
+
s("span", null, d(n.resourceName), 1)
|
|
360
|
+
])) : S("", !0)
|
|
361
|
+
]),
|
|
362
|
+
s("div", Ge, [
|
|
363
|
+
r(o(ye), { size: 12 }),
|
|
364
|
+
s("span", null, "Ordered at " + d(X(n.createdAt)), 1)
|
|
365
|
+
])
|
|
366
|
+
]),
|
|
367
|
+
s("div", Je, [
|
|
368
|
+
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")),
|
|
369
|
+
n.reservationPrice || n.reservationPrice === 0 ? (c(), m("div", st, " €" + d(n.reservationPrice.toFixed(2)), 1)) : S("", !0)
|
|
370
|
+
])
|
|
371
|
+
])
|
|
372
|
+
], 8, Le))), 128))
|
|
373
|
+
]))
|
|
374
|
+
]),
|
|
375
|
+
_: 1
|
|
376
|
+
})
|
|
377
|
+
]),
|
|
378
|
+
_: 1
|
|
379
|
+
})
|
|
380
|
+
])
|
|
381
|
+
]),
|
|
382
|
+
_: 1
|
|
383
|
+
}),
|
|
384
|
+
r(we, {
|
|
385
|
+
ref_key: "reservationDetailDialog",
|
|
386
|
+
ref: b,
|
|
387
|
+
onCancelled: y,
|
|
388
|
+
onConfirmed: y,
|
|
389
|
+
onRejected: y
|
|
390
|
+
}, null, 512)
|
|
391
|
+
], 64);
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
});
|
|
395
|
+
export {
|
|
396
|
+
dt as default
|
|
397
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),x=require("@oneclick.dev/cms-kit"),i=require("lucide-vue-next"),b=require("./ReservationDetailDialog.vue_vue_type_script_setup_true_lang-Vxubki_v.js"),q=require("./EditLayout.vue_vue_type_script_setup_true_lang-Czu6Dcde.js"),M={class:"space-y-6"},H={class:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"},$={class:"text-2xl font-semibold tracking-tight flex items-center gap-2"},Y={class:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"},K={class:"flex items-center gap-1"},Q={class:"flex items-center gap-1"},X={class:"flex items-center gap-2"},G={class:"flex items-center gap-1"},J={class:"text-sm text-muted-foreground mt-2"},W={class:"relative mb-4"},Z={key:0,class:"mb-3 text-sm text-muted-foreground"},ee={key:1,class:"flex items-center justify-center py-8"},te={key:2,class:"text-center py-8 text-muted-foreground"},oe={key:3,class:"text-center py-8 text-muted-foreground"},ne={key:4,class:"space-y-2"},se=["onClick"],re={class:"flex items-start justify-between"},ae={class:"flex-1"},le={class:"font-medium"},ce={class:"text-sm text-muted-foreground"},ie={class:"text-sm text-muted-foreground"},de={class:"flex items-center gap-4 flex-wrap mt-1"},ue={class:"flex items-center gap-2 text-xs text-muted-foreground"},me={class:"flex items-center gap-2 text-xs text-muted-foreground"},pe={key:0,class:"flex items-center gap-1 text-xs text-muted-foreground"},fe={class:"flex items-center gap-2 mt-1 text-xs text-muted-foreground"},ge={class:"text-right"},ve={key:0,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"},_e={key:1,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"},xe={key:2,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"},ye={key:3,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"},he={key:4,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"},ke={key:5,class:"text-sm font-medium mt-1"},Ne=e.defineComponent({__name:"orders",setup(De){const D=x.useRoute();x.useRouter();const{params:S}=x.useModuleRoute(),{config:y}=x.useModule(),w=x.useFirebaseIntegration(y.project),d=e.ref([]),h=e.ref([]),v=e.ref(!0),m=e.ref(""),_=e.ref(null),p=new Date,c=e.ref(new Date),E=e.computed(()=>({date:z(c.value),resource:null}));e.provide("event",E);const B=e.computed(()=>{const t=new Date(p);t.setDate(p.getDate()-1);const o=new Date(p);return o.setDate(p.getDate()+1),c.value.toDateString()===p.toDateString()?"Today":c.value.toDateString()===t.toDateString()?"Yesterday":c.value.toDateString()===o.toDateString()?"Tomorrow":c.value.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),I=()=>{const t=new Date(c.value);t.setDate(t.getDate()-1),c.value=t},T=()=>{const t=new Date(c.value);t.setDate(t.getDate()+1),t<=p&&(c.value=t)},O=e.computed(()=>{const t=new Date(c.value);return t.setDate(t.getDate()+1),t<=p}),P=()=>{c.value=new Date},z=t=>{const o=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${o}-${s}-${r}`},A=t=>t?new Date(t).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):"",R=t=>t?new Date(t).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):"",V=e.computed(()=>m.value.trim()?new b.Fuse(d.value,{keys:["customerInfo.firstName","customerInfo.lastName","customerInfo.email","customerInfo.phone","resourceName"],threshold:.3,ignoreLocation:!0}).search(m.value).map(o=>o.item):d.value),k=e.computed(()=>({spots:d.value.reduce((t,o)=>t+(o.spots||0),0),bookings:d.value.length,revenue:d.value.reduce((t,o)=>t+(o.reservationPrice||0),0)})),U=()=>{m.value=""},j=async()=>{try{const t=S.value.id,o=await w.get(y.agendaCollection,t);h.value=o?.resources?.filter(s=>s.isActive)||[]}catch(t){console.error("Error loading resources:",t),h.value=[]}},f=async()=>{v.value=!0,d.value=[];try{const t=S.value.id,o=new Date(c.value);o.setHours(0,0,0,0);const s=new Date(c.value);s.setHours(23,59,59,999);const r=await w.find(y.reservationsCollection,{filters:[{field:"agendaId",operator:"==",value:t},{field:"createdAt",operator:">=",value:o.toISOString()},{field:"createdAt",operator:"<=",value:s.toISOString()}]});console.log("allOrders",r);let u=[];r.forEach(a=>{(a.reservations||[]).forEach(l=>{const N=h.value.find(C=>C.id===l.resourceId);u.push({customerInfo:a.customerInfo,amountDue:a.amountDue,amountPaid:a.amountPaid,status:a.status,reservationStatus:l.status,subtotal:a.subtotal,total:a.total,discount:a.discount,id:a.id,res_id:l.id,resourceId:l.resourceId,spots:l.spots,date:l.date,createdAt:a.createdAt,startTime:l.timeslot?.startTime,endTime:l.timeslot?.endTime,reservationPrice:l.totalPrice,reservationBasePrice:l.basePrice,reservationAddOnsPrice:l.addOnsPrice,pricingOptionId:l.pricingOptionId,pricingOption:l.pricingOption,resourceName:N?.name||"Unknown",resourceColor:N?.color})})}),d.value=u.sort((a,g)=>(g.createdAt||"").localeCompare(a.createdAt||""))}catch(t){console.error("Error loading orders:",t),d.value=[]}finally{v.value=!1}},F=async()=>{await j(),await f()},L=async(t,o)=>{const s=await w.get(y.reservationsCollection,t),r=s?.reservations?.find(u=>u.id===o);if(r){const u=h.value.find(g=>g.id===r.resourceId),a={customerInfo:s.customerInfo,amountDue:s.amountDue,amountPaid:s.amountPaid,status:s.status,reservationStatus:r.status,subtotal:s.subtotal,total:s.total,discount:s.discount,id:s.id,res_id:r.id,resourceId:r.resourceId,spots:r.spots,date:r.date,createdAt:s.createdAt,startTime:r.timeslot?.startTime,endTime:r.timeslot?.endTime,reservationPrice:r.totalPrice,reservationBasePrice:r.basePrice,reservationAddOnsPrice:r.addOnsPrice,pricingOptionId:r.pricingOptionId,pricingOption:r.pricingOption,resourceName:u?.name||"Unknown",resourceColor:u?.color};await e.nextTick(),console.log("Showing order in dialog:",a,_.value,_.value?.openDialog),_.value?.openDialog(a)}};return F(),e.onMounted(async()=>{if(D.query.orderId){const t=D.query.orderId,o=D.query.reservationId,s=new URL(window.location.href);s.searchParams.delete("orderId"),s.searchParams.delete("reservationId"),window.history.replaceState(window.history.state,"",s.toString()),await L(t,o)}}),e.watch(c,()=>{f()}),(t,o)=>{const s=e.resolveComponent("Badge"),r=e.resolveComponent("CardTitle"),u=e.resolveComponent("CardDescription"),a=e.resolveComponent("Button"),g=e.resolveComponent("CardHeader"),l=e.resolveComponent("Input"),N=e.resolveComponent("CardContent"),C=e.resolveComponent("Card");return e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createVNode(q._sfc_main,null,{default:e.withCtx(()=>[e.createElementVNode("div",M,[e.createElementVNode("div",H,[e.createElementVNode("div",null,[e.createElementVNode("h1",$,[e.createVNode(e.unref(i.ShoppingBag),{class:"size-6"}),o[1]||(o[1]=e.createTextVNode(" Orders ",-1))]),o[2]||(o[2]=e.createElementVNode("p",{class:"text-muted-foreground text-sm mt-1"}," View orders by when they were placed ",-1))])]),e.createVNode(C,null,{default:e.withCtx(()=>[e.createVNode(g,null,{default:e.withCtx(()=>[e.createElementVNode("div",Y,[e.createElementVNode("div",null,[e.createVNode(r,{class:"flex items-center gap-2"},{default:e.withCtx(()=>[o[3]||(o[3]=e.createTextVNode(" Orders received ",-1)),e.unref(k).bookings>0?(e.openBlock(),e.createBlock(s,{key:0,variant:"secondary"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(e.unref(k).bookings),1)]),_:1})):e.createCommentVNode("",!0)]),_:1}),e.createVNode(u,{class:"flex items-center gap-4 mt-1"},{default:e.withCtx(()=>[e.createElementVNode("span",K,[e.createVNode(e.unref(i.Users),{size:14}),e.createTextVNode(" "+e.toDisplayString(e.unref(k).spots)+" spots ",1)]),e.createElementVNode("span",Q," €"+e.toDisplayString(e.unref(k).revenue.toFixed(2))+" revenue ",1)]),_:1})]),e.createElementVNode("div",X,[e.createElementVNode("div",G,[e.createVNode(a,{variant:"ghost",size:"icon",class:"size-8",onClick:I},{default:e.withCtx(()=>[e.createVNode(e.unref(i.ChevronLeft),{size:16})]),_:1}),e.createVNode(a,{variant:"ghost",size:"sm",class:"h-8 px-3 text-xs",onClick:P},{default:e.withCtx(()=>[...o[4]||(o[4]=[e.createTextVNode(" Today ",-1)])]),_:1}),e.createVNode(a,{variant:"ghost",size:"icon",class:"size-8",onClick:T,disabled:!e.unref(O)},{default:e.withCtx(()=>[e.createVNode(e.unref(i.ChevronRight),{size:16})]),_:1},8,["disabled"])]),e.createVNode(a,{variant:"ghost",size:"icon",onClick:f,disabled:e.unref(v)},{default:e.withCtx(()=>[e.createVNode(e.unref(i.RefreshCw),{size:16,class:e.normalizeClass({"animate-spin":e.unref(v)})},null,8,["class"])]),_:1},8,["disabled"])])]),e.createElementVNode("div",J,e.toDisplayString(e.unref(B)),1)]),_:1}),e.createVNode(N,null,{default:e.withCtx(()=>[e.createElementVNode("div",W,[e.createVNode(e.unref(i.Search),{size:16,class:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.createVNode(l,{modelValue:e.unref(m),"onUpdate:modelValue":o[0]||(o[0]=n=>e.isRef(m)?m.value=n:null),placeholder:"Search by name, email, or phone...",class:"pl-9 pr-9"},null,8,["modelValue"]),e.unref(m)?(e.openBlock(),e.createBlock(a,{key:0,variant:"ghost",size:"icon",class:"absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7",onClick:U},{default:e.withCtx(()=>[e.createVNode(e.unref(i.X),{size:14})]),_:1})):e.createCommentVNode("",!0)]),e.unref(m)?(e.openBlock(),e.createElementBlock("div",Z," Showing "+e.toDisplayString(e.unref(V).length)+" of "+e.toDisplayString(e.unref(d).length)+" orders ",1)):e.createCommentVNode("",!0),e.unref(v)?(e.openBlock(),e.createElementBlock("div",ee,[...o[5]||(o[5]=[e.createElementVNode("div",{class:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"},null,-1)])])):e.unref(d).length===0?(e.openBlock(),e.createElementBlock("div",te,[e.createVNode(e.unref(i.ShoppingBag),{class:"size-12 mx-auto mb-3 opacity-50"}),o[6]||(o[6]=e.createElementVNode("p",null,"No orders received on this day",-1))])):e.unref(V).length===0?(e.openBlock(),e.createElementBlock("div",oe," No orders match your search ")):(e.openBlock(),e.createElementBlock("div",ne,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(V),n=>(e.openBlock(),e.createElementBlock("div",{key:n.res_id||n.id,class:"p-3 border rounded-lg hover:bg-muted/50 transition-colors cursor-pointer",onClick:we=>e.unref(_)?.openDialog(n)},[e.createElementVNode("div",re,[e.createElementVNode("div",ae,[e.createElementVNode("div",le,e.toDisplayString(n.customerInfo?.firstName)+" "+e.toDisplayString(n.customerInfo?.lastName||"Unknown Customer"),1),e.createElementVNode("div",ce,e.toDisplayString(n.customerInfo?.email),1),e.createElementVNode("div",ie,e.toDisplayString(n.customerInfo?.phone),1),e.createElementVNode("div",de,[e.createElementVNode("div",ue,[e.createVNode(e.unref(i.Calendar),{size:12}),e.createElementVNode("span",null,e.toDisplayString(R(n.date))+" · "+e.toDisplayString(n.startTime)+" - "+e.toDisplayString(n.endTime),1)]),e.createElementVNode("div",me,[e.createVNode(e.unref(i.Users),{size:12}),e.createElementVNode("span",null,e.toDisplayString(n.spots)+" spots",1)]),n.resourceName?(e.openBlock(),e.createElementBlock("div",pe,[e.createElementVNode("div",{class:"w-3 h-3 rounded-full",style:e.normalizeStyle({backgroundColor:n.resourceColor||"#6b7280"})},null,4),e.createElementVNode("span",null,e.toDisplayString(n.resourceName),1)])):e.createCommentVNode("",!0)]),e.createElementVNode("div",fe,[e.createVNode(e.unref(i.Clock),{size:12}),e.createElementVNode("span",null,"Ordered at "+e.toDisplayString(A(n.createdAt)),1)])]),e.createElementVNode("div",ge,[n.reservationStatus==="needs_approval"?(e.openBlock(),e.createElementBlock("span",ve,"Needs Approval")):n.reservationStatus==="approved"?(e.openBlock(),e.createElementBlock("span",_e,"Approved")):n.reservationStatus==="rejected"?(e.openBlock(),e.createElementBlock("span",xe,"Rejected")):n.reservationStatus==="cancelled"?(e.openBlock(),e.createElementBlock("span",ye,"Cancelled")):(e.openBlock(),e.createElementBlock("span",he,"Pending")),n.reservationPrice||n.reservationPrice===0?(e.openBlock(),e.createElementBlock("div",ke," €"+e.toDisplayString(n.reservationPrice.toFixed(2)),1)):e.createCommentVNode("",!0)])])],8,se))),128))]))]),_:1})]),_:1})])]),_:1}),e.createVNode(b._sfc_main,{ref_key:"reservationDetailDialog",ref:_,onCancelled:f,onConfirmed:f,onRejected:f},null,512)],64)}}});exports.default=Ne;
|
|
@@ -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 q(f){const{initFirebase:v,normalizeTimestamps:D}=f,p=r.createRouter();async function l(u){const{supabase:d,instanceId:m}=u.context.module,{data:e,error:a}=await d.from("project_modules").select("config").eq("id",m).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 p.get("/products",r.defineEventHandler(async u=>{try{const{firebase:d,collection:m}=await l(u);return(await d.firestore().collection(m).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"})}})),p.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:m,collection:e}=await l(u),a=await m.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(m){throw console.error("Products handler — get error:",m),r.createError({statusCode:m.statusCode||500,statusMessage:m.statusMessage||"Failed to get product"})}})),p.get("/empty-stock",r.defineEventHandler(async u=>{const m=r.getQuery(u).category;try{const{firebase:e,collection:a}=await l(u);let o=e.firestore().collection(a).where("stock","==",0);m&&(o=o.where("collections","array-contains",m));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"})}})),p.handler}function b(f){const{initFirebase:v,normalizeTimestamps:D}=f,p=r.createRouter();async function l(d){const{supabase:m,instanceId:e}=d.context.module,{data:a,error:o}=await m.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 p.get("/appointments",r.defineEventHandler(async d=>{const m=r.getQuery(d),e=Math.min(Number(m.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"})}})),p.get("/appointments/find",r.defineEventHandler(async d=>{const m=r.getQuery(d),e=(m.name||"").toLowerCase().trim(),a=(m.email||"").toLowerCase().trim(),o=m.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(g=>u(D({id:g.id,...g.data()})));return o&&(c=c.filter(g=>g.date===o)),e&&(c=c.filter(g=>{const y=(g.customerInfo?.firstName||"").toLowerCase(),w=(g.customerInfo?.lastName||"").toLowerCase();return y.includes(e)||w.includes(e)||`${y} ${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"})}})),p.get("/appointments/:appointmentId",r.defineEventHandler(async d=>{const m=r.getRouterParam(d,"appointmentId");if(!m)throw r.createError({statusCode:400,statusMessage:"Appointment ID is required."});try{const{firebase:e,reservationsCollection:a}=await l(d);console.log("Fetching appointment with ID:",m,a);const o=await e.firestore().collection(a).doc(m).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"})}})),p.handler}const S="https://analyticsdata.googleapis.com/v1beta",T=["https://www.googleapis.com/auth/analytics.readonly","https://www.googleapis.com/auth/webmasters.readonly"],P="https://searchconsole.googleapis.com/webmasters/v3";function N(f){const{decrypt:v,getGoogleAccessToken:D}=f,p=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,g=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:y,error:w}=await a.from("integrations").select("config").eq("id",c).single();let h=y?.config;if(w||!h){const{data:I,error:M}=await a.from("agency_integrations").select("config").eq("id",c).single();if(M||!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:g}}async function u(e,a,o){const t=await fetch(`${S}/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()}p.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,g=`${c*2}daysAgo`,y=`${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:g,endDate:y,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)})),p.get("/realtime",r.defineEventHandler(async e=>{const{accessToken:a,propertyId:o}=await l(e),t=await fetch(`${S}/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,g)=>c+parseInt(g.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}})),p.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}),g=C(c,"pagePath"),y=new Map;for(const h of g.rows){const A=h.pagePath.toLowerCase().replace(/\/+$/,""),E=y.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 y.set(A,{...h})}return{rows:[...y.values()].sort((h,A)=>(A.screenPageViews||0)-(h.screenPageViews||0)).slice(0,i),rowCount:g.rowCount}})),p.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")})),p.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")})),p.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")})),p.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")})),p.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")})),p.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")})),p.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")})),p.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")})),p.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")})),p.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(g=>({...g,exitRate:g.bounceRate||0})),c})),p.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 y=`${P}/sites/${encodeURIComponent(t)}/searchAnalytics/query`;console.log("[GA Module] Attempting Search Console query for site:",t);const w=await fetch(y,{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 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(y){console.error("[GA Module] Search Console request failed:",y?.message||y)}else console.log("[GA Module] No siteUrl configured, skipping Search Console");try{const y=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(y,"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"}})),p.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")})),p.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",g=["browser","operatingSystem","screenResolution"].includes(i)?i:"browser",y=await u(a,o,{dateRanges:[{startDate:s,endDate:n}],dimensions:[{name:g}],metrics:[{name:"totalUsers"},{name:"sessions"},{name:"engagementRate"}],orderBys:[{metric:{metricName:"totalUsers"},desc:!0}],limit:10});return C(y,g)})),p.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")})),p.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"])})),p.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 m(e,a,o){const t=`${P}/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 p.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 m(a,o,{startDate:s,endDate:n,dimensions:["query"],rowLimit:i});return{rows:(c.rows||[]).map(g=>({query:g.keys[0],clicks:g.clicks,impressions:g.impressions,ctr:g.ctr,position:g.position})),rowCount:c.rows?.length||0}})),p.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 m(a,o,{startDate:s,endDate:n,dimensions:["page"],rowLimit:i});return{rows:(c.rows||[]).map(g=>({page:g.keys[0],clicks:g.clicks,impressions:g.impressions,ctr:g.ctr,position:g.position})),rowCount:c.rows?.length||0}})),p.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 m(a,o,{startDate:s,endDate:n,dimensions:["date"],rowLimit:500})).rows||[]).map(y=>({date:y.keys[0],clicks:y.clicks,impressions:y.impressions,ctr:y.ctr,position:y.position})).sort((y,w)=>y.date.localeCompare(w.date)),g=c.reduce((y,w)=>({clicks:y.clicks+w.clicks,impressions:y.impressions+w.impressions}),{clicks:0,impressions:0});return g.ctr=g.impressions>0?g.clicks/g.impressions:0,g.avgPosition=c.length>0?c.reduce((y,w)=>y+w.position,0)/c.length:0,{rows:c,totals:g,rowCount:c.length}})),p.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 m(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}})),p.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((g,y)=>{c[g]=parseFloat(s.metricValues[y]?.value||"0")}),u.push(c)});const d={},m={};f.totals&&f.totals.length>=2?D.forEach((s,n)=>{d[s]=parseFloat(f.totals[0]?.metricValues?.[n]?.value||"0"),m[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=m[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:m,changes:e,rowCount:t.length}}function C(f,v){const D=(f.metricHeaders||[]).map(l=>l.name),p=(f.rows||[]).map(l=>{const u={[v]:l.dimensionValues[0].value};return D.forEach((d,m)=>{u[d]=parseFloat(l.metricValues[m].value)}),u});return{rows:p,rowCount:f.rowCount||p.length}}function k(f,v){const D=(f.metricHeaders||[]).map(l=>l.name),p=(f.rows||[]).map(l=>{const u={};return v.forEach((d,m)=>{u[d]=l.dimensionValues[m]?.value||""}),D.forEach((d,m)=>{u[d]=parseFloat(l.metricValues[m].value)}),u});return{rows:p,rowCount:f.rowCount||p.length}}function U(f){const{decrypt:v}=f,D=r.createRouter();async function p(l){const{supabase:u,instanceId:d}=l.context.module,{data:m,error:e}=await u.from("project_modules").select("config").eq("id",d).single();if(e||!m?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load module config."});const a=m.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:y,error:w}=await u.from("agency_integrations").select("config").eq("id",o).single();if(w||!y?.config)throw r.createError({statusCode:500,statusMessage:"Failed to load Github credentials."});c=y.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:m}=await p(l);await fetch(`https://api.github.com/repos/${m}/${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=b;exports.contentManager=U;exports.googleAnalytics=N;exports.products=q;
|