web-agent-bridge 3.9.2 → 3.10.0

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.
@@ -116,6 +116,35 @@ function handleWebhookEvent(event) {
116
116
  periodEnd: null
117
117
  });
118
118
  updateSiteTier.run(tier || 'starter', wab_site_id, wab_user_id);
119
+
120
+ // ── License delivery email (best-effort, non-blocking) ──
121
+ try {
122
+ const { findUserById, findSiteById: getSite } = require('../models/db');
123
+ const user = findUserById.get(wab_user_id);
124
+ const site = getSite.get(wab_site_id);
125
+ if (user && site) {
126
+ const { sendEmail } = require('./email');
127
+ const baseUrl = process.env.BASE_URL || 'https://webagentbridge.com';
128
+ const amount = session.amount_total != null
129
+ ? `${(session.amount_total / 100).toFixed(2)} ${(session.currency || 'usd').toUpperCase()}`
130
+ : null;
131
+ Promise.resolve(sendEmail({
132
+ to: user.email,
133
+ template: 'license_delivery',
134
+ data: {
135
+ name: user.name,
136
+ tier: tier || 'starter',
137
+ siteDomain: site.domain,
138
+ licenseKey: site.license_key,
139
+ amount,
140
+ dashboardUrl: `${baseUrl}/dashboard`
141
+ },
142
+ userId: user.id
143
+ })).catch((e) => console.error('[stripe] license_delivery email failed:', e.message));
144
+ }
145
+ } catch (e) {
146
+ console.error('[stripe] license_delivery setup failed:', e.message);
147
+ }
119
148
  }
120
149
  break;
121
150
  }
@@ -187,6 +216,85 @@ function handleWebhookEvent(event) {
187
216
  }
188
217
  break;
189
218
  }
219
+
220
+ case 'charge.refunded': {
221
+ const charge = event.data.object;
222
+ try {
223
+ const userId =
224
+ (charge.metadata && charge.metadata.wab_user_id) ||
225
+ (charge.invoice && (() => {
226
+ // best-effort: look up subscription via the invoice's subscription id
227
+ try {
228
+ const inv = charge.invoice;
229
+ if (typeof inv === 'string') return null;
230
+ if (inv && inv.subscription) {
231
+ const sub = getStripeSubscriptionBySubId(inv.subscription);
232
+ return sub ? sub.user_id : null;
233
+ }
234
+ } catch { return null; }
235
+ return null;
236
+ })()) || null;
237
+
238
+ if (userId) {
239
+ savePayment({
240
+ userId,
241
+ stripePaymentId: `refund_${charge.id}`,
242
+ amount: -(charge.amount_refunded || charge.amount || 0),
243
+ currency: charge.currency || 'usd',
244
+ status: 'refunded',
245
+ description: `Refund: ${charge.id}`
246
+ });
247
+ }
248
+
249
+ // Downgrade any subscription tied to this charge (best-effort)
250
+ if (charge.invoice) {
251
+ try {
252
+ const invId = typeof charge.invoice === 'string' ? null : charge.invoice;
253
+ // Subscription id can be on the expanded invoice; we mark the
254
+ // user's subscriptions as refunded so admin tools can review.
255
+ if (invId && invId.subscription) {
256
+ updateStripeSubscription(invId.subscription, { status: 'cancelled' });
257
+ const sub = getStripeSubscriptionBySubId(invId.subscription);
258
+ if (sub) updateSiteTier.run('free', sub.site_id, sub.user_id);
259
+ }
260
+ } catch (e) {
261
+ console.error('[stripe] charge.refunded subscription update failed:', e.message);
262
+ }
263
+ }
264
+ console.warn(`[stripe] charge.refunded processed: charge=${charge.id} amount=${charge.amount_refunded}`);
265
+ } catch (e) {
266
+ console.error('[stripe] charge.refunded handler error:', e.message);
267
+ }
268
+ break;
269
+ }
270
+
271
+ case 'charge.dispute.created': {
272
+ const dispute = event.data.object;
273
+ try {
274
+ const userId = (dispute.metadata && dispute.metadata.wab_user_id) || null;
275
+ if (userId) {
276
+ savePayment({
277
+ userId,
278
+ stripePaymentId: `dispute_${dispute.id}`,
279
+ amount: -(dispute.amount || 0),
280
+ currency: dispute.currency || 'usd',
281
+ status: 'disputed',
282
+ description: `Chargeback/dispute: ${dispute.id} reason=${dispute.reason || 'unknown'}`
283
+ });
284
+ }
285
+ // Suspend any subscription on the disputed charge
286
+ try {
287
+ if (dispute.charge) {
288
+ // Without expanding the charge we cannot reliably find the sub,
289
+ // but admins are alerted via the audit log + payments row above.
290
+ }
291
+ } catch { /* noop */ }
292
+ console.warn(`[stripe] charge.dispute.created: dispute=${dispute.id} reason=${dispute.reason}`);
293
+ } catch (e) {
294
+ console.error('[stripe] charge.dispute.created handler error:', e.message);
295
+ }
296
+ break;
297
+ }
190
298
  }
191
299
  }
192
300
 
@@ -292,6 +292,14 @@ function transitionTransaction(txId, toStatus, patch = {}) {
292
292
  db.prepare("UPDATE atp_intents SET status='consumed', updated_at=? WHERE id=? AND status='authorized'")
293
293
  .run(nowIso(), tx.intent_id);
294
294
  }
295
+
296
+ // Platform commission (best-effort, never blocks the tx).
297
+ try {
298
+ const commissions = require('./commissions');
299
+ commissions.recordCommissionForTransaction(getTransaction(txId));
300
+ } catch (e) {
301
+ console.error('[atp] commission record failed (non-fatal):', e.message);
302
+ }
295
303
  }
296
304
  if (toStatus === 'compensated' && tx.status === 'settled') {
297
305
  db.prepare(`
@@ -300,6 +308,13 @@ function transitionTransaction(txId, toStatus, patch = {}) {
300
308
  updated_at = ?
301
309
  WHERE id = ?
302
310
  `).run(tx.amount_cents, nowIso(), tx.intent_id);
311
+
312
+ try {
313
+ const commissions = require('./commissions');
314
+ commissions.markCommissionRefunded(txId, 'tx_compensated');
315
+ } catch (e) {
316
+ console.error('[atp] commission refund mark failed (non-fatal):', e.message);
317
+ }
303
318
  }
304
319
 
305
320
  return getTransaction(txId);