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,159 @@
|
|
|
1
|
+
import { nanoid, timingSafeEqualString } from "../crypto.mjs";
|
|
2
|
+
import { computeHmacSha256 } from "./common.mjs";
|
|
3
|
+
export async function verifyStripeSignature(rawBody, signatureHeader, secret, toleranceSec = 300) {
|
|
4
|
+
if (!signatureHeader || !secret) return false;
|
|
5
|
+
const parts = signatureHeader.split(",");
|
|
6
|
+
let timestamp = "";
|
|
7
|
+
const signatures = [];
|
|
8
|
+
for (const p of parts) {
|
|
9
|
+
const idx = p.indexOf("=");
|
|
10
|
+
if (idx !== -1) {
|
|
11
|
+
const k = p.slice(0, idx).trim();
|
|
12
|
+
const v = p.slice(idx + 1).trim();
|
|
13
|
+
if (k === "t") timestamp = v;
|
|
14
|
+
if (k === "v1") signatures.push(v);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
if (!timestamp || !signatures.length) return false;
|
|
18
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
19
|
+
const tsNum = parseInt(timestamp, 10);
|
|
20
|
+
if (isNaN(tsNum) || Math.abs(now - tsNum) > toleranceSec) {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
const payload = `${timestamp}.${rawBody}`;
|
|
24
|
+
const expectedSignature = await computeHmacSha256(secret, payload);
|
|
25
|
+
return signatures.some((sig) => timingSafeEqualString(sig.toLowerCase(), expectedSignature.toLowerCase()));
|
|
26
|
+
}
|
|
27
|
+
export async function handleStripeWebhookEvent(db, ct, st, payload, now) {
|
|
28
|
+
const eventType = payload.type;
|
|
29
|
+
const obj = payload.data?.object || {};
|
|
30
|
+
const eventData = obj;
|
|
31
|
+
let affectedSubId = null;
|
|
32
|
+
switch (eventType) {
|
|
33
|
+
case "checkout.session.completed": {
|
|
34
|
+
const customerId = obj.customer;
|
|
35
|
+
const customerEmail = obj.customer_details?.email || obj.customer_email || "";
|
|
36
|
+
const customerName = obj.customer_details?.name || null;
|
|
37
|
+
const userId = obj.metadata?.userId || obj.client_reference_id;
|
|
38
|
+
const orgId = obj.metadata?.orgId || null;
|
|
39
|
+
if (userId && customerId) {
|
|
40
|
+
await db.prepare(
|
|
41
|
+
`INSERT INTO ${ct} (id, user_id, org_id, provider, customer_id, email, name, metadata_json, created_at, updated_at)
|
|
42
|
+
VALUES (?, ?, ?, 'stripe', ?, ?, ?, ?, ?, ?)
|
|
43
|
+
ON CONFLICT(customer_id) DO UPDATE SET email = excluded.email, name = excluded.name, org_id = excluded.org_id, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
44
|
+
).bind(
|
|
45
|
+
nanoid(),
|
|
46
|
+
userId,
|
|
47
|
+
orgId,
|
|
48
|
+
customerId,
|
|
49
|
+
customerEmail,
|
|
50
|
+
customerName,
|
|
51
|
+
JSON.stringify(obj.metadata || {}),
|
|
52
|
+
now,
|
|
53
|
+
now
|
|
54
|
+
).run();
|
|
55
|
+
}
|
|
56
|
+
const subId = obj.subscription;
|
|
57
|
+
if (subId) {
|
|
58
|
+
affectedSubId = subId;
|
|
59
|
+
const planId = obj.metadata?.planId || `default`;
|
|
60
|
+
await db.prepare(
|
|
61
|
+
`INSERT INTO ${st}
|
|
62
|
+
(id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
63
|
+
VALUES (?, ?, ?, ?, 'stripe', ?, ?, '', 'active', 1, 0, ?, ?, null, null, ?, ?, ?)
|
|
64
|
+
ON CONFLICT(subscription_id) DO NOTHING`
|
|
65
|
+
).bind(
|
|
66
|
+
nanoid(),
|
|
67
|
+
customerId || "",
|
|
68
|
+
userId || "",
|
|
69
|
+
orgId,
|
|
70
|
+
subId,
|
|
71
|
+
planId,
|
|
72
|
+
now,
|
|
73
|
+
now + 30 * 864e5,
|
|
74
|
+
JSON.stringify(obj.metadata || {}),
|
|
75
|
+
now,
|
|
76
|
+
now
|
|
77
|
+
).run();
|
|
78
|
+
}
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
case "customer.subscription.created":
|
|
82
|
+
case "customer.subscription.updated": {
|
|
83
|
+
const subId = obj.id;
|
|
84
|
+
affectedSubId = subId;
|
|
85
|
+
const customerId = obj.customer;
|
|
86
|
+
const status = obj.status;
|
|
87
|
+
const priceId = obj.items?.data?.[0]?.price?.id || obj.plan?.id || "";
|
|
88
|
+
const planId = obj.metadata?.planId || obj.items?.data?.[0]?.price?.lookup_key || priceId;
|
|
89
|
+
const quantity = obj.items?.data?.[0]?.quantity || obj.quantity || 1;
|
|
90
|
+
const cancelAtPeriodEnd = obj.cancel_at_period_end ? 1 : 0;
|
|
91
|
+
const periodStart = obj.current_period_start ? obj.current_period_start * 1e3 : now;
|
|
92
|
+
const periodEnd = obj.current_period_end ? obj.current_period_end * 1e3 : now + 30 * 864e5;
|
|
93
|
+
const trialEnd = obj.trial_end ? obj.trial_end * 1e3 : null;
|
|
94
|
+
const canceledAt = obj.canceled_at ? obj.canceled_at * 1e3 : null;
|
|
95
|
+
const cust = await db.prepare(`SELECT user_id, org_id FROM ${ct} WHERE customer_id = ? LIMIT 1`).bind(customerId).first();
|
|
96
|
+
const userId = cust?.user_id || obj.metadata?.userId || "";
|
|
97
|
+
const orgId = cust?.org_id || obj.metadata?.orgId || null;
|
|
98
|
+
await db.prepare(
|
|
99
|
+
`INSERT INTO ${st}
|
|
100
|
+
(id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
101
|
+
VALUES (?, ?, ?, ?, 'stripe', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
102
|
+
ON CONFLICT(subscription_id) DO UPDATE SET
|
|
103
|
+
plan_id = excluded.plan_id, price_id = excluded.price_id, status = excluded.status,
|
|
104
|
+
quantity = excluded.quantity, cancel_at_period_end = excluded.cancel_at_period_end,
|
|
105
|
+
current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end,
|
|
106
|
+
trial_end = excluded.trial_end, canceled_at = excluded.canceled_at,
|
|
107
|
+
metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
108
|
+
).bind(
|
|
109
|
+
nanoid(),
|
|
110
|
+
customerId,
|
|
111
|
+
userId,
|
|
112
|
+
orgId,
|
|
113
|
+
subId,
|
|
114
|
+
planId,
|
|
115
|
+
priceId,
|
|
116
|
+
status,
|
|
117
|
+
quantity,
|
|
118
|
+
cancelAtPeriodEnd,
|
|
119
|
+
periodStart,
|
|
120
|
+
periodEnd,
|
|
121
|
+
trialEnd,
|
|
122
|
+
canceledAt,
|
|
123
|
+
JSON.stringify(obj.metadata || {}),
|
|
124
|
+
now,
|
|
125
|
+
now
|
|
126
|
+
).run();
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
case "customer.subscription.deleted": {
|
|
130
|
+
const subId = obj.id;
|
|
131
|
+
affectedSubId = subId;
|
|
132
|
+
await db.prepare(
|
|
133
|
+
`UPDATE ${st} SET status = 'canceled', canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
134
|
+
).bind(now, now, subId).run();
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
case "invoice.payment_succeeded": {
|
|
138
|
+
const subId = obj.subscription;
|
|
139
|
+
if (subId) {
|
|
140
|
+
affectedSubId = subId;
|
|
141
|
+
await db.prepare(
|
|
142
|
+
`UPDATE ${st} SET status = 'active', updated_at = ? WHERE subscription_id = ?`
|
|
143
|
+
).bind(now, subId).run();
|
|
144
|
+
}
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
case "invoice.payment_failed": {
|
|
148
|
+
const subId = obj.subscription;
|
|
149
|
+
if (subId) {
|
|
150
|
+
affectedSubId = subId;
|
|
151
|
+
await db.prepare(
|
|
152
|
+
`UPDATE ${st} SET status = 'past_due', updated_at = ? WHERE subscription_id = ?`
|
|
153
|
+
).bind(now, subId).run();
|
|
154
|
+
}
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { eventType, eventData, affectedSubId };
|
|
159
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type RequestEvent } from "nuxt/server";
|
|
2
|
+
import type { QarpeoSubscription, SubscriptionStatus } from "../../../../types";
|
|
3
|
+
/**
|
|
4
|
+
* Cancels a Stripe subscription at the end of the current billing period. Calls Stripe POST
|
|
5
|
+
* /v1/subscriptions/{id} with `cancel_at_period_end: true` and marks the D1 row as canceled.
|
|
6
|
+
*/
|
|
7
|
+
export declare function cancelSubscription(event: RequestEvent, subscriptionId: string): Promise<{
|
|
8
|
+
success: boolean;
|
|
9
|
+
subscriptionId: string;
|
|
10
|
+
status: string;
|
|
11
|
+
}>;
|
|
12
|
+
/**
|
|
13
|
+
* Pauses collection on a Stripe subscription. Calls Stripe POST /v1/subscriptions/{id} with
|
|
14
|
+
* `pause_collection: { behavior: 'void', resumes_at: null }` and marks the D1 row as paused.
|
|
15
|
+
*/
|
|
16
|
+
export declare function pauseSubscription(event: RequestEvent, subscriptionId: string): Promise<{
|
|
17
|
+
success: boolean;
|
|
18
|
+
subscriptionId: string;
|
|
19
|
+
status: string;
|
|
20
|
+
}>;
|
|
21
|
+
/**
|
|
22
|
+
* Changes a Stripe subscription to a new price/plan with proration. Fetches the current
|
|
23
|
+
* subscription item id, calls Stripe POST /v1/subscriptions/{id} to swap the item price, and
|
|
24
|
+
* updates the D1 plan_id/price_id.
|
|
25
|
+
*/
|
|
26
|
+
export declare function changePlan(event: RequestEvent, subscriptionId: string, newPriceId: string): Promise<{
|
|
27
|
+
success: boolean;
|
|
28
|
+
subscriptionId: string;
|
|
29
|
+
planId: string;
|
|
30
|
+
}>;
|
|
31
|
+
/**
|
|
32
|
+
* Gets the current active subscription for a user or organization from D1.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* const sub = await getSubscription(event)
|
|
37
|
+
* if (sub?.status === "active") {
|
|
38
|
+
* console.log("Plan:", sub.planId)
|
|
39
|
+
* }
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function getSubscription(event: RequestEvent, options?: {
|
|
43
|
+
userId?: string;
|
|
44
|
+
orgId?: string;
|
|
45
|
+
}): Promise<QarpeoSubscription | null>;
|
|
46
|
+
export interface RequireSubscriptionOptions {
|
|
47
|
+
tier?: string | string[];
|
|
48
|
+
plan?: string | string[];
|
|
49
|
+
status?: SubscriptionStatus[];
|
|
50
|
+
message?: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Server guard: throws 402 Payment Required if caller has no active subscription.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```ts
|
|
57
|
+
* const sub = await requireSubscription(event, { plan: "pro" })
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare function requireSubscription(event: RequestEvent, options?: RequireSubscriptionOptions): Promise<QarpeoSubscription>;
|
|
61
|
+
/**
|
|
62
|
+
* Checks whether the current user or organization's active subscription plan includes a specific
|
|
63
|
+
* feature flag.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* if (!(await hasFeature(event, "custom_domain"))) {
|
|
68
|
+
* throw createError({ statusCode: 403, message: "Custom domains require Pro plan" })
|
|
69
|
+
* }
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
export declare function hasFeature(event: RequestEvent, feature: string): Promise<boolean>;
|
|
73
|
+
/**
|
|
74
|
+
* Checks whether a numerical usage limit defined on the active plan configuration has been
|
|
75
|
+
* exceeded.
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* const { allowed, limit, current } = await checkLimit(event, "max_projects", projectCount)
|
|
80
|
+
* if (!allowed) {
|
|
81
|
+
* throw createError({ statusCode: 403, message: `Project limit (${limit}) reached` })
|
|
82
|
+
* }
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
export declare function checkLimit(event: RequestEvent, limitKey: string, currentUsage: number): Promise<{
|
|
86
|
+
allowed: boolean;
|
|
87
|
+
limit: number;
|
|
88
|
+
current: number;
|
|
89
|
+
}>;
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { createError } from "nuxt/server";
|
|
2
|
+
import { getAuthContext } from "../context.mjs";
|
|
3
|
+
import {
|
|
4
|
+
STRIPE_API_VERSION,
|
|
5
|
+
subscriptionTbl,
|
|
6
|
+
getPaymentsDb,
|
|
7
|
+
getPaymentsConfig,
|
|
8
|
+
ensurePaymentsTables,
|
|
9
|
+
rowToSubscription
|
|
10
|
+
} from "./common.mjs";
|
|
11
|
+
export async function cancelSubscription(event, subscriptionId) {
|
|
12
|
+
await ensurePaymentsTables(event);
|
|
13
|
+
const st = subscriptionTbl(event);
|
|
14
|
+
const db = getPaymentsDb(event);
|
|
15
|
+
const config = getPaymentsConfig(event);
|
|
16
|
+
if (!subscriptionId) {
|
|
17
|
+
throw createError({ statusCode: 400, message: "subscriptionId is required" });
|
|
18
|
+
}
|
|
19
|
+
if (!config.secretKey) {
|
|
20
|
+
throw createError({
|
|
21
|
+
statusCode: 500,
|
|
22
|
+
statusMessage: "Internal Server Error",
|
|
23
|
+
message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
if (config.provider !== "stripe") {
|
|
27
|
+
throw createError({
|
|
28
|
+
statusCode: 501,
|
|
29
|
+
message: `Subscription cancel not implemented for provider ${config.provider}`
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const params = new URLSearchParams();
|
|
33
|
+
params.set("cancel_at_period_end", "true");
|
|
34
|
+
const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
35
|
+
method: "POST",
|
|
36
|
+
signal: AbortSignal.timeout(1e4),
|
|
37
|
+
headers: {
|
|
38
|
+
Authorization: `Bearer ${config.secretKey}`,
|
|
39
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
40
|
+
"Stripe-Version": STRIPE_API_VERSION
|
|
41
|
+
},
|
|
42
|
+
body: params.toString()
|
|
43
|
+
});
|
|
44
|
+
if (!res.ok) {
|
|
45
|
+
const errText = await res.text();
|
|
46
|
+
throw createError({ statusCode: res.status, message: `Stripe cancel failed: ${errText}` });
|
|
47
|
+
}
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
await db.prepare(
|
|
50
|
+
`UPDATE ${st} SET status = 'canceled', cancel_at_period_end = 1, updated_at = ? WHERE subscription_id = ?`
|
|
51
|
+
).bind(now, subscriptionId).run();
|
|
52
|
+
return { success: true, subscriptionId, status: "canceled" };
|
|
53
|
+
}
|
|
54
|
+
export async function pauseSubscription(event, subscriptionId) {
|
|
55
|
+
await ensurePaymentsTables(event);
|
|
56
|
+
const st = subscriptionTbl(event);
|
|
57
|
+
const db = getPaymentsDb(event);
|
|
58
|
+
const config = getPaymentsConfig(event);
|
|
59
|
+
if (!subscriptionId) {
|
|
60
|
+
throw createError({ statusCode: 400, message: "subscriptionId is required" });
|
|
61
|
+
}
|
|
62
|
+
if (!config.secretKey) {
|
|
63
|
+
throw createError({
|
|
64
|
+
statusCode: 500,
|
|
65
|
+
statusMessage: "Internal Server Error",
|
|
66
|
+
message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
if (config.provider !== "stripe") {
|
|
70
|
+
throw createError({
|
|
71
|
+
statusCode: 501,
|
|
72
|
+
message: `Subscription pause not implemented for provider ${config.provider}`
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const params = new URLSearchParams();
|
|
76
|
+
params.set("pause_collection[behavior]", "void");
|
|
77
|
+
params.set("pause_collection[resumes_at]", "");
|
|
78
|
+
const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
79
|
+
method: "POST",
|
|
80
|
+
signal: AbortSignal.timeout(1e4),
|
|
81
|
+
headers: {
|
|
82
|
+
Authorization: `Bearer ${config.secretKey}`,
|
|
83
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
84
|
+
"Stripe-Version": STRIPE_API_VERSION
|
|
85
|
+
},
|
|
86
|
+
body: params.toString()
|
|
87
|
+
});
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
const errText = await res.text();
|
|
90
|
+
throw createError({ statusCode: res.status, message: `Stripe pause failed: ${errText}` });
|
|
91
|
+
}
|
|
92
|
+
const now = Date.now();
|
|
93
|
+
await db.prepare(
|
|
94
|
+
`UPDATE ${st} SET status = 'paused', updated_at = ? WHERE subscription_id = ?`
|
|
95
|
+
).bind(now, subscriptionId).run();
|
|
96
|
+
return { success: true, subscriptionId, status: "paused" };
|
|
97
|
+
}
|
|
98
|
+
export async function changePlan(event, subscriptionId, newPriceId) {
|
|
99
|
+
await ensurePaymentsTables(event);
|
|
100
|
+
const st = subscriptionTbl(event);
|
|
101
|
+
const db = getPaymentsDb(event);
|
|
102
|
+
const config = getPaymentsConfig(event);
|
|
103
|
+
if (!subscriptionId) {
|
|
104
|
+
throw createError({ statusCode: 400, message: "subscriptionId is required" });
|
|
105
|
+
}
|
|
106
|
+
if (!newPriceId) {
|
|
107
|
+
throw createError({ statusCode: 400, message: "newPriceId is required" });
|
|
108
|
+
}
|
|
109
|
+
if (!config.secretKey) {
|
|
110
|
+
throw createError({
|
|
111
|
+
statusCode: 500,
|
|
112
|
+
statusMessage: "Internal Server Error",
|
|
113
|
+
message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
if (config.provider !== "stripe") {
|
|
117
|
+
throw createError({
|
|
118
|
+
statusCode: 501,
|
|
119
|
+
message: `Plan change not implemented for provider ${config.provider}`
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
const getRes = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
123
|
+
method: "GET",
|
|
124
|
+
signal: AbortSignal.timeout(1e4),
|
|
125
|
+
headers: {
|
|
126
|
+
Authorization: `Bearer ${config.secretKey}`,
|
|
127
|
+
"Stripe-Version": STRIPE_API_VERSION
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
if (!getRes.ok) {
|
|
131
|
+
const errText = await getRes.text();
|
|
132
|
+
throw createError({
|
|
133
|
+
statusCode: getRes.status,
|
|
134
|
+
message: `Stripe fetch subscription failed: ${errText}`
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
const sub = await getRes.json();
|
|
138
|
+
const currentItemId = sub?.items?.data?.[0]?.id;
|
|
139
|
+
if (!currentItemId) {
|
|
140
|
+
throw createError({ statusCode: 409, message: "Subscription has no item to change" });
|
|
141
|
+
}
|
|
142
|
+
const params = new URLSearchParams();
|
|
143
|
+
params.set("items[0][id]", currentItemId);
|
|
144
|
+
params.set("items[0][price]", newPriceId);
|
|
145
|
+
params.set("proration_behavior", "create_prorations");
|
|
146
|
+
const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
|
|
147
|
+
method: "POST",
|
|
148
|
+
signal: AbortSignal.timeout(1e4),
|
|
149
|
+
headers: {
|
|
150
|
+
Authorization: `Bearer ${config.secretKey}`,
|
|
151
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
152
|
+
"Stripe-Version": STRIPE_API_VERSION
|
|
153
|
+
},
|
|
154
|
+
body: params.toString()
|
|
155
|
+
});
|
|
156
|
+
if (!res.ok) {
|
|
157
|
+
const errText = await res.text();
|
|
158
|
+
throw createError({ statusCode: res.status, message: `Stripe plan change failed: ${errText}` });
|
|
159
|
+
}
|
|
160
|
+
const updated = await res.json();
|
|
161
|
+
const newPlanId = updated?.items?.data?.[0]?.price?.id || newPriceId;
|
|
162
|
+
const now = Date.now();
|
|
163
|
+
await db.prepare(
|
|
164
|
+
`UPDATE ${st} SET plan_id = ?, price_id = ?, updated_at = ? WHERE subscription_id = ?`
|
|
165
|
+
).bind(newPlanId, newPriceId, now, subscriptionId).run();
|
|
166
|
+
return { success: true, subscriptionId, planId: newPlanId };
|
|
167
|
+
}
|
|
168
|
+
export async function getSubscription(event, options) {
|
|
169
|
+
await ensurePaymentsTables(event);
|
|
170
|
+
const st = subscriptionTbl(event);
|
|
171
|
+
const db = getPaymentsDb(event);
|
|
172
|
+
const auth = await getAuthContext(event);
|
|
173
|
+
const userId = options?.userId || auth?.user?.id;
|
|
174
|
+
const orgId = options?.orgId || auth?.organization?.id;
|
|
175
|
+
if (!userId && !orgId) return null;
|
|
176
|
+
let row = null;
|
|
177
|
+
if (orgId) {
|
|
178
|
+
row = await db.prepare(
|
|
179
|
+
`SELECT * FROM ${st} WHERE org_id = ? AND status IN ('active', 'trialing') ORDER BY created_at DESC LIMIT 1`
|
|
180
|
+
).bind(orgId).first();
|
|
181
|
+
}
|
|
182
|
+
if (!row && userId) {
|
|
183
|
+
row = await db.prepare(
|
|
184
|
+
`SELECT * FROM ${st} WHERE user_id = ? AND status IN ('active', 'trialing') ORDER BY created_at DESC LIMIT 1`
|
|
185
|
+
).bind(userId).first();
|
|
186
|
+
}
|
|
187
|
+
return row ? rowToSubscription(row) : null;
|
|
188
|
+
}
|
|
189
|
+
export async function requireSubscription(event, options) {
|
|
190
|
+
const sub = await getSubscription(event);
|
|
191
|
+
if (!sub) {
|
|
192
|
+
throw createError({
|
|
193
|
+
statusCode: 402,
|
|
194
|
+
statusMessage: "Payment Required",
|
|
195
|
+
message: options?.message || "Active subscription required to access this resource"
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const allowedStatuses = options?.status || ["active", "trialing"];
|
|
199
|
+
if (!allowedStatuses.includes(sub.status)) {
|
|
200
|
+
throw createError({
|
|
201
|
+
statusCode: 402,
|
|
202
|
+
statusMessage: "Payment Required",
|
|
203
|
+
message: options?.message || `Subscription status is ${sub.status}. Active subscription required.`
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const requiredPlans = options?.plan ? Array.isArray(options.plan) ? options.plan : [options.plan] : [];
|
|
207
|
+
const requiredTiers = options?.tier ? Array.isArray(options.tier) ? options.tier : [options.tier] : [];
|
|
208
|
+
const allRequired = [...requiredPlans, ...requiredTiers];
|
|
209
|
+
if (allRequired.length > 0 && !allRequired.includes(sub.planId)) {
|
|
210
|
+
throw createError({
|
|
211
|
+
statusCode: 403,
|
|
212
|
+
statusMessage: "Forbidden",
|
|
213
|
+
message: options?.message || `Subscription tier "${sub.planId}" does not satisfy required plan (${allRequired.join(", ")})`
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return sub;
|
|
217
|
+
}
|
|
218
|
+
export async function hasFeature(event, feature) {
|
|
219
|
+
const sub = await getSubscription(event);
|
|
220
|
+
if (!sub || sub.status !== "active" && sub.status !== "trialing") return false;
|
|
221
|
+
const config = getPaymentsConfig(event);
|
|
222
|
+
const plan = config.plans?.[sub.planId];
|
|
223
|
+
if (!plan?.features) return false;
|
|
224
|
+
return plan.features.includes(feature);
|
|
225
|
+
}
|
|
226
|
+
export async function checkLimit(event, limitKey, currentUsage) {
|
|
227
|
+
const sub = await getSubscription(event);
|
|
228
|
+
const config = getPaymentsConfig(event);
|
|
229
|
+
const plan = sub ? config.plans?.[sub.planId] : void 0;
|
|
230
|
+
const limit = plan?.limits?.[limitKey] ?? Infinity;
|
|
231
|
+
return {
|
|
232
|
+
allowed: currentUsage < limit,
|
|
233
|
+
limit,
|
|
234
|
+
current: currentUsage
|
|
235
|
+
};
|
|
236
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type RequestEvent } from "nuxt/server";
|
|
2
|
+
import type { MeterRecordOptions, MeterUsageResult, UsageSummary } from "../../../../types";
|
|
3
|
+
/** Records a metered usage event in D1 and reports to upstream provider (e.g. Stripe Meters API). */
|
|
4
|
+
export declare function reportUsage(event: RequestEvent, options: MeterRecordOptions): Promise<MeterUsageResult>;
|
|
5
|
+
/** Queries metered usage summary and records from D1 for a user or organization. */
|
|
6
|
+
export declare function getUsageSummary(event: RequestEvent, options: {
|
|
7
|
+
eventName?: string;
|
|
8
|
+
userId?: string;
|
|
9
|
+
orgId?: string;
|
|
10
|
+
since?: number;
|
|
11
|
+
until?: number;
|
|
12
|
+
}): Promise<UsageSummary>;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { getAuthContext } from "../context.mjs";
|
|
2
|
+
import { nanoid } from "../crypto.mjs";
|
|
3
|
+
import {
|
|
4
|
+
STRIPE_API_VERSION,
|
|
5
|
+
customerTbl,
|
|
6
|
+
usageRecordTbl,
|
|
7
|
+
getPaymentsDb,
|
|
8
|
+
getPaymentsConfig,
|
|
9
|
+
ensurePaymentsTables
|
|
10
|
+
} from "./common.mjs";
|
|
11
|
+
export async function reportUsage(event, options) {
|
|
12
|
+
await ensurePaymentsTables(event);
|
|
13
|
+
const ct = customerTbl(event);
|
|
14
|
+
const ut = usageRecordTbl(event);
|
|
15
|
+
const db = getPaymentsDb(event);
|
|
16
|
+
const config = getPaymentsConfig(event);
|
|
17
|
+
const auth = await getAuthContext(event).catch(() => null);
|
|
18
|
+
const userId = options.userId || auth?.user?.id || null;
|
|
19
|
+
const orgId = options.orgId || auth?.organization?.id || null;
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
const timestamp = options.timestamp || now;
|
|
22
|
+
const id = nanoid();
|
|
23
|
+
const quantity = options.quantity ?? 1;
|
|
24
|
+
const action = options.action || "increment";
|
|
25
|
+
const metadataJson = options.metadata ? JSON.stringify(options.metadata) : "{}";
|
|
26
|
+
await db.prepare(
|
|
27
|
+
`INSERT INTO ${ut}
|
|
28
|
+
(id, user_id, org_id, customer_id, subscription_id, event_name, quantity, action, metadata_json, timestamp, created_at)
|
|
29
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
30
|
+
).bind(
|
|
31
|
+
id,
|
|
32
|
+
userId,
|
|
33
|
+
orgId,
|
|
34
|
+
options.customerId || null,
|
|
35
|
+
options.subscriptionId || null,
|
|
36
|
+
options.eventName,
|
|
37
|
+
quantity,
|
|
38
|
+
action,
|
|
39
|
+
metadataJson,
|
|
40
|
+
timestamp,
|
|
41
|
+
now
|
|
42
|
+
).run();
|
|
43
|
+
if (config.provider === "stripe" && config.secretKey) {
|
|
44
|
+
let custId = options.customerId;
|
|
45
|
+
if (!custId && userId) {
|
|
46
|
+
const cust = await db.prepare(
|
|
47
|
+
`SELECT customer_id FROM ${ct} WHERE user_id = ? AND provider = 'stripe' LIMIT 1`
|
|
48
|
+
).bind(userId).first();
|
|
49
|
+
if (cust) custId = cust.customer_id;
|
|
50
|
+
}
|
|
51
|
+
if (custId) {
|
|
52
|
+
try {
|
|
53
|
+
const params = new URLSearchParams();
|
|
54
|
+
params.set("event_name", options.eventName);
|
|
55
|
+
params.set("payload[value]", String(quantity));
|
|
56
|
+
params.set("payload[stripe_customer_id]", custId);
|
|
57
|
+
params.set("timestamp", String(Math.floor(timestamp / 1e3)));
|
|
58
|
+
const res = await fetch("https://api.stripe.com/v1/billing/meter_events", {
|
|
59
|
+
method: "POST",
|
|
60
|
+
signal: AbortSignal.timeout(1e4),
|
|
61
|
+
headers: {
|
|
62
|
+
Authorization: `Bearer ${config.secretKey}`,
|
|
63
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
64
|
+
"Stripe-Version": STRIPE_API_VERSION
|
|
65
|
+
},
|
|
66
|
+
body: params.toString()
|
|
67
|
+
});
|
|
68
|
+
if (!res.ok) {
|
|
69
|
+
const errText = await res.text();
|
|
70
|
+
console.warn("[qarpeo:payments] Stripe meter event reported non-ok:", errText);
|
|
71
|
+
}
|
|
72
|
+
} catch (err) {
|
|
73
|
+
console.warn("[qarpeo:payments] Failed to report meter event to Stripe:", err);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
success: true,
|
|
79
|
+
id,
|
|
80
|
+
eventName: options.eventName,
|
|
81
|
+
quantity,
|
|
82
|
+
timestamp
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
export async function getUsageSummary(event, options) {
|
|
86
|
+
await ensurePaymentsTables(event);
|
|
87
|
+
const ut = usageRecordTbl(event);
|
|
88
|
+
const db = getPaymentsDb(event);
|
|
89
|
+
const auth = await getAuthContext(event).catch(() => null);
|
|
90
|
+
const userId = options.userId || auth?.user?.id;
|
|
91
|
+
const orgId = options.orgId || auth?.organization?.id;
|
|
92
|
+
let sql = `SELECT * FROM ${ut} WHERE 1=1`;
|
|
93
|
+
const params = [];
|
|
94
|
+
if (options.eventName) {
|
|
95
|
+
sql += " AND event_name = ?";
|
|
96
|
+
params.push(options.eventName);
|
|
97
|
+
}
|
|
98
|
+
if (orgId) {
|
|
99
|
+
sql += " AND org_id = ?";
|
|
100
|
+
params.push(orgId);
|
|
101
|
+
} else if (userId) {
|
|
102
|
+
sql += " AND user_id = ?";
|
|
103
|
+
params.push(userId);
|
|
104
|
+
}
|
|
105
|
+
if (options.since) {
|
|
106
|
+
sql += " AND timestamp >= ?";
|
|
107
|
+
params.push(options.since);
|
|
108
|
+
}
|
|
109
|
+
if (options.until) {
|
|
110
|
+
sql += " AND timestamp <= ?";
|
|
111
|
+
params.push(options.until);
|
|
112
|
+
}
|
|
113
|
+
sql += " ORDER BY timestamp DESC LIMIT 500";
|
|
114
|
+
const stmt = db.prepare(sql);
|
|
115
|
+
const bound = params.length > 0 ? stmt.bind(...params) : stmt;
|
|
116
|
+
const result = await bound.all();
|
|
117
|
+
const rows = result.results || [];
|
|
118
|
+
let total = 0;
|
|
119
|
+
for (const row of rows) {
|
|
120
|
+
if (row.action === "set") {
|
|
121
|
+
total = row.quantity;
|
|
122
|
+
} else {
|
|
123
|
+
total += row.quantity;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
eventName: options.eventName || "all",
|
|
128
|
+
total,
|
|
129
|
+
count: rows.length,
|
|
130
|
+
records: rows.map((r) => ({
|
|
131
|
+
id: r.id,
|
|
132
|
+
userId: r.user_id,
|
|
133
|
+
orgId: r.org_id,
|
|
134
|
+
customerId: r.customer_id,
|
|
135
|
+
subscriptionId: r.subscription_id,
|
|
136
|
+
eventName: r.event_name,
|
|
137
|
+
quantity: r.quantity,
|
|
138
|
+
action: r.action,
|
|
139
|
+
metadata: JSON.parse(r.metadata_json || "{}"),
|
|
140
|
+
timestamp: r.timestamp
|
|
141
|
+
}))
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type RequestEvent } from "nuxt/server";
|
|
2
|
+
export declare function processPaymentWebhook(event: RequestEvent, rawBody: string): Promise<{
|
|
3
|
+
success: boolean;
|
|
4
|
+
eventType?: string;
|
|
5
|
+
error?: string;
|
|
6
|
+
} | {
|
|
7
|
+
received: true;
|
|
8
|
+
skipped: true;
|
|
9
|
+
reason: "duplicate";
|
|
10
|
+
}>;
|