qarpeo 0.2.1 → 0.3.1
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/chunks/tools.mjs +993 -31
- package/dist/cli/index.mjs +1071 -31
- package/dist/fate/index.d.ts +9 -1
- package/dist/fate/index.mjs +20 -3
- package/dist/module.mjs +296 -750
- package/dist/runtime/browser.mjs +2 -2
- package/dist/runtime/comments-server.d.ts +3 -0
- package/dist/runtime/comments-server.mjs +2 -0
- package/dist/runtime/comments.d.ts +0 -2
- package/dist/runtime/comments.mjs +0 -2
- package/dist/runtime/db.d.ts +10 -9
- package/dist/runtime/db.mjs +79 -8
- package/dist/runtime/drizzle.mjs +21 -6
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/realtime-server.d.ts +4 -0
- package/dist/runtime/realtime-server.mjs +13 -0
- package/dist/runtime/realtime.d.ts +1 -4
- package/dist/runtime/realtime.mjs +0 -13
- package/dist/runtime/replica.d.ts +27 -0
- package/dist/runtime/replica.mjs +229 -0
- package/dist/runtime/server/durable-objects/agent.mjs +14 -2
- package/dist/runtime/server/durable-objects/room.d.ts +10 -0
- package/dist/runtime/server/durable-objects/room.mjs +119 -28
- package/dist/runtime/server/middleware/devtools.mjs +1 -1
- package/dist/runtime/server/middleware/tenancy.mjs +7 -4
- package/dist/runtime/server/plugins/store.mjs +1 -1
- package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
- package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
- package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
- package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
- package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
- package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
- package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
- package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
- package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
- package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
- package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
- package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
- package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
- package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
- package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
- package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
- package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
- package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
- package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
- package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
- package/dist/runtime/server/routes/fate.d.ts +6 -0
- package/dist/runtime/server/routes/fate.mjs +32 -3
- package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
- package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
- package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
- package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
- package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
- package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
- package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
- package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
- package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
- package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
- package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
- package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
- package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
- package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
- package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
- package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
- package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
- package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
- package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
- package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
- package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
- package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
- package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
- package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
- package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
- package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
- package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
- package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
- package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
- package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
- package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
- package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
- package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
- package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
- package/dist/runtime/server/utils/ai.d.ts +6 -0
- package/dist/runtime/server/utils/ai.mjs +12 -2
- package/dist/runtime/server/utils/analytics-query.mjs +8 -4
- package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
- package/dist/runtime/server/utils/browser-utils.mjs +135 -0
- package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
- package/dist/runtime/server/utils/cms/cache.mjs +95 -0
- package/dist/runtime/server/utils/cms/common.mjs +1 -1
- package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
- package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
- package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
- package/dist/runtime/server/utils/cms/path.d.ts +8 -0
- package/dist/runtime/server/utils/cms/path.mjs +23 -0
- package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
- package/dist/runtime/server/utils/cms/queries.mjs +366 -0
- package/dist/runtime/server/utils/cms/references.d.ts +48 -0
- package/dist/runtime/server/utils/cms/references.mjs +309 -0
- package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
- package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
- package/dist/runtime/server/utils/cms/sync.mjs +3 -3
- package/dist/runtime/server/utils/cms.d.ts +5 -82
- package/dist/runtime/server/utils/cms.mjs +28 -1367
- package/dist/runtime/server/utils/comments.d.ts +11 -0
- package/dist/runtime/server/utils/comments.mjs +65 -17
- package/dist/runtime/server/utils/crypto.mjs +1 -1
- package/dist/runtime/server/utils/domains.mjs +9 -0
- package/dist/runtime/server/utils/drizzle.d.ts +26 -1
- package/dist/runtime/server/utils/drizzle.mjs +78 -19
- package/dist/runtime/server/utils/email-inbound.mjs +9 -1
- package/dist/runtime/server/utils/impersonation.mjs +58 -1
- package/dist/runtime/server/utils/lock.d.ts +11 -0
- package/dist/runtime/server/utils/lock.mjs +4 -0
- package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
- package/dist/runtime/server/utils/mail.d.ts +2 -1
- package/dist/runtime/server/utils/mail.mjs +17 -11
- package/dist/runtime/server/utils/notifications.d.ts +13 -4
- package/dist/runtime/server/utils/notifications.mjs +20 -4
- package/dist/runtime/server/utils/organization.mjs +36 -1
- package/dist/runtime/server/utils/passwordless.mjs +8 -0
- package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
- package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
- package/dist/runtime/server/utils/payments/common.d.ts +45 -0
- package/dist/runtime/server/utils/payments/common.mjs +234 -0
- package/dist/runtime/server/utils/payments/index.d.ts +9 -0
- package/dist/runtime/server/utils/payments/index.mjs +21 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
- package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
- package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
- package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
- package/dist/runtime/server/utils/payments/polar.mjs +66 -0
- package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
- package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
- package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
- package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
- package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
- package/dist/runtime/server/utils/payments/usage.mjs +143 -0
- package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
- package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
- package/dist/runtime/server/utils/payments.d.ts +1 -158
- package/dist/runtime/server/utils/payments.mjs +1 -1289
- package/dist/runtime/server/utils/queue.d.ts +2 -0
- package/dist/runtime/server/utils/queue.mjs +34 -21
- package/dist/runtime/server/utils/rag.mjs +30 -17
- package/dist/runtime/server/utils/realtime.d.ts +5 -1
- package/dist/runtime/server/utils/realtime.mjs +43 -7
- package/dist/runtime/server/utils/session.mjs +16 -3
- package/dist/runtime/server/utils/sso.d.ts +3 -0
- package/dist/runtime/server/utils/sso.mjs +43 -0
- package/dist/runtime/server/utils/storage.mjs +12 -1
- package/dist/runtime/server/utils/store/cart.d.ts +63 -0
- package/dist/runtime/server/utils/store/cart.mjs +542 -0
- package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
- package/dist/runtime/server/utils/store/checkout.mjs +118 -0
- package/dist/runtime/server/utils/store/common.d.ts +29 -0
- package/dist/runtime/server/utils/store/common.mjs +479 -0
- package/dist/runtime/server/utils/store/index.d.ts +7 -0
- package/dist/runtime/server/utils/store/index.mjs +30 -0
- package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
- package/dist/runtime/server/utils/store/inventory.mjs +190 -0
- package/dist/runtime/server/utils/store/orders.d.ts +60 -0
- package/dist/runtime/server/utils/store/orders.mjs +590 -0
- package/dist/runtime/server/utils/store/products.d.ts +35 -0
- package/dist/runtime/server/utils/store/products.mjs +461 -0
- package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
- package/dist/runtime/server/utils/store/vendor.mjs +68 -0
- package/dist/runtime/server/utils/store.d.ts +1 -207
- package/dist/runtime/server/utils/store.mjs +1 -2227
- package/dist/runtime/server/utils/string.d.ts +1 -1
- package/dist/runtime/server/utils/string.mjs +12 -4
- package/dist/runtime/server/utils/tenant.mjs +19 -5
- package/dist/runtime/server/utils/tracker.mjs +2 -0
- package/dist/runtime/server.d.ts +3 -3
- package/dist/runtime/server.mjs +4 -4
- package/dist/runtime/storage-server.d.ts +2 -0
- package/dist/runtime/storage-server.mjs +1 -0
- package/dist/runtime/storage.d.ts +1 -1
- package/dist/runtime/storage.mjs +0 -1
- package/dist/runtime/store.d.ts +0 -1
- package/dist/runtime/store.mjs +0 -1
- package/dist/runtime/test-utils.d.ts +4 -0
- package/dist/runtime/test-utils.mjs +54 -0
- package/dist/runtime/types/d1.d.ts +43 -0
- package/dist/runtime/types/drizzle.d.ts +6 -0
- package/dist/runtime/types/store.d.ts +1 -1
- package/dist/types/analytics.d.ts +80 -0
- package/dist/types/auth.d.ts +282 -0
- package/dist/types/cache.d.ts +55 -0
- package/dist/types/comments.d.ts +130 -0
- package/dist/types/db.d.ts +29 -0
- package/dist/types/email.d.ts +182 -0
- package/dist/types/index.d.ts +22 -0
- package/dist/types/jobs.d.ts +58 -0
- package/dist/types/notifications.d.ts +77 -0
- package/dist/types/options.d.ts +363 -0
- package/dist/types/payments.d.ts +145 -0
- package/dist/types/ratelimit.d.ts +71 -0
- package/dist/types/realtime.d.ts +136 -0
- package/dist/types/site.d.ts +121 -0
- package/dist/types/storage.d.ts +164 -0
- package/dist/types/store-options.d.ts +199 -0
- package/dist/types/tenant.d.ts +100 -0
- package/dist/types.d.ts +1 -2174
- package/dist/utils/migration-lock.d.ts +139 -0
- package/dist/utils/pkg.d.ts +14 -1
- package/dist/utils/schema-diff.d.ts +39 -0
- package/package.json +55 -17
- package/dist/chunks/auth-schema.mjs +0 -364
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createError,
|
|
3
|
+
getCookie,
|
|
4
|
+
setCookie,
|
|
5
|
+
getRequestHeader
|
|
6
|
+
} from "nuxt/server";
|
|
7
|
+
import { getAuthContext } from "../context.mjs";
|
|
8
|
+
import { nanoid } from "../crypto.mjs";
|
|
9
|
+
import { detectStoreCountry, calculateStoreTax } from "../store-localization.mjs";
|
|
10
|
+
import { getTenant } from "../tenant.mjs";
|
|
11
|
+
import {
|
|
12
|
+
getD1,
|
|
13
|
+
safeJsonParse,
|
|
14
|
+
getStoreConfig,
|
|
15
|
+
storeProductTbl,
|
|
16
|
+
storeVariantTbl,
|
|
17
|
+
storeCartTbl,
|
|
18
|
+
storeCartItemTbl,
|
|
19
|
+
storeDiscountTbl,
|
|
20
|
+
rowToProduct,
|
|
21
|
+
rowToVariant,
|
|
22
|
+
rowToCartItem,
|
|
23
|
+
rowToCart,
|
|
24
|
+
rowToDiscount
|
|
25
|
+
} from "./common.mjs";
|
|
26
|
+
import { getStoreInventory } from "./inventory.mjs";
|
|
27
|
+
export async function getOrCreateStoreCart(sessionToken, event) {
|
|
28
|
+
const db = getD1(event);
|
|
29
|
+
const cart = storeCartTbl(event);
|
|
30
|
+
const cartItem = storeCartItemTbl(event);
|
|
31
|
+
const v = storeVariantTbl(event);
|
|
32
|
+
const p = storeProductTbl(event);
|
|
33
|
+
const auth = event ? await getAuthContext(event).catch(() => null) : null;
|
|
34
|
+
const userId = auth?.user?.id ?? null;
|
|
35
|
+
const activeTenant = event ? getTenant(event) : null;
|
|
36
|
+
const tenantId = activeTenant?.id ?? null;
|
|
37
|
+
const token = sessionToken || nanoid(32);
|
|
38
|
+
const now = Date.now();
|
|
39
|
+
const ttlMs = (getStoreConfig(event).cart?.maxAgeDays ?? 30) * 86400 * 1e3;
|
|
40
|
+
const expiresAt = now + ttlMs;
|
|
41
|
+
let cartRow = await db.prepare(`SELECT * FROM ${cart} WHERE session_token = ?`).bind(token).first();
|
|
42
|
+
if (!cartRow && userId) {
|
|
43
|
+
if (tenantId) {
|
|
44
|
+
cartRow = await db.prepare(`SELECT * FROM ${cart} WHERE user_id = ? AND tenant_id = ? AND expires_at > ? ORDER BY updated_at DESC LIMIT 1`).bind(userId, tenantId, now).first();
|
|
45
|
+
} else {
|
|
46
|
+
cartRow = await db.prepare(`SELECT * FROM ${cart} WHERE user_id = ? AND tenant_id IS NULL AND expires_at > ? ORDER BY updated_at DESC LIMIT 1`).bind(userId, now).first();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (!cartRow) {
|
|
50
|
+
const id = nanoid();
|
|
51
|
+
const currency = getStoreConfig(event).currency || "USD";
|
|
52
|
+
await db.prepare(
|
|
53
|
+
`INSERT INTO ${cart} (
|
|
54
|
+
id, tenant_id, user_id, session_token, currency,
|
|
55
|
+
coupon_code, metadata_json, expires_at, created_at, updated_at
|
|
56
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
57
|
+
).bind(id, tenantId, userId, token, currency, null, "{}", expiresAt, now, now).run();
|
|
58
|
+
return {
|
|
59
|
+
id,
|
|
60
|
+
tenantId,
|
|
61
|
+
userId,
|
|
62
|
+
sessionToken: token,
|
|
63
|
+
currency,
|
|
64
|
+
couponCode: null,
|
|
65
|
+
items: [],
|
|
66
|
+
metadata: {},
|
|
67
|
+
expiresAt,
|
|
68
|
+
createdAt: now,
|
|
69
|
+
updatedAt: now
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const itemRows = await db.prepare(`SELECT * FROM ${cartItem} WHERE cart_id = ? ORDER BY created_at ASC`).bind(cartRow.id).all();
|
|
73
|
+
const items = (itemRows.results ?? []).map(rowToCartItem);
|
|
74
|
+
if (items.length > 0) {
|
|
75
|
+
const variantIds = items.map((i) => i.variantId);
|
|
76
|
+
const vPlaceholders = variantIds.map(() => "?").join(", ");
|
|
77
|
+
const variantRows = await db.prepare(`SELECT * FROM ${v} WHERE id IN (${vPlaceholders})`).bind(...variantIds).all().catch(() => ({ results: [] }));
|
|
78
|
+
const vMap = /* @__PURE__ */ new Map();
|
|
79
|
+
for (const row of variantRows.results ?? []) {
|
|
80
|
+
vMap.set(row.id, rowToVariant(row));
|
|
81
|
+
}
|
|
82
|
+
const productIds = items.map((i) => i.productId);
|
|
83
|
+
const pPlaceholders = productIds.map(() => "?").join(", ");
|
|
84
|
+
const productRows = await db.prepare(`SELECT * FROM ${p} WHERE id IN (${pPlaceholders})`).bind(...productIds).all().catch(() => ({ results: [] }));
|
|
85
|
+
const pMap = /* @__PURE__ */ new Map();
|
|
86
|
+
for (const row of productRows.results ?? []) {
|
|
87
|
+
pMap.set(row.id, rowToProduct(row));
|
|
88
|
+
}
|
|
89
|
+
for (const item of items) {
|
|
90
|
+
item.variant = vMap.get(item.variantId);
|
|
91
|
+
item.product = pMap.get(item.productId);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return rowToCart(cartRow, items);
|
|
95
|
+
}
|
|
96
|
+
export async function getStoreCart(cartIdOrToken, event) {
|
|
97
|
+
const db = getD1(event);
|
|
98
|
+
const cart = storeCartTbl(event);
|
|
99
|
+
const cartRow = await db.prepare(`SELECT * FROM ${cart} WHERE id = ? OR session_token = ? LIMIT 1`).bind(cartIdOrToken, cartIdOrToken).first();
|
|
100
|
+
if (!cartRow) return null;
|
|
101
|
+
return getOrCreateStoreCart(cartRow.session_token, event);
|
|
102
|
+
}
|
|
103
|
+
export async function resolveStoreCart(event, options) {
|
|
104
|
+
const explicitCartId = options?.cartId;
|
|
105
|
+
const explicitToken = options?.sessionToken;
|
|
106
|
+
const cookieToken = event ? getCookie(event, "qarpeo_cart_session") : void 0;
|
|
107
|
+
const headerToken = event ? getRequestHeader(event, "x-cart-session") : void 0;
|
|
108
|
+
const callerToken = explicitToken || headerToken || cookieToken || void 0;
|
|
109
|
+
const auth = event ? await getAuthContext(event).catch(() => null) : null;
|
|
110
|
+
const authUserId = auth?.user?.id ?? null;
|
|
111
|
+
if (explicitCartId) {
|
|
112
|
+
const targetCart = await getStoreCart(explicitCartId, event);
|
|
113
|
+
if (!targetCart) {
|
|
114
|
+
throw createError({ statusCode: 404, statusMessage: "Cart not found." });
|
|
115
|
+
}
|
|
116
|
+
if (targetCart.userId) {
|
|
117
|
+
if (!authUserId || targetCart.userId !== authUserId) {
|
|
118
|
+
throw createError({
|
|
119
|
+
statusCode: 403,
|
|
120
|
+
statusMessage: "Forbidden",
|
|
121
|
+
message: "You do not have permission to access or modify this cart."
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
} else if (targetCart.sessionToken) {
|
|
125
|
+
const isTokenMatch = callerToken && targetCart.sessionToken === callerToken;
|
|
126
|
+
if (!isTokenMatch) {
|
|
127
|
+
throw createError({
|
|
128
|
+
statusCode: 403,
|
|
129
|
+
statusMessage: "Forbidden",
|
|
130
|
+
message: "You do not have permission to access or modify this cart."
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (event && targetCart.sessionToken) {
|
|
135
|
+
setCookie(event, "qarpeo_cart_session", targetCart.sessionToken, {
|
|
136
|
+
maxAge: 30 * 86400,
|
|
137
|
+
path: "/",
|
|
138
|
+
httpOnly: false,
|
|
139
|
+
sameSite: "lax"
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
return targetCart;
|
|
143
|
+
}
|
|
144
|
+
const cart = await getOrCreateStoreCart(callerToken, event);
|
|
145
|
+
if (event && cart.sessionToken) {
|
|
146
|
+
setCookie(event, "qarpeo_cart_session", cart.sessionToken, {
|
|
147
|
+
maxAge: 30 * 86400,
|
|
148
|
+
path: "/",
|
|
149
|
+
httpOnly: false,
|
|
150
|
+
sameSite: "lax"
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return cart;
|
|
154
|
+
}
|
|
155
|
+
export async function addToStoreCart(cartId, item, event) {
|
|
156
|
+
const db = getD1(event);
|
|
157
|
+
const cart = storeCartTbl(event);
|
|
158
|
+
const cartItem = storeCartItemTbl(event);
|
|
159
|
+
const now = Date.now();
|
|
160
|
+
const safeQuantity = Math.min(999, Math.max(1, Math.trunc(Number(item.quantity) || 1)));
|
|
161
|
+
const inv = await getStoreInventory(item.variantId, event);
|
|
162
|
+
if (inv && !inv.allowBackorder) {
|
|
163
|
+
const available = inv.stockQuantity - inv.reservedQuantity;
|
|
164
|
+
if (available < safeQuantity) {
|
|
165
|
+
throw createError({
|
|
166
|
+
statusCode: 400,
|
|
167
|
+
statusMessage: `Insufficient stock. Only ${Math.max(0, available)} item(s) available.`
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const existing = await db.prepare(`SELECT * FROM ${cartItem} WHERE cart_id = ? AND variant_id = ?`).bind(cartId, item.variantId).first();
|
|
172
|
+
if (existing) {
|
|
173
|
+
const newQty = Math.min(999, Math.max(1, Math.trunc(Number(existing.quantity) || 0) + safeQuantity));
|
|
174
|
+
await db.prepare(`UPDATE ${cartItem} SET quantity = ?, updated_at = ? WHERE id = ?`).bind(newQty, now, existing.id).run();
|
|
175
|
+
await db.prepare(`UPDATE ${cart} SET updated_at = ? WHERE id = ?`).bind(now, cartId).run();
|
|
176
|
+
const updated = await db.prepare(`SELECT * FROM ${cartItem} WHERE id = ?`).bind(existing.id).first();
|
|
177
|
+
return rowToCartItem(updated);
|
|
178
|
+
}
|
|
179
|
+
const id = nanoid();
|
|
180
|
+
await db.prepare(
|
|
181
|
+
`INSERT INTO ${cartItem} (
|
|
182
|
+
id, cart_id, product_id, variant_id, quantity,
|
|
183
|
+
custom_attributes_json, created_at, updated_at
|
|
184
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
185
|
+
).bind(
|
|
186
|
+
id,
|
|
187
|
+
cartId,
|
|
188
|
+
item.productId,
|
|
189
|
+
item.variantId,
|
|
190
|
+
safeQuantity,
|
|
191
|
+
JSON.stringify(item.customAttributes || {}),
|
|
192
|
+
now,
|
|
193
|
+
now
|
|
194
|
+
).run();
|
|
195
|
+
await db.prepare(`UPDATE ${cart} SET updated_at = ? WHERE id = ?`).bind(now, cartId).run();
|
|
196
|
+
const inserted = await db.prepare(`SELECT * FROM ${cartItem} WHERE id = ?`).bind(id).first();
|
|
197
|
+
return rowToCartItem(inserted);
|
|
198
|
+
}
|
|
199
|
+
export async function updateStoreCartItem(itemId, quantity, event) {
|
|
200
|
+
const db = getD1(event);
|
|
201
|
+
const cartItem = storeCartItemTbl(event);
|
|
202
|
+
const cart = storeCartTbl(event);
|
|
203
|
+
const now = Date.now();
|
|
204
|
+
const safeQuantity = Math.trunc(Number(quantity));
|
|
205
|
+
if (isNaN(safeQuantity) || safeQuantity <= 0) {
|
|
206
|
+
await removeStoreCartItem(itemId, event);
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
const boundedQuantity = Math.min(999, safeQuantity);
|
|
210
|
+
const existing = await db.prepare(`SELECT * FROM ${cartItem} WHERE id = ?`).bind(itemId).first();
|
|
211
|
+
if (!existing) return null;
|
|
212
|
+
const inv = await getStoreInventory(existing.variant_id, event);
|
|
213
|
+
if (inv && !inv.allowBackorder) {
|
|
214
|
+
const available = inv.stockQuantity - inv.reservedQuantity;
|
|
215
|
+
if (available < boundedQuantity) {
|
|
216
|
+
throw createError({
|
|
217
|
+
statusCode: 400,
|
|
218
|
+
statusMessage: `Insufficient stock. Only ${Math.max(0, available)} item(s) available.`
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
await db.prepare(`UPDATE ${cartItem} SET quantity = ?, updated_at = ? WHERE id = ?`).bind(boundedQuantity, now, itemId).run();
|
|
223
|
+
await db.prepare(`UPDATE ${cart} SET updated_at = ? WHERE id = ?`).bind(now, existing.cart_id).run();
|
|
224
|
+
const updated = await db.prepare(`SELECT * FROM ${cartItem} WHERE id = ?`).bind(itemId).first();
|
|
225
|
+
return updated ? rowToCartItem(updated) : null;
|
|
226
|
+
}
|
|
227
|
+
export async function removeStoreCartItem(itemId, event) {
|
|
228
|
+
const db = getD1(event);
|
|
229
|
+
const cartItem = storeCartItemTbl(event);
|
|
230
|
+
const cart = storeCartTbl(event);
|
|
231
|
+
const now = Date.now();
|
|
232
|
+
const item = await db.prepare(`SELECT cart_id FROM ${cartItem} WHERE id = ?`).bind(itemId).first();
|
|
233
|
+
if (!item) return false;
|
|
234
|
+
await db.prepare(`DELETE FROM ${cartItem} WHERE id = ?`).bind(itemId).run();
|
|
235
|
+
await db.prepare(`UPDATE ${cart} SET updated_at = ? WHERE id = ?`).bind(now, item.cart_id).run();
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
export async function clearStoreCart(cartId, event) {
|
|
239
|
+
const db = getD1(event);
|
|
240
|
+
const cartItem = storeCartItemTbl(event);
|
|
241
|
+
const cart = storeCartTbl(event);
|
|
242
|
+
const now = Date.now();
|
|
243
|
+
await db.prepare(`DELETE FROM ${cartItem} WHERE cart_id = ?`).bind(cartId).run();
|
|
244
|
+
await db.prepare(`UPDATE ${cart} SET coupon_code = NULL, updated_at = ? WHERE id = ?`).bind(now, cartId).run();
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
export async function calculateStoreCartTotals(cartId, event) {
|
|
248
|
+
const cart = await getStoreCart(cartId, event);
|
|
249
|
+
if (!cart) {
|
|
250
|
+
return {
|
|
251
|
+
subtotal: 0,
|
|
252
|
+
taxTotal: 0,
|
|
253
|
+
shippingTotal: 0,
|
|
254
|
+
discountTotal: 0,
|
|
255
|
+
total: 0,
|
|
256
|
+
currency: "USD",
|
|
257
|
+
itemCount: 0
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
let subtotal = 0;
|
|
261
|
+
let itemCount = 0;
|
|
262
|
+
for (const item of cart.items) {
|
|
263
|
+
const unitPrice = item.variant?.priceOverride != null ? item.variant.priceOverride : item.product?.basePrice ?? 0;
|
|
264
|
+
subtotal += unitPrice * item.quantity;
|
|
265
|
+
itemCount += item.quantity;
|
|
266
|
+
}
|
|
267
|
+
let discountTotal = 0;
|
|
268
|
+
if (cart.couponCode) {
|
|
269
|
+
const val = await validateStoreDiscount(cart.couponCode, subtotal, event, {
|
|
270
|
+
tenantId: cart.tenantId ?? void 0
|
|
271
|
+
});
|
|
272
|
+
if (val.valid) {
|
|
273
|
+
discountTotal = val.discountAmount;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const cfg = getStoreConfig(event);
|
|
277
|
+
let shippingTotal = 0;
|
|
278
|
+
if (cfg.checkout?.shippingRates && cfg.checkout.shippingRates.length > 0) {
|
|
279
|
+
shippingTotal = cfg.checkout.shippingRates[0]?.amount ?? 0;
|
|
280
|
+
}
|
|
281
|
+
let taxTotal = 0;
|
|
282
|
+
const locCfg = cfg.localization;
|
|
283
|
+
if (locCfg?.tax) {
|
|
284
|
+
const destCountry = cart.metadata?.shippingCountry ?? detectStoreCountry(event) ?? "US";
|
|
285
|
+
const destState = cart.metadata?.shippingState;
|
|
286
|
+
const taxResult = calculateStoreTax(
|
|
287
|
+
{
|
|
288
|
+
subtotal: Math.max(0, subtotal - discountTotal),
|
|
289
|
+
shippingTotal,
|
|
290
|
+
country: destCountry,
|
|
291
|
+
state: destState,
|
|
292
|
+
isDigital: Boolean(cart.metadata?.isDigital)
|
|
293
|
+
},
|
|
294
|
+
locCfg.tax
|
|
295
|
+
);
|
|
296
|
+
taxTotal = taxResult.taxTotal;
|
|
297
|
+
} else if (cfg.checkout?.taxRate) {
|
|
298
|
+
const taxableAmount = Math.max(0, subtotal - discountTotal);
|
|
299
|
+
taxTotal = Math.round(taxableAmount * cfg.checkout.taxRate);
|
|
300
|
+
}
|
|
301
|
+
const total = Math.max(0, subtotal - discountTotal + shippingTotal + taxTotal);
|
|
302
|
+
return {
|
|
303
|
+
subtotal,
|
|
304
|
+
taxTotal,
|
|
305
|
+
shippingTotal,
|
|
306
|
+
discountTotal,
|
|
307
|
+
total,
|
|
308
|
+
currency: cart.currency,
|
|
309
|
+
itemCount
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
export async function mergeGuestCartOnLogin(guestSessionToken, userId, event) {
|
|
313
|
+
const db = getD1(event);
|
|
314
|
+
const cart = storeCartTbl(event);
|
|
315
|
+
const cartItem = storeCartItemTbl(event);
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
const guestCart = await db.prepare(`SELECT * FROM ${cart} WHERE session_token = ?`).bind(guestSessionToken).first();
|
|
318
|
+
if (!guestCart) {
|
|
319
|
+
return getOrCreateStoreCart(void 0, event);
|
|
320
|
+
}
|
|
321
|
+
const userCart = await db.prepare(`SELECT * FROM ${cart} WHERE user_id = ? AND expires_at > ? ORDER BY updated_at DESC LIMIT 1`).bind(userId, now).first();
|
|
322
|
+
if (!userCart) {
|
|
323
|
+
await db.prepare(`UPDATE ${cart} SET user_id = ?, updated_at = ? WHERE id = ?`).bind(userId, now, guestCart.id).run();
|
|
324
|
+
return await getStoreCart(guestCart.id, event);
|
|
325
|
+
}
|
|
326
|
+
const guestItems = await db.prepare(`SELECT * FROM ${cartItem} WHERE cart_id = ?`).bind(guestCart.id).all();
|
|
327
|
+
for (const item of guestItems.results ?? []) {
|
|
328
|
+
await addToStoreCart(
|
|
329
|
+
userCart.id,
|
|
330
|
+
{
|
|
331
|
+
productId: item.product_id,
|
|
332
|
+
variantId: item.variant_id,
|
|
333
|
+
quantity: Number(item.quantity),
|
|
334
|
+
customAttributes: safeJsonParse(item.custom_attributes_json, {})
|
|
335
|
+
},
|
|
336
|
+
event
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
await db.batch([
|
|
340
|
+
db.prepare(`DELETE FROM ${cartItem} WHERE cart_id = ?`).bind(guestCart.id),
|
|
341
|
+
db.prepare(`DELETE FROM ${cart} WHERE id = ?`).bind(guestCart.id)
|
|
342
|
+
]);
|
|
343
|
+
return await getStoreCart(userCart.id, event);
|
|
344
|
+
}
|
|
345
|
+
export async function validateStoreDiscount(code, subtotal, event, opts = {}) {
|
|
346
|
+
const db = getD1(event);
|
|
347
|
+
const disc = storeDiscountTbl(event);
|
|
348
|
+
const cleanCode = code.trim().toUpperCase();
|
|
349
|
+
let sql = `SELECT * FROM ${disc} WHERE UPPER(code) = ? AND is_active = 1`;
|
|
350
|
+
const params = [cleanCode];
|
|
351
|
+
if (opts.tenantId !== void 0) {
|
|
352
|
+
sql += " AND tenant_id = ?";
|
|
353
|
+
params.push(opts.tenantId);
|
|
354
|
+
}
|
|
355
|
+
sql += " LIMIT 1";
|
|
356
|
+
const row = await db.prepare(sql).bind(...params).first();
|
|
357
|
+
if (!row) {
|
|
358
|
+
return { valid: false, discountAmount: 0, message: "Invalid or expired coupon code." };
|
|
359
|
+
}
|
|
360
|
+
const discount = rowToDiscount(row);
|
|
361
|
+
const now = Date.now();
|
|
362
|
+
if (discount.startsAt && now < discount.startsAt) {
|
|
363
|
+
return { valid: false, discountAmount: 0, message: "Coupon is not active yet." };
|
|
364
|
+
}
|
|
365
|
+
if (discount.expiresAt && now > discount.expiresAt) {
|
|
366
|
+
return { valid: false, discountAmount: 0, message: "Coupon has expired." };
|
|
367
|
+
}
|
|
368
|
+
if (discount.maxUses != null && discount.usedCount >= discount.maxUses) {
|
|
369
|
+
return { valid: false, discountAmount: 0, message: "Coupon usage limit reached." };
|
|
370
|
+
}
|
|
371
|
+
if (discount.minOrderAmount > 0 && subtotal < discount.minOrderAmount) {
|
|
372
|
+
return {
|
|
373
|
+
valid: false,
|
|
374
|
+
discountAmount: 0,
|
|
375
|
+
message: `Minimum order amount of ${(discount.minOrderAmount / 100).toFixed(2)} required.`
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
let discountAmount = 0;
|
|
379
|
+
if (discount.type === "percentage") {
|
|
380
|
+
const cappedPercent = Math.max(0, Math.min(discount.value, 100));
|
|
381
|
+
discountAmount = Math.min(Math.round(subtotal * cappedPercent / 100), subtotal);
|
|
382
|
+
} else if (discount.type === "fixed_amount") {
|
|
383
|
+
discountAmount = Math.max(0, Math.min(discount.value, subtotal));
|
|
384
|
+
} else if (discount.type === "free_shipping") {
|
|
385
|
+
discountAmount = 0;
|
|
386
|
+
}
|
|
387
|
+
return { valid: true, discount, discountAmount };
|
|
388
|
+
}
|
|
389
|
+
export async function applyStoreDiscount(cartId, code, event) {
|
|
390
|
+
const db = getD1(event);
|
|
391
|
+
const cartT = storeCartTbl(event);
|
|
392
|
+
const cart = await getStoreCart(cartId, event);
|
|
393
|
+
if (!cart) {
|
|
394
|
+
throw createError({ statusCode: 404, statusMessage: "Cart not found." });
|
|
395
|
+
}
|
|
396
|
+
let subtotal = 0;
|
|
397
|
+
for (const item of cart.items) {
|
|
398
|
+
const price = item.variant?.priceOverride != null ? item.variant.priceOverride : item.product?.basePrice ?? 0;
|
|
399
|
+
subtotal += price * item.quantity;
|
|
400
|
+
}
|
|
401
|
+
const val = await validateStoreDiscount(code, subtotal, event, {
|
|
402
|
+
tenantId: cart.tenantId ?? void 0
|
|
403
|
+
});
|
|
404
|
+
if (!val.valid) {
|
|
405
|
+
return {
|
|
406
|
+
success: false,
|
|
407
|
+
totals: await calculateStoreCartTotals(cartId, event),
|
|
408
|
+
message: val.message
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
const now = Date.now();
|
|
412
|
+
await db.prepare(`UPDATE ${cartT} SET coupon_code = ?, updated_at = ? WHERE id = ?`).bind(val.discount.code, now, cartId).run();
|
|
413
|
+
const totals = await calculateStoreCartTotals(cartId, event);
|
|
414
|
+
return { success: true, totals };
|
|
415
|
+
}
|
|
416
|
+
export async function createStoreDiscount(data, event) {
|
|
417
|
+
const db = getD1(event);
|
|
418
|
+
const disc = storeDiscountTbl(event);
|
|
419
|
+
const id = nanoid();
|
|
420
|
+
const code = data.code.trim().toUpperCase();
|
|
421
|
+
const now = Date.now();
|
|
422
|
+
await db.prepare(
|
|
423
|
+
`INSERT INTO ${disc} (
|
|
424
|
+
id, tenant_id, code, type, value, min_order_amount,
|
|
425
|
+
max_uses, used_count, starts_at, expires_at, is_active,
|
|
426
|
+
metadata_json, created_at, updated_at
|
|
427
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`
|
|
428
|
+
).bind(
|
|
429
|
+
id,
|
|
430
|
+
data.tenantId ?? null,
|
|
431
|
+
code,
|
|
432
|
+
data.type,
|
|
433
|
+
data.value,
|
|
434
|
+
data.minOrderAmount ?? 0,
|
|
435
|
+
data.maxUses ?? null,
|
|
436
|
+
data.startsAt ?? null,
|
|
437
|
+
data.expiresAt ?? null,
|
|
438
|
+
data.isActive !== void 0 ? data.isActive ? 1 : 0 : 1,
|
|
439
|
+
JSON.stringify(data.metadata || {}),
|
|
440
|
+
now,
|
|
441
|
+
now
|
|
442
|
+
).run();
|
|
443
|
+
const row = await db.prepare(`SELECT * FROM ${disc} WHERE id = ?`).bind(id).first();
|
|
444
|
+
return rowToDiscount(row);
|
|
445
|
+
}
|
|
446
|
+
export async function getStoreDiscount(idOrCode, event) {
|
|
447
|
+
const db = getD1(event);
|
|
448
|
+
const disc = storeDiscountTbl(event);
|
|
449
|
+
const row = await db.prepare(`SELECT * FROM ${disc} WHERE id = ? OR UPPER(code) = ? LIMIT 1`).bind(idOrCode, idOrCode.trim().toUpperCase()).first();
|
|
450
|
+
return row ? rowToDiscount(row) : null;
|
|
451
|
+
}
|
|
452
|
+
export async function updateStoreDiscount(id, updates, event) {
|
|
453
|
+
const db = getD1(event);
|
|
454
|
+
const disc = storeDiscountTbl(event);
|
|
455
|
+
const now = Date.now();
|
|
456
|
+
const setClauses = ["updated_at = ?"];
|
|
457
|
+
const params = [now];
|
|
458
|
+
if (updates.code !== void 0) {
|
|
459
|
+
setClauses.push("code = ?");
|
|
460
|
+
params.push(updates.code.trim().toUpperCase());
|
|
461
|
+
}
|
|
462
|
+
if (updates.type !== void 0) {
|
|
463
|
+
setClauses.push("type = ?");
|
|
464
|
+
params.push(updates.type);
|
|
465
|
+
}
|
|
466
|
+
if (updates.value !== void 0) {
|
|
467
|
+
setClauses.push("value = ?");
|
|
468
|
+
params.push(updates.value);
|
|
469
|
+
}
|
|
470
|
+
if (updates.minOrderAmount !== void 0) {
|
|
471
|
+
setClauses.push("min_order_amount = ?");
|
|
472
|
+
params.push(updates.minOrderAmount);
|
|
473
|
+
}
|
|
474
|
+
if (updates.maxUses !== void 0) {
|
|
475
|
+
setClauses.push("max_uses = ?");
|
|
476
|
+
params.push(updates.maxUses);
|
|
477
|
+
}
|
|
478
|
+
if (updates.startsAt !== void 0) {
|
|
479
|
+
setClauses.push("starts_at = ?");
|
|
480
|
+
params.push(updates.startsAt);
|
|
481
|
+
}
|
|
482
|
+
if (updates.expiresAt !== void 0) {
|
|
483
|
+
setClauses.push("expires_at = ?");
|
|
484
|
+
params.push(updates.expiresAt);
|
|
485
|
+
}
|
|
486
|
+
if (updates.isActive !== void 0) {
|
|
487
|
+
setClauses.push("is_active = ?");
|
|
488
|
+
params.push(updates.isActive ? 1 : 0);
|
|
489
|
+
}
|
|
490
|
+
if (updates.metadata !== void 0) {
|
|
491
|
+
setClauses.push("metadata_json = ?");
|
|
492
|
+
params.push(JSON.stringify(updates.metadata));
|
|
493
|
+
}
|
|
494
|
+
params.push(id);
|
|
495
|
+
await db.prepare(`UPDATE ${disc} SET ${setClauses.join(", ")} WHERE id = ?`).bind(...params).run();
|
|
496
|
+
return getStoreDiscount(id, event);
|
|
497
|
+
}
|
|
498
|
+
export async function deleteStoreDiscount(id, event) {
|
|
499
|
+
const db = getD1(event);
|
|
500
|
+
const disc = storeDiscountTbl(event);
|
|
501
|
+
const res = await db.prepare(`DELETE FROM ${disc} WHERE id = ?`).bind(id).run();
|
|
502
|
+
return Boolean(res?.meta?.changes);
|
|
503
|
+
}
|
|
504
|
+
export async function queryStoreDiscounts(opts = {}, event) {
|
|
505
|
+
const db = getD1(event);
|
|
506
|
+
const disc = storeDiscountTbl(event);
|
|
507
|
+
const whereClauses = [];
|
|
508
|
+
const params = [];
|
|
509
|
+
if (opts.tenantId !== void 0) {
|
|
510
|
+
whereClauses.push("tenant_id = ?");
|
|
511
|
+
params.push(opts.tenantId);
|
|
512
|
+
}
|
|
513
|
+
if (opts.isActive !== void 0) {
|
|
514
|
+
whereClauses.push("is_active = ?");
|
|
515
|
+
params.push(opts.isActive ? 1 : 0);
|
|
516
|
+
}
|
|
517
|
+
if (opts.type !== void 0) {
|
|
518
|
+
whereClauses.push("type = ?");
|
|
519
|
+
params.push(opts.type);
|
|
520
|
+
}
|
|
521
|
+
if (opts.search) {
|
|
522
|
+
whereClauses.push("code LIKE ?");
|
|
523
|
+
params.push(`%${opts.search.trim().toUpperCase()}%`);
|
|
524
|
+
}
|
|
525
|
+
const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
|
|
526
|
+
const limit = Math.min(opts.limit ?? 20, 100);
|
|
527
|
+
const offset = opts.offset ?? 0;
|
|
528
|
+
const countResult = await db.prepare(`SELECT COUNT(*) as cnt FROM ${disc} ${whereSql}`).bind(...params).first();
|
|
529
|
+
const total = countResult?.cnt ?? 0;
|
|
530
|
+
if (total === 0) return { discounts: [], total: 0 };
|
|
531
|
+
const rows = await db.prepare(`SELECT * FROM ${disc} ${whereSql} ORDER BY created_at DESC LIMIT ? OFFSET ?`).bind(...params, limit, offset).all();
|
|
532
|
+
const discounts = (rows.results ?? []).map(rowToDiscount);
|
|
533
|
+
return { discounts, total };
|
|
534
|
+
}
|
|
535
|
+
export async function removeStoreDiscount(cartId, event) {
|
|
536
|
+
const db = getD1(event);
|
|
537
|
+
const cartT = storeCartTbl(event);
|
|
538
|
+
const now = Date.now();
|
|
539
|
+
await db.prepare(`UPDATE ${cartT} SET coupon_code = NULL, updated_at = ? WHERE id = ?`).bind(now, cartId).run();
|
|
540
|
+
const totals = await calculateStoreCartTotals(cartId, event);
|
|
541
|
+
return { success: true, totals };
|
|
542
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { RequestEvent } from "nuxt/server";
|
|
2
|
+
import type { StoreCustomerAddress, StoreOrder } from "../../../types/store";
|
|
3
|
+
export declare function createStoreCheckoutSession(cartId: string, opts?: {
|
|
4
|
+
customerEmail?: string;
|
|
5
|
+
customerName?: string;
|
|
6
|
+
shippingAddress?: StoreCustomerAddress;
|
|
7
|
+
billingAddress?: StoreCustomerAddress;
|
|
8
|
+
successUrl?: string;
|
|
9
|
+
cancelUrl?: string;
|
|
10
|
+
}, event?: RequestEvent): Promise<{
|
|
11
|
+
sessionId: string;
|
|
12
|
+
checkoutUrl?: string;
|
|
13
|
+
order: StoreOrder;
|
|
14
|
+
}>;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { useRuntimeConfig } from "nuxt/server";
|
|
2
|
+
import { getAuthContext } from "../context.mjs";
|
|
3
|
+
import { nanoid } from "../crypto.mjs";
|
|
4
|
+
import { getPaymentsConfig } from "../payments/index.mjs";
|
|
5
|
+
import { createStoreOrder } from "./orders.mjs";
|
|
6
|
+
export async function createStoreCheckoutSession(cartId, opts = {}, event) {
|
|
7
|
+
const auth = event ? await getAuthContext(event).catch(() => null) : null;
|
|
8
|
+
const email = opts.customerEmail || auth?.user?.email || "guest@checkout.local";
|
|
9
|
+
const name = opts.customerName || auth?.user?.name || void 0;
|
|
10
|
+
const order = await createStoreOrder(
|
|
11
|
+
{
|
|
12
|
+
cartId,
|
|
13
|
+
customerEmail: email,
|
|
14
|
+
customerName: name,
|
|
15
|
+
shippingAddress: opts.shippingAddress,
|
|
16
|
+
billingAddress: opts.billingAddress
|
|
17
|
+
},
|
|
18
|
+
event
|
|
19
|
+
);
|
|
20
|
+
const paymentsConfig = getPaymentsConfig(event);
|
|
21
|
+
const siteUrl = useRuntimeConfig().public?.siteUrl || "http://localhost:3000";
|
|
22
|
+
if (paymentsConfig.provider === "stripe" && paymentsConfig.secretKey) {
|
|
23
|
+
try {
|
|
24
|
+
const cleanSite = siteUrl.replace(/\/+$/, "");
|
|
25
|
+
const successUrl = opts.successUrl ? opts.successUrl.includes("{CHECKOUT_SESSION_ID}") ? opts.successUrl : `${opts.successUrl}${opts.successUrl.includes("?") ? "&" : "?"}session_id={CHECKOUT_SESSION_ID}&order_id=${order.id}` : `${cleanSite}/checkout/success?session_id={CHECKOUT_SESSION_ID}&order_id=${order.id}`;
|
|
26
|
+
const cancelUrl = opts.cancelUrl ? opts.cancelUrl : `${cleanSite}/checkout/cancel?order_id=${order.id}`;
|
|
27
|
+
const params = new URLSearchParams();
|
|
28
|
+
params.set("mode", "payment");
|
|
29
|
+
params.set("success_url", successUrl);
|
|
30
|
+
params.set("cancel_url", cancelUrl);
|
|
31
|
+
if (email && email !== "guest@checkout.local") {
|
|
32
|
+
params.set("customer_email", email);
|
|
33
|
+
}
|
|
34
|
+
if (order.userId) {
|
|
35
|
+
params.set("client_reference_id", order.userId);
|
|
36
|
+
}
|
|
37
|
+
params.set("metadata[type]", "store_order");
|
|
38
|
+
params.set("metadata[orderId]", order.id);
|
|
39
|
+
params.set("metadata[orderNumber]", order.orderNumber);
|
|
40
|
+
params.set("metadata[cartId]", cartId);
|
|
41
|
+
params.set("payment_intent_data[metadata][type]", "store_order");
|
|
42
|
+
params.set("payment_intent_data[metadata][orderId]", order.id);
|
|
43
|
+
params.set("payment_intent_data[metadata][orderNumber]", order.orderNumber);
|
|
44
|
+
order.items.forEach((item, index) => {
|
|
45
|
+
params.set(`line_items[${index}][price_data][currency]`, order.currency.toLowerCase());
|
|
46
|
+
params.set(`line_items[${index}][price_data][unit_amount]`, String(item.unitPrice));
|
|
47
|
+
params.set(`line_items[${index}][price_data][product_data][name]`, item.title || "Store Item");
|
|
48
|
+
params.set(`line_items[${index}][quantity]`, String(item.quantity));
|
|
49
|
+
});
|
|
50
|
+
if (order.shippingTotal && order.shippingTotal > 0) {
|
|
51
|
+
const shipIdx = order.items.length;
|
|
52
|
+
params.set(`line_items[${shipIdx}][price_data][currency]`, order.currency.toLowerCase());
|
|
53
|
+
params.set(`line_items[${shipIdx}][price_data][unit_amount]`, String(order.shippingTotal));
|
|
54
|
+
params.set(`line_items[${shipIdx}][price_data][product_data][name]`, "Shipping");
|
|
55
|
+
params.set(`line_items[${shipIdx}][quantity]`, "1");
|
|
56
|
+
}
|
|
57
|
+
if (order.taxTotal && order.taxTotal > 0) {
|
|
58
|
+
const taxIdx = order.items.length + (order.shippingTotal && order.shippingTotal > 0 ? 1 : 0);
|
|
59
|
+
params.set(`line_items[${taxIdx}][price_data][currency]`, order.currency.toLowerCase());
|
|
60
|
+
params.set(`line_items[${taxIdx}][price_data][unit_amount]`, String(order.taxTotal));
|
|
61
|
+
params.set(`line_items[${taxIdx}][price_data][product_data][name]`, "Tax");
|
|
62
|
+
params.set(`line_items[${taxIdx}][quantity]`, "1");
|
|
63
|
+
}
|
|
64
|
+
if (order.discountTotal && order.discountTotal > 0) {
|
|
65
|
+
try {
|
|
66
|
+
const couponRes = await fetch("https://api.stripe.com/v1/coupons", {
|
|
67
|
+
method: "POST",
|
|
68
|
+
headers: {
|
|
69
|
+
Authorization: `Bearer ${paymentsConfig.secretKey}`,
|
|
70
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
71
|
+
"Stripe-Version": "2024-06-20"
|
|
72
|
+
},
|
|
73
|
+
body: new URLSearchParams({
|
|
74
|
+
duration: "once",
|
|
75
|
+
amount_off: String(order.discountTotal),
|
|
76
|
+
currency: order.currency.toLowerCase(),
|
|
77
|
+
name: "Order Discount"
|
|
78
|
+
}).toString()
|
|
79
|
+
});
|
|
80
|
+
if (couponRes.ok) {
|
|
81
|
+
const coupon = await couponRes.json();
|
|
82
|
+
params.set("discounts[0][coupon]", coupon.id);
|
|
83
|
+
}
|
|
84
|
+
} catch {
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const res = await fetch("https://api.stripe.com/v1/checkout/sessions", {
|
|
88
|
+
method: "POST",
|
|
89
|
+
signal: AbortSignal.timeout(1e4),
|
|
90
|
+
headers: {
|
|
91
|
+
Authorization: `Bearer ${paymentsConfig.secretKey}`,
|
|
92
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
93
|
+
"Stripe-Version": "2024-06-20"
|
|
94
|
+
},
|
|
95
|
+
body: params.toString()
|
|
96
|
+
});
|
|
97
|
+
if (res.ok) {
|
|
98
|
+
const session = await res.json();
|
|
99
|
+
return {
|
|
100
|
+
sessionId: session.id,
|
|
101
|
+
order,
|
|
102
|
+
checkoutUrl: session.url || `/checkout/${order.id}?session=${session.id}`
|
|
103
|
+
};
|
|
104
|
+
} else {
|
|
105
|
+
const errText = await res.text();
|
|
106
|
+
console.error("[qarpeo:store] Stripe Checkout session creation failed:", errText);
|
|
107
|
+
}
|
|
108
|
+
} catch (err) {
|
|
109
|
+
console.error("[qarpeo:store] Failed to create Stripe checkout session:", err?.message || err);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const sessionId = nanoid(32);
|
|
113
|
+
return {
|
|
114
|
+
sessionId,
|
|
115
|
+
order,
|
|
116
|
+
checkoutUrl: `/checkout/${order.id}?session=${sessionId}`
|
|
117
|
+
};
|
|
118
|
+
}
|