| 1 | import { randomBytes, randomUUID } from "crypto"; |
| 2 | import { and, asc |
| 3 | import { ORPCError } |
| 4 | import { z } |
| 5 | import { db } |
| 6 | import { |
| 7 | billingCategories, |
| 8 | billingCouponRedemptions, |
| 9 | billingCoupons, |
| 10 | billingInvoiceItems, |
| 11 | billingInvoices, |
| 12 | billingPaymentGateways, |
| 13 | billingPlans, |
| 14 | billingPlanPrices, |
| 15 | billingProducts, |
| 16 | billingReferralCodes, |
| 17 | billingReferralRedemptions, |
| 18 | billingSubscriptions, |
| 19 | billingTransactions, |
| 20 | billingWallet, |
| 21 | billingWalletTransactions, |
| 22 | eggs, |
| 23 | nodeAllocations, |
| 24 | nodes, |
| 25 | serverVariables, |
| 26 | servers, |
| 27 | settings, |
| 28 | } from "@struxa/db"; |
| 29 | import { recordActivity } |
| 30 | import { getEffectiveAppUrl } |
| 31 | import { encrypt, decrypt |
| 32 | import { createWingsClient } |
| 33 | import { buildInvocation } |
| 34 | import { createStripeTopupSession, createSimPayTopupSession |
| 35 | import { adminProcedure, protectedProcedure |
| 36 | |
| 37 | const DURATION_DAYS: Record |
| 38 | "7day": 7, |
| 39 | "1month": 30, |
| 40 | "3months": 90, |
| 41 | "6months": 180, |
| 42 | "1year": 365, |
| 43 | }; |
| 44 | |
| 45 | |
| 46 | function slugify(s: |
| 47 | return s.toLowerCase |
| 48 | } |
| 49 | |
| 50 | const DURATIONS = [ |
| 51 | |
| 52 | type NodeCapacityEntry |
| 53 | let _capacityCache: { |
| 54 | |
| 55 | async function getNodeCapacityMap() |
| 56 | if (_capacityCache && |
| 57 | |
| 58 | const freeAllocs = |
| 59 | where: isNull(nodeAllocations |
| 60 | with: { node: true |
| 61 | }); |
| 62 | |
| 63 | const freeCountByNode = |
| 64 | for (const a |
| 65 | |
| 66 | const map = |
| 67 | for (const a |
| 68 | if (map.has |
| 69 | const node = |
| 70 | const [usage] |
| 71 | usedRam: sql<number |
| 72 | usedDisk: sql<number |
| 73 | }).from(servers |
| 74 | const maxRam = |
| 75 | const maxDisk = |
| 76 | map.set(a |
| 77 | remainingRamMB: maxRam - |
| 78 | remainingDiskMB: maxDisk - |
| 79 | freeAllocCount: freeCountByNode.get |
| 80 | }); |
| 81 | } |
| 82 | |
| 83 | // ponytail: process-local cache; resets on deploy. Fine for a 2-min soft stock check |
| 84 | _capacityCache = { data |
| 85 | return map; |
| 86 | } |
| 87 | |
| 88 | export function invalidateCapacityCache() |
| 89 | _capacityCache = null; |
| 90 | } |
| 91 | |
| 92 | const resourceLimitsSchema = z |
| 93 | cpu: z.number |
| 94 | ram: z.number |
| 95 | disk: z.number |
| 96 | backups: z.number |
| 97 | allocations: z.number |
| 98 | databases: z.number |
| 99 | eggs: z.array |
| 100 | nodes: z.array |
| 101 | }); |
| 102 | |
| 103 | export const billingRouter = |
| 104 | getConfig: protectedProcedure.handler |
| 105 | const rows = |
| 106 | const s = |
| 107 | return { |
| 108 | enabled: s.billing_enabled |
| 109 | referralEnabled: s.billing_referral_enabled |
| 110 | defaultCurrency: s.billing_default_currency |
| 111 | }; |
| 112 | }), |
| 113 | |
| 114 | listCategories: protectedProcedure.handler |
| 115 | const rows = |
| 116 | .select() |
| 117 | .from(billingCategories) |
| 118 | .where(eq(billingCategories |
| 119 | .orderBy(asc(billingCategories |
| 120 | return rows.map |
| 121 | id: r.id |
| 122 | name: r.name |
| 123 | slug: r.slug |
| 124 | description: r.description |
| 125 | icon: r.icon |
| 126 | bannerUrl: r.coverImage |
| 127 | })); |
| 128 | }), |
| 129 | |
| 130 | listProducts: protectedProcedure |
| 131 | .input(z.object |
| 132 | .handler(async ( |
| 133 | const [products, |
| 134 | db.query.billingProducts |
| 135 | where: input?.categoryId |
| 136 | ? and(eq( |
| 137 | : eq(billingProducts. |
| 138 | orderBy: [asc(billingProducts |
| 139 | with: { |
| 140 | plans: { |
| 141 | where: and(eq |
| 142 | with: { prices: { |
| 143 | }, |
| 144 | }, |
| 145 | }), |
| 146 | getNodeCapacityMap(), |
| 147 | ]); |
| 148 | |
| 149 | return products |
| 150 | .filter((p) |
| 151 | .map((product) |
| 152 | const plan = |
| 153 | const limits = |
| 154 | cpu?: number |
| 155 | backups?: number |
| 156 | } | null; |
| 157 | const allowedNodes = |
| 158 | const requiredRamMB = |
| 159 | const requiredDiskMB = |
| 160 | let soldOut = |
| 161 | for (const [nodeId |
| 162 | if (allowedNodes.length |
| 163 | if (cap.freeAllocCount |
| 164 | soldOut = false; |
| 165 | break; |
| 166 | } |
| 167 | } |
| 168 | return { |
| 169 | id: product.id |
| 170 | planId: plan.id |
| 171 | categoryId: product.categoryId |
| 172 | name: product.name |
| 173 | description: product.description |
| 174 | isFeatured: product.isFeatured |
| 175 | icon: product.icon |
| 176 | currency: plan.currency |
| 177 | soldOut, |
| 178 | resources: { |
| 179 | cpu: limits?.cpu |
| 180 | ram: limits?.ram |
| 181 | disk: limits?.disk |
| 182 | backups: limits?.backups |
| 183 | allocations: limits?.allocations |
| 184 | databases: limits?.databases |
| 185 | eggs: limits?.eggs |
| 186 | }, |
| 187 | prices: plan.prices |
| 188 | id: p.id |
| 189 | duration: p.duration |
| 190 | price: p.priceCents |
| 191 | })), |
| 192 | }; |
| 193 | }); |
| 194 | }), |
| 195 | |
| 196 | getWallet: protectedProcedure.handler |
| 197 | const row = |
| 198 | where: eq(billingWallet |
| 199 | }); |
| 200 | if (row) return |
| 201 | const currencyRow = |
| 202 | where: eq(settings |
| 203 | }); |
| 204 | return { balanceCents: |
| 205 | }), |
| 206 | |
| 207 | listWalletTransactions: protectedProcedure |
| 208 | .input(z.object |
| 209 | .handler(async ( |
| 210 | const rows = |
| 211 | where: eq(billingWalletTransactions |
| 212 | orderBy: [desc(billingWalletTransactions |
| 213 | limit: input?.limit |
| 214 | offset: input?.offset |
| 215 | }); |
| 216 | return rows.map |
| 217 | id: r.id |
| 218 | type: r.type |
| 219 | amountCents: r.amountCents |
| 220 | balanceAfterCents: r.balanceAfterCents |
| 221 | currency: r.currency |
| 222 | description: r.description |
| 223 | createdAt: r.createdAt |
| 224 | })); |
| 225 | }), |
| 226 | |
| 227 | listActiveGateways: protectedProcedure.handler |
| 228 | const rows = |
| 229 | where: eq(billingPaymentGateways |
| 230 | orderBy: [asc(billingPaymentGateways |
| 231 | columns: { id: true |
| 232 | }); |
| 233 | return rows; |
| 234 | }), |
| 235 | |
| 236 | createTopupSession: protectedProcedure |
| 237 | .input(z.object |
| 238 | gatewayId: z.string |
| 239 | amountCents: z.number |
| 240 | successUrl: z.string |
| 241 | cancelUrl: z.string |
| 242 | })) |
| 243 | .handler(async ( |
| 244 | const gateway = |
| 245 | where: and(eq |
| 246 | }); |
| 247 | if (!gateway) |
| 248 | |
| 249 | const raw = |
| 250 | publishableKey?: string |
| 251 | } | null ?? |
| 252 | |
| 253 | const wallet = |
| 254 | where: eq(billingWallet |
| 255 | }); |
| 256 | const currencyRow = |
| 257 | where: eq(settings |
| 258 | }); |
| 259 | const currency = |
| 260 | |
| 261 | if (gateway.provider |
| 262 | if (!raw.secretKey |
| 263 | const { url |
| 264 | { secretKey: decrypt( |
| 265 | { |
| 266 | userId: context.session |
| 267 | amountCents: input.amountCents |
| 268 | currency, |
| 269 | successUrl: input.successUrl |
| 270 | cancelUrl: input.cancelUrl |
| 271 | gatewayId: gateway.id |
| 272 | }, |
| 273 | ); |
| 274 | return { url |
| 275 | } |
| 276 | |
| 277 | if (gateway.provider |
| 278 | if (!raw.secretKey |
| 279 | if (!raw.serviceId |
| 280 | const { url |
| 281 | { apiPassword: decrypt( |
| 282 | { |
| 283 | userId: context.session |
| 284 | amountCents: input.amountCents |
| 285 | currency, |
| 286 | successUrl: input.successUrl |
| 287 | cancelUrl: input.cancelUrl |
| 288 | gatewayId: gateway.id |
| 289 | customerEmail: context.session |
| 290 | customerName: context.session |
| 291 | }, |
| 292 | ); |
| 293 | return { url |
| 294 | } |
| 295 | |
| 296 | if (gateway.provider |
| 297 | if (!raw.publishableKey |
| 298 | if (!raw.secretKey |
| 299 | const { url |
| 300 | { clientId: raw. |
| 301 | { |
| 302 | userId: context.session |
| 303 | amountCents: input.amountCents |
| 304 | currency, |
| 305 | successUrl: input.successUrl |
| 306 | cancelUrl: input.cancelUrl |
| 307 | gatewayId: gateway.id |
| 308 | }, |
| 309 | ); |
| 310 | return { url |
| 311 | } |
| 312 | |
| 313 | if (gateway.provider |
| 314 | if (!raw.publishableKey |
| 315 | if (!raw.serviceId |
| 316 | if (!raw.secretKey |
| 317 | if (!raw.webhookSecret |
| 318 | const appUrl = |
| 319 | if (!appUrl) |
| 320 | const { url |
| 321 | { |
| 322 | merchantId: raw.publishableKey |
| 323 | posId: raw.serviceId |
| 324 | apiKey: decrypt(raw |
| 325 | sandbox: raw.sandbox |
| 326 | }, |
| 327 | { |
| 328 | userId: context.session |
| 329 | amountCents: input.amountCents |
| 330 | currency, |
| 331 | successUrl: input.successUrl |
| 332 | cancelUrl: input.cancelUrl |
| 333 | statusUrl: new URL |
| 334 | gatewayId: gateway.id |
| 335 | customerEmail: context.session |
| 336 | }, |
| 337 | ); |
| 338 | return { url |
| 339 | } |
| 340 | |
| 341 | throw new Error( |
| 342 | }), |
| 343 | |
| 344 | adminListCategories: adminProcedure.handler |
| 345 | const rows = |
| 346 | return rows.map |
| 347 | id: r.id |
| 348 | name: r.name |
| 349 | slug: r.slug |
| 350 | description: r.description |
| 351 | isActive: r.isActive |
| 352 | sortOrder: r.sortOrder |
| 353 | icon: r.icon |
| 354 | bannerUrl: r.coverImage |
| 355 | })); |
| 356 | }), |
| 357 | |
| 358 | adminCreateCategory: adminProcedure |
| 359 | .input( |
| 360 | z.object({ |
| 361 | name: z.string |
| 362 | slug: z.string |
| 363 | description: z.string |
| 364 | isActive: z.boolean |
| 365 | sortOrder: z.number |
| 366 | icon: z.string |
| 367 | coverImage: z.string |
| 368 | }), |
| 369 | ) |
| 370 | .handler(async ( |
| 371 | const id = |
| 372 | const slug = |
| 373 | await db.insert |
| 374 | id, |
| 375 | name: input.name |
| 376 | slug, |
| 377 | description: input.description |
| 378 | isActive: input.isActive |
| 379 | sortOrder: input.sortOrder |
| 380 | icon: input.icon |
| 381 | coverImage: input.coverImage |
| 382 | }); |
| 383 | recordActivity({ eventType: |
| 384 | }), |
| 385 | |
| 386 | adminUpdateCategory: adminProcedure |
| 387 | .input( |
| 388 | z.object({ |
| 389 | id: z.string |
| 390 | name: z.string |
| 391 | slug: z.string |
| 392 | description: z.string |
| 393 | isActive: z.boolean |
| 394 | sortOrder: z.number |
| 395 | icon: z.string |
| 396 | coverImage: z.string |
| 397 | }), |
| 398 | ) |
| 399 | .handler(async ( |
| 400 | const { id, |
| 401 | await db.update |
| 402 | recordActivity({ eventType: |
| 403 | }), |
| 404 | |
| 405 | adminDeleteCategory: adminProcedure |
| 406 | .input(z.object |
| 407 | .handler(async ( |
| 408 | const products = |
| 409 | for (const product |
| 410 | await db.delete |
| 411 | await db.delete |
| 412 | } |
| 413 | await db.delete |
| 414 | recordActivity({ eventType: |
| 415 | }), |
| 416 | |
| 417 | adminListProducts: adminProcedure.handler |
| 418 | const products = |
| 419 | orderBy: asc(billingProducts |
| 420 | with: { |
| 421 | plans: { |
| 422 | with: { prices: true |
| 423 | }, |
| 424 | }, |
| 425 | }); |
| 426 | return products.map |
| 427 | const plan = |
| 428 | const limits = |
| 429 | cpu?: number |
| 430 | backups?: number |
| 431 | } | null; |
| 432 | return { |
| 433 | id: product.id |
| 434 | categoryId: product.categoryId |
| 435 | name: product.name |
| 436 | description: product.description |
| 437 | isFeatured: product.isFeatured |
| 438 | isActive: plan?.isActive |
| 439 | isPublic: plan?.isPublic |
| 440 | icon: product.icon |
| 441 | resources: { |
| 442 | cpu: limits?.cpu |
| 443 | ram: limits?.ram |
| 444 | disk: limits?.disk |
| 445 | backups: limits?.backups |
| 446 | allocations: limits?.allocations |
| 447 | databases: limits?.databases |
| 448 | eggs: limits?.eggs |
| 449 | nodes: limits?.nodes |
| 450 | }, |
| 451 | prices: (plan?.prices |
| 452 | id: p.id |
| 453 | duration: p.duration |
| 454 | price: p.priceCents |
| 455 | })), |
| 456 | }; |
| 457 | }); |
| 458 | }), |
| 459 | |
| 460 | adminCreateProduct: adminProcedure |
| 461 | .input( |
| 462 | z.object({ |
| 463 | categoryId: z.string |
| 464 | name: z.string |
| 465 | slug: z.string |
| 466 | description: z.string |
| 467 | isActive: z.boolean |
| 468 | isPublic: z.boolean |
| 469 | isFeatured: z.boolean |
| 470 | icon: z.string |
| 471 | resourceLimits: resourceLimitsSchema, |
| 472 | prices: z.array |
| 473 | z.object({ |
| 474 | duration: z.enum |
| 475 | priceCents: z.number |
| 476 | }), |
| 477 | ), |
| 478 | currency: z.string |
| 479 | }), |
| 480 | ) |
| 481 | .handler(async ( |
| 482 | const durations = |
| 483 | if (new Set |
| 484 | |
| 485 | const productId = |
| 486 | const planId = |
| 487 | const slug = |
| 488 | |
| 489 | const currencySettingRow = |
| 490 | const defaultCurrencyForPlan = |
| 491 | |
| 492 | await db.transaction |
| 493 | if (input.isFeatured |
| 494 | await tx.update |
| 495 | } |
| 496 | await tx.insert |
| 497 | id: productId, |
| 498 | categoryId: input.categoryId |
| 499 | name: input.name |
| 500 | slug, |
| 501 | description: input.description |
| 502 | isActive: input.isActive |
| 503 | isFeatured: input.isFeatured |
| 504 | icon: input.icon |
| 505 | sortOrder: 0, |
| 506 | }); |
| 507 | await tx.insert |
| 508 | id: planId, |
| 509 | productId, |
| 510 | name: input.name |
| 511 | description: input.description |
| 512 | currency: defaultCurrencyForPlan, |
| 513 | resourceLimits: input.resourceLimits |
| 514 | isActive: input.isActive |
| 515 | isPublic: input.isPublic |
| 516 | sortOrder: 0, |
| 517 | }); |
| 518 | if (input.prices |
| 519 | await tx.insert |
| 520 | input.prices.map |
| 521 | ); |
| 522 | } |
| 523 | }); |
| 524 | |
| 525 | recordActivity({ eventType: |
| 526 | return { id: |
| 527 | }), |
| 528 | |
| 529 | adminUpdateProduct: adminProcedure |
| 530 | .input( |
| 531 | z.object({ |
| 532 | id: z.string |
| 533 | categoryId: z.string |
| 534 | name: z.string |
| 535 | slug: z.string |
| 536 | description: z.string |
| 537 | isActive: z.boolean |
| 538 | isPublic: z.boolean |
| 539 | isFeatured: z.boolean |
| 540 | icon: z.string |
| 541 | resourceLimits: resourceLimitsSchema.optional |
| 542 | prices: z |
| 543 | .array( |
| 544 | z.object({ |
| 545 | duration: z.enum |
| 546 | priceCents: z.number |
| 547 | }), |
| 548 | ) |
| 549 | .optional(), |
| 550 | currency: z.string |
| 551 | }), |
| 552 | ) |
| 553 | .handler(async ( |
| 554 | if (input.isFeatured |
| 555 | const product = |
| 556 | const catId = |
| 557 | if (catId) { |
| 558 | await db.update |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | await db.update |
| 563 | ...(input.categoryId |
| 564 | ...(input.name |
| 565 | ...(input.slug |
| 566 | ...(input.description |
| 567 | ...(input.isActive |
| 568 | ...(input.isFeatured |
| 569 | ...(input.icon |
| 570 | }).where(eq |
| 571 | |
| 572 | const existingPlan = |
| 573 | where: eq(billingPlans |
| 574 | }); |
| 575 | |
| 576 | if (existingPlan) { |
| 577 | await db.update |
| 578 | ...(input.isActive |
| 579 | ...(input.isPublic |
| 580 | ...(input.name |
| 581 | ...(input.description |
| 582 | ...(input.currency |
| 583 | ...(input.resourceLimits |
| 584 | }).where(eq |
| 585 | |
| 586 | if (input.prices |
| 587 | const existingPrices = |
| 588 | const existingByDuration = |
| 589 | |
| 590 | for (const p |
| 591 | const existing = |
| 592 | if (existing) { |
| 593 | await db.update |
| 594 | } else { |
| 595 | await db.insert |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | const incomingDurations = |
| 600 | const toDelete = |
| 601 | if (toDelete.length |
| 602 | const referencedIds = |
| 603 | const safeToDelete = |
| 604 | if (safeToDelete.length |
| 605 | await db.delete |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | recordActivity({ eventType: |
| 612 | }), |
| 613 | |
| 614 | adminDeleteProduct: adminProcedure |
| 615 | .input(z.object |
| 616 | .handler(async ( |
| 617 | await db.delete |
| 618 | await db.delete |
| 619 | recordActivity({ eventType: |
| 620 | }), |
| 621 | |
| 622 | adminListGateways: adminProcedure.handler |
| 623 | const rows = |
| 624 | .select() |
| 625 | .from(billingPaymentGateways) |
| 626 | .orderBy(asc(billingPaymentGateways |
| 627 | return rows.map |
| 628 | const config = |
| 629 | return { |
| 630 | id: r.id |
| 631 | name: r.name |
| 632 | provider: r.provider |
| 633 | isActive: r.isActive |
| 634 | sortOrder: r.sortOrder |
| 635 | hasPublishableKey: !!config.publishableKey |
| 636 | hasSecretKey: !!config.secretKey |
| 637 | hasWebhookSecret: !!config.webhookSecret |
| 638 | sandbox: config.sandbox |
| 639 | }; |
| 640 | }); |
| 641 | }), |
| 642 | |
| 643 | adminCreateGateway: adminProcedure |
| 644 | .input( |
| 645 | z.object({ |
| 646 | name: z.string |
| 647 | provider: z.string |
| 648 | isActive: z.boolean |
| 649 | sortOrder: z.number |
| 650 | publishableKey: z.string |
| 651 | secretKey: z.string |
| 652 | webhookSecret: z.string |
| 653 | serviceId: z.string |
| 654 | sandbox: z.boolean |
| 655 | }), |
| 656 | ) |
| 657 | .handler(async ( |
| 658 | const id = |
| 659 | const config: |
| 660 | if (input.publishableKey |
| 661 | if (input.secretKey |
| 662 | if (input.webhookSecret |
| 663 | if (input.serviceId |
| 664 | if (input.sandbox |
| 665 | await db.insert |
| 666 | id, |
| 667 | name: input.name |
| 668 | provider: input.provider |
| 669 | config, |
| 670 | isActive: input.isActive |
| 671 | sortOrder: input.sortOrder |
| 672 | }); |
| 673 | recordActivity({ eventType: |
| 674 | return { id |
| 675 | }), |
| 676 | |
| 677 | adminUpdateGateway: adminProcedure |
| 678 | .input( |
| 679 | z.object({ |
| 680 | id: z.string |
| 681 | name: z.string |
| 682 | isActive: z.boolean |
| 683 | sortOrder: z.number |
| 684 | publishableKey: z.string |
| 685 | secretKey: z.string |
| 686 | webhookSecret: z.string |
| 687 | serviceId: z.string |
| 688 | sandbox: z.boolean |
| 689 | }), |
| 690 | ) |
| 691 | .handler(async ( |
| 692 | const existing = |
| 693 | where: eq(billingPaymentGateways |
| 694 | }); |
| 695 | if (!existing) |
| 696 | |
| 697 | const existingConfig = |
| 698 | const config: |
| 699 | if (input.publishableKey |
| 700 | if (input.secretKey |
| 701 | if (input.webhookSecret |
| 702 | if (input.serviceId |
| 703 | if (input.sandbox |
| 704 | |
| 705 | await db.update |
| 706 | ...(input.name |
| 707 | ...(input.isActive |
| 708 | ...(input.sortOrder |
| 709 | config, |
| 710 | }).where(eq |
| 711 | |
| 712 | recordActivity({ eventType: |
| 713 | }), |
| 714 | |
| 715 | adminDeleteGateway: adminProcedure |
| 716 | .input(z.object |
| 717 | .handler(async ( |
| 718 | await db.delete |
| 719 | recordActivity({ eventType: |
| 720 | }), |
| 721 | |
| 722 | getReferralCode: protectedProcedure.handler |
| 723 | const row = |
| 724 | where: eq(billingReferralCodes |
| 725 | }); |
| 726 | if (!row) |
| 727 | return { code: |
| 728 | }), |
| 729 | |
| 730 | generateReferralCode: protectedProcedure |
| 731 | .input(z.object |
| 732 | .handler(async ( |
| 733 | const existing = |
| 734 | where: eq(billingReferralCodes |
| 735 | }); |
| 736 | if (existing) return |
| 737 | |
| 738 | const code = |
| 739 | const taken = |
| 740 | where: eq(billingReferralCodes |
| 741 | }); |
| 742 | if (taken) throw |
| 743 | |
| 744 | await db.insert |
| 745 | id: randomUUID(), |
| 746 | userId: context.session |
| 747 | code, |
| 748 | }); |
| 749 | return { code, |
| 750 | }), |
| 751 | |
| 752 | updateReferralCode: protectedProcedure |
| 753 | .input(z.object |
| 754 | .handler(async ( |
| 755 | const existing = |
| 756 | where: eq(billingReferralCodes |
| 757 | }); |
| 758 | if (!existing) |
| 759 | |
| 760 | const code = |
| 761 | if (code === |
| 762 | |
| 763 | const taken = |
| 764 | where: eq(billingReferralCodes |
| 765 | }); |
| 766 | if (taken) throw |
| 767 | |
| 768 | await db.update |
| 769 | .set({ code |
| 770 | .where(eq(billingReferralCodes |
| 771 | return { code, |
| 772 | }), |
| 773 | |
| 774 | applyReferralCode: protectedProcedure |
| 775 | .input(z.object |
| 776 | .handler(async ( |
| 777 | const alreadyApplied = |
| 778 | where: eq(billingReferralRedemptions |
| 779 | }); |
| 780 | if (alreadyApplied) throw |
| 781 | |
| 782 | const referralCode = |
| 783 | where: and(eq |
| 784 | }); |
| 785 | if (!referralCode) |
| 786 | if (referralCode.userId |
| 787 | |
| 788 | await db.insert |
| 789 | id: randomUUID(), |
| 790 | codeId: referralCode.id |
| 791 | refereeId: context.session |
| 792 | referrerId: referralCode.userId |
| 793 | }); |
| 794 | await db.update |
| 795 | .set({ usageCount: |
| 796 | .where(eq(billingReferralCodes |
| 797 | |
| 798 | return { success: |
| 799 | }), |
| 800 | |
| 801 | listSubscriptions: protectedProcedure.handler |
| 802 | const rows = |
| 803 | where: and( |
| 804 | eq(billingSubscriptions.userId |
| 805 | ne(billingSubscriptions.status |
| 806 | ), |
| 807 | with: { |
| 808 | plan: { columns: { |
| 809 | price: { columns: { |
| 810 | }, |
| 811 | orderBy: [desc(billingSubscriptions |
| 812 | }); |
| 813 | return rows.map |
| 814 | id: r.id |
| 815 | status: r.status |
| 816 | planId: r.planId |
| 817 | planName: r.plan |
| 818 | duration: r.price |
| 819 | priceCents: r.price |
| 820 | currency: r.currency |
| 821 | currentPeriodStart: r.currentPeriodStart |
| 822 | currentPeriodEnd: r.currentPeriodEnd |
| 823 | cancelAtPeriodEnd: r.cancelAtPeriodEnd |
| 824 | })); |
| 825 | }), |
| 826 | |
| 827 | getActiveSubscription: protectedProcedure.handler |
| 828 | const row = |
| 829 | where: and( |
| 830 | eq(billingSubscriptions.userId |
| 831 | or( |
| 832 | eq(billingSubscriptions.status |
| 833 | eq(billingSubscriptions.status |
| 834 | ), |
| 835 | ), |
| 836 | with: { |
| 837 | plan: true, |
| 838 | price: { columns: { |
| 839 | }, |
| 840 | orderBy: [desc(billingSubscriptions |
| 841 | }); |
| 842 | if (!row) |
| 843 | const limits = |
| 844 | cpu?: number |
| 845 | backups?: number |
| 846 | } | null; |
| 847 | return { |
| 848 | id: row.id |
| 849 | status: row.status |
| 850 | planId: row.planId |
| 851 | planName: row.plan |
| 852 | duration: row.price |
| 853 | priceCents: row.price |
| 854 | currency: row.currency |
| 855 | currentPeriodStart: row.currentPeriodStart |
| 856 | currentPeriodEnd: row.currentPeriodEnd |
| 857 | cancelAtPeriodEnd: row.cancelAtPeriodEnd |
| 858 | resourceLimits: { |
| 859 | cpu: limits?.cpu |
| 860 | ram: limits?.ram |
| 861 | disk: limits?.disk |
| 862 | backups: limits?.backups |
| 863 | allocations: limits?.allocations |
| 864 | databases: limits?.databases |
| 865 | eggs: limits?.eggs |
| 866 | }, |
| 867 | }; |
| 868 | }), |
| 869 | |
| 870 | listPlanEggs: protectedProcedure |
| 871 | .input(z.object |
| 872 | .handler(async ( |
| 873 | if (!input.planId |
| 874 | const plan = |
| 875 | where: eq(billingPlans |
| 876 | columns: { resourceLimits: true |
| 877 | }); |
| 878 | const limits = |
| 879 | const eggIds = |
| 880 | if (eggIds.length |
| 881 | const rows = |
| 882 | where: inArray(eggs |
| 883 | columns: { id: true |
| 884 | with: { |
| 885 | variables: { |
| 886 | columns: { id: true |
| 887 | }, |
| 888 | }, |
| 889 | }); |
| 890 | return rows.map |
| 891 | let imagesMap: |
| 892 | try { imagesMap = |
| 893 | return { |
| 894 | id: row.id |
| 895 | name: row.name |
| 896 | dockerImages: Object.entries |
| 897 | variables: row.variables |
| 898 | }; |
| 899 | }); |
| 900 | }), |
| 901 | |
| 902 | purchasePlan: protectedProcedure |
| 903 | .input(z.object |
| 904 | priceId: z.string |
| 905 | eggId: z.string |
| 906 | serverName: z.string |
| 907 | couponCode: z.string |
| 908 | dockerImage: z.string |
| 909 | envVars: z.record |
| 910 | })) |
| 911 | .handler(async ( |
| 912 | const userId = |
| 913 | |
| 914 | const priceRow = |
| 915 | where: and(eq |
| 916 | with: { plan: true |
| 917 | }); |
| 918 | if (!priceRow?.plan |
| 919 | |
| 920 | const plan = |
| 921 | if (!plan.isActive |
| 922 | |
| 923 | const planLimits = |
| 924 | cpu?: number |
| 925 | backups?: number |
| 926 | } | null; |
| 927 | |
| 928 | const allowedEggs = |
| 929 | if (allowedEggs.length |
| 930 | throw new ORPCError( |
| 931 | } |
| 932 | |
| 933 | const eggRow = |
| 934 | where: eq(eggs |
| 935 | with: { variables: true |
| 936 | }); |
| 937 | if (!eggRow) |
| 938 | |
| 939 | const allowedNodeIds = |
| 940 | const requiredRam = |
| 941 | const requiredDisk = |
| 942 | |
| 943 | const freeAllocs = |
| 944 | where: and( |
| 945 | isNull(nodeAllocations.serverId |
| 946 | allowedNodeIds.length > 0 |
| 947 | ), |
| 948 | with: { node: true |
| 949 | }); |
| 950 | |
| 951 | // ponytail: soft capacity check - two concurrent buys can both pass; overallocation headroom absorbs the slop |
| 952 | const nodeUsageCache = |
| 953 | let alloc: |
| 954 | |
| 955 | for (const candidate |
| 956 | const nodeId = |
| 957 | if (!nodeUsageCache.has |
| 958 | const [usage] |
| 959 | usedRam: sql<number |
| 960 | usedDisk: sql<number |
| 961 | }).from(servers |
| 962 | nodeUsageCache.set(nodeId |
| 963 | } |
| 964 | const node = |
| 965 | const usage = |
| 966 | const maxRam = |
| 967 | const maxDisk = |
| 968 | if (usage.usedRam |
| 969 | alloc = candidate; |
| 970 | break; |
| 971 | } |
| 972 | } |
| 973 | |
| 974 | if (!alloc) |
| 975 | const hasAnyFree = |
| 976 | throw new ORPCError( |
| 977 | } |
| 978 | |
| 979 | const wallet = |
| 980 | where: eq(billingWallet |
| 981 | }); |
| 982 | const settingsRows = |
| 983 | const s = |
| 984 | const currency = |
| 985 | |
| 986 | let discountCents = |
| 987 | let couponRow: |
| 988 | if (input.couponCode |
| 989 | const now = |
| 990 | couponRow = await |
| 991 | where: and( |
| 992 | eq(billingCoupons.code |
| 993 | eq(billingCoupons.isActive |
| 994 | or(isNull(billingCoupons |
| 995 | ), |
| 996 | }) ?? null; |
| 997 | if ( |
| 998 | couponRow && |
| 999 | (!couponRow.redeemBy |
| 1000 | (couponRow.maxRedemptions === |
| 1001 | ) { |
| 1002 | const alreadyUsed = |
| 1003 | where: and( |
| 1004 | eq(billingCouponRedemptions.couponId |
| 1005 | eq(billingCouponRedemptions.userId |
| 1006 | ), |
| 1007 | }); |
| 1008 | if (!alreadyUsed) |
| 1009 | if (couponRow.discountType |
| 1010 | discountCents = Math. |
| 1011 | } else { |
| 1012 | discountCents = couponRow. |
| 1013 | } |
| 1014 | } |
| 1015 | } else { |
| 1016 | couponRow = null; |
| 1017 | } |
| 1018 | } |
| 1019 | |
| 1020 | const finalAmountCents = |
| 1021 | const durationDays = |
| 1022 | const now = |
| 1023 | const periodEnd = |
| 1024 | const invoicePrefix = |
| 1025 | const invoiceNumber = |
| 1026 | |
| 1027 | const subscriptionId = |
| 1028 | const invoiceId = |
| 1029 | const invoiceItemId = |
| 1030 | const walletTxId = |
| 1031 | const transactionId = |
| 1032 | const serverId = |
| 1033 | const serverUuid = |
| 1034 | const serverUuidShort = |
| 1035 | |
| 1036 | const resolveVar = |
| 1037 | v.userEditable && |
| 1038 | ? (input.envVars |
| 1039 | : (v.defaultValue |
| 1040 | |
| 1041 | const varMap: |
| 1042 | for (const v |
| 1043 | varMap[v.envVariable |
| 1044 | } |
| 1045 | const serverInvocation = |
| 1046 | let dockerImages: |
| 1047 | try { dockerImages = |
| 1048 | const availableImages = |
| 1049 | const serverImage = |
| 1050 | ? input.dockerImage |
| 1051 | : availableImages[0] |
| 1052 | |
| 1053 | if (finalAmountCents > |
| 1054 | throw new ORPCError( |
| 1055 | } |
| 1056 | |
| 1057 | await db.transaction |
| 1058 | let balanceAfter = |
| 1059 | |
| 1060 | if (finalAmountCents > |
| 1061 | const result = |
| 1062 | .update(billingWallet) |
| 1063 | .set({ balanceCents: |
| 1064 | .where(and( |
| 1065 | eq(billingWallet.userId |
| 1066 | gte(billingWallet.balanceCents |
| 1067 | )); |
| 1068 | if ((result as |
| 1069 | throw new ORPCError( |
| 1070 | } |
| 1071 | const refreshed = |
| 1072 | where: eq(billingWallet |
| 1073 | columns: { balanceCents: true |
| 1074 | }); |
| 1075 | balanceAfter = refreshed?. |
| 1076 | } |
| 1077 | |
| 1078 | await tx.insert |
| 1079 | id: subscriptionId, |
| 1080 | userId, |
| 1081 | planId: plan.id |
| 1082 | priceId: priceRow.id |
| 1083 | status: "active", |
| 1084 | currency, |
| 1085 | currentPeriodStart: now, |
| 1086 | currentPeriodEnd: periodEnd, |
| 1087 | cancelAtPeriodEnd: false, |
| 1088 | }); |
| 1089 | |
| 1090 | await tx.insert |
| 1091 | id: serverId, |
| 1092 | uuid: serverUuid, |
| 1093 | uuidShort: serverUuidShort, |
| 1094 | name: input.serverName |
| 1095 | userId, |
| 1096 | nodeId: alloc.nodeId |
| 1097 | eggId: input.eggId |
| 1098 | allocationId: alloc.id |
| 1099 | subscriptionId, |
| 1100 | memory: (planLimits?.ram |
| 1101 | disk: (planLimits?.disk |
| 1102 | cpu: (planLimits?.cpu |
| 1103 | swap: 0, |
| 1104 | io: 500, |
| 1105 | oomDisabled: false, |
| 1106 | image: serverImage, |
| 1107 | startup: eggRow.startup |
| 1108 | invocation: serverInvocation, |
| 1109 | status: "installing", |
| 1110 | }); |
| 1111 | |
| 1112 | if (eggRow.variables |
| 1113 | await tx.insert |
| 1114 | eggRow.variables.map |
| 1115 | id: randomUUID(), |
| 1116 | serverId, |
| 1117 | variableId: v.id |
| 1118 | variableValue: resolveVar(v |
| 1119 | })), |
| 1120 | ); |
| 1121 | } |
| 1122 | |
| 1123 | await tx.update |
| 1124 | |
| 1125 | await tx.insert |
| 1126 | id: invoiceId, |
| 1127 | userId, |
| 1128 | subscriptionId, |
| 1129 | invoiceNumber, |
| 1130 | status: "paid", |
| 1131 | currency, |
| 1132 | subtotalCents: priceRow.priceCents |
| 1133 | discountCents, |
| 1134 | totalCents: finalAmountCents, |
| 1135 | amountPaidCents: finalAmountCents, |
| 1136 | amountDueCents: 0, |
| 1137 | paidAt: now, |
| 1138 | }); |
| 1139 | |
| 1140 | await tx.insert |
| 1141 | id: invoiceItemId, |
| 1142 | invoiceId, |
| 1143 | description: `${plan. |
| 1144 | quantity: 1, |
| 1145 | unitAmountCents: priceRow.priceCents |
| 1146 | totalCents: priceRow.priceCents |
| 1147 | currency, |
| 1148 | periodStart: now, |
| 1149 | periodEnd, |
| 1150 | }); |
| 1151 | |
| 1152 | if (finalAmountCents > |
| 1153 | await tx.insert |
| 1154 | id: walletTxId, |
| 1155 | userId, |
| 1156 | invoiceId, |
| 1157 | amountCents: -finalAmountCents, |
| 1158 | balanceAfterCents: balanceAfter, |
| 1159 | currency, |
| 1160 | type: "charge", |
| 1161 | description: `${plan. |
| 1162 | }); |
| 1163 | |
| 1164 | await tx.insert |
| 1165 | id: transactionId, |
| 1166 | userId, |
| 1167 | invoiceId, |
| 1168 | type: "payment", |
| 1169 | status: "succeeded", |
| 1170 | amountCents: finalAmountCents, |
| 1171 | currency, |
| 1172 | description: `${plan. |
| 1173 | }); |
| 1174 | } |
| 1175 | |
| 1176 | if (couponRow && |
| 1177 | await tx.insert |
| 1178 | id: randomUUID(), |
| 1179 | couponId: couponRow.id |
| 1180 | userId, |
| 1181 | invoiceId, |
| 1182 | discountAmountCents: discountCents, |
| 1183 | currency, |
| 1184 | }); |
| 1185 | await tx |
| 1186 | .update(billingCoupons) |
| 1187 | .set({ timesRedeemed: |
| 1188 | .where(eq(billingCoupons |
| 1189 | } |
| 1190 | }); |
| 1191 | |
| 1192 | const wingsNode = |
| 1193 | const wingsClient = |
| 1194 | const environment: |
| 1195 | for (const v |
| 1196 | environment[v.envVariable |
| 1197 | } |
| 1198 | try { |
| 1199 | await wingsClient.createServer |
| 1200 | uuid: serverUuid, |
| 1201 | start_on_completion: true, |
| 1202 | environment, |
| 1203 | limits: { |
| 1204 | cpu: (planLimits?.cpu |
| 1205 | memory: (planLimits?.ram |
| 1206 | disk: (planLimits?.disk |
| 1207 | swap: 0, |
| 1208 | io: 500, |
| 1209 | threads: null, |
| 1210 | oom_disabled: false, |
| 1211 | }, |
| 1212 | container: { |
| 1213 | image: serverImage, |
| 1214 | oom_killer: true, |
| 1215 | }, |
| 1216 | }); |
| 1217 | } catch { |
| 1218 | // Wings provisioning failed; server stays "installing" - admin can reinstall |
| 1219 | } |
| 1220 | |
| 1221 | invalidateCapacityCache(); |
| 1222 | |
| 1223 | recordActivity({ |
| 1224 | eventType: "billing.plan.purchase", |
| 1225 | userId, |
| 1226 | ip: context.ip |
| 1227 | properties: { planId: plan |
| 1228 | }); |
| 1229 | |
| 1230 | return { subscriptionId, |
| 1231 | }), |
| 1232 | |
| 1233 | getServerSubscription: protectedProcedure |
| 1234 | .input(z.object |
| 1235 | .handler(async ( |
| 1236 | const server = |
| 1237 | where: eq(servers |
| 1238 | columns: { subscriptionId: true |
| 1239 | }); |
| 1240 | if (!server || |
| 1241 | if (!server.subscriptionId |
| 1242 | |
| 1243 | const sub = |
| 1244 | where: eq(billingSubscriptions |
| 1245 | with: { |
| 1246 | plan: { columns: { |
| 1247 | price: { columns: { |
| 1248 | }, |
| 1249 | }); |
| 1250 | if (!sub) |
| 1251 | |
| 1252 | const availablePrices = |
| 1253 | where: and( |
| 1254 | eq(billingPlanPrices.planId |
| 1255 | eq(billingPlanPrices.isActive |
| 1256 | ), |
| 1257 | columns: { id: true |
| 1258 | orderBy: [asc(billingPlanPrices |
| 1259 | }); |
| 1260 | |
| 1261 | return { |
| 1262 | subscriptionId: sub.id |
| 1263 | status: sub.status |
| 1264 | currentPeriodEnd: sub.currentPeriodEnd |
| 1265 | planName: sub.plan |
| 1266 | currency: sub.currency |
| 1267 | cancelAtPeriodEnd: sub.cancelAtPeriodEnd |
| 1268 | availablePrices: availablePrices.map |
| 1269 | id: p.id |
| 1270 | duration: p.duration |
| 1271 | priceCents: p.priceCents |
| 1272 | })), |
| 1273 | }; |
| 1274 | }), |
| 1275 | |
| 1276 | extendSubscription: protectedProcedure |
| 1277 | .input(z.object |
| 1278 | .handler(async ( |
| 1279 | const userId = |
| 1280 | |
| 1281 | const sub = |
| 1282 | where: and( |
| 1283 | eq(billingSubscriptions.id |
| 1284 | eq(billingSubscriptions.userId |
| 1285 | ), |
| 1286 | with: { plan: { |
| 1287 | }); |
| 1288 | if (!sub) |
| 1289 | if (!["active", |
| 1290 | throw new ORPCError( |
| 1291 | } |
| 1292 | |
| 1293 | const priceRow = |
| 1294 | where: and( |
| 1295 | eq(billingPlanPrices.id |
| 1296 | eq(billingPlanPrices.planId |
| 1297 | eq(billingPlanPrices.isActive |
| 1298 | ), |
| 1299 | }); |
| 1300 | if (!priceRow) |
| 1301 | |
| 1302 | const durationDays = |
| 1303 | const planName = |
| 1304 | const txDescription = |
| 1305 | const priceCents = |
| 1306 | const currency = |
| 1307 | |
| 1308 | const wallet = |
| 1309 | where: eq(billingWallet |
| 1310 | }); |
| 1311 | if ((wallet?.balanceCents |
| 1312 | throw new ORPCError( |
| 1313 | } |
| 1314 | |
| 1315 | const invoiceId = |
| 1316 | const invoiceItemId = |
| 1317 | const walletTxId = |
| 1318 | const transactionId = |
| 1319 | const now = |
| 1320 | |
| 1321 | const invoiceNumber = |
| 1322 | |
| 1323 | let newPeriodEnd: |
| 1324 | |
| 1325 | await db.transaction |
| 1326 | let balanceAfter = |
| 1327 | |
| 1328 | if (priceCents > |
| 1329 | const result = |
| 1330 | .update(billingWallet) |
| 1331 | .set({ balanceCents: |
| 1332 | .where(and( |
| 1333 | eq(billingWallet.userId |
| 1334 | gte(billingWallet.balanceCents |
| 1335 | )); |
| 1336 | if ((result as |
| 1337 | throw new ORPCError( |
| 1338 | } |
| 1339 | const refreshed = |
| 1340 | where: eq(billingWallet |
| 1341 | columns: { balanceCents: true |
| 1342 | }); |
| 1343 | balanceAfter = refreshed?. |
| 1344 | } |
| 1345 | |
| 1346 | await tx |
| 1347 | .update(billingSubscriptions) |
| 1348 | .set({ |
| 1349 | currentPeriodEnd: sql`DATE_ADD(COALESCE(${ |
| 1350 | cancelAtPeriodEnd: false, |
| 1351 | canceledAt: null, |
| 1352 | }) |
| 1353 | .where(eq(billingSubscriptions |
| 1354 | |
| 1355 | const updatedSub = |
| 1356 | where: eq(billingSubscriptions |
| 1357 | columns: { currentPeriodEnd: true |
| 1358 | }); |
| 1359 | newPeriodEnd = updatedSub?. |
| 1360 | |
| 1361 | await tx.insert |
| 1362 | id: invoiceId, |
| 1363 | userId, |
| 1364 | subscriptionId: sub.id |
| 1365 | invoiceNumber, |
| 1366 | status: "paid", |
| 1367 | currency, |
| 1368 | subtotalCents: priceCents, |
| 1369 | discountCents: 0, |
| 1370 | totalCents: priceCents, |
| 1371 | amountPaidCents: priceCents, |
| 1372 | amountDueCents: 0, |
| 1373 | paidAt: now, |
| 1374 | }); |
| 1375 | |
| 1376 | await tx.insert |
| 1377 | id: invoiceItemId, |
| 1378 | invoiceId, |
| 1379 | description: txDescription, |
| 1380 | quantity: 1, |
| 1381 | unitAmountCents: priceCents, |
| 1382 | totalCents: priceCents, |
| 1383 | currency, |
| 1384 | periodStart: sub.currentPeriodEnd |
| 1385 | periodEnd: newPeriodEnd, |
| 1386 | }); |
| 1387 | |
| 1388 | if (priceCents > |
| 1389 | await tx.insert |
| 1390 | id: walletTxId, |
| 1391 | userId, |
| 1392 | invoiceId, |
| 1393 | amountCents: -priceCents, |
| 1394 | balanceAfterCents: balanceAfter, |
| 1395 | currency, |
| 1396 | type: "charge", |
| 1397 | description: txDescription, |
| 1398 | }); |
| 1399 | |
| 1400 | await tx.insert |
| 1401 | id: transactionId, |
| 1402 | userId, |
| 1403 | invoiceId, |
| 1404 | type: "payment", |
| 1405 | status: "succeeded", |
| 1406 | amountCents: priceCents, |
| 1407 | currency, |
| 1408 | description: txDescription, |
| 1409 | }); |
| 1410 | } |
| 1411 | }); |
| 1412 | |
| 1413 | recordActivity({ |
| 1414 | eventType: "billing.subscription.extend", |
| 1415 | userId, |
| 1416 | ip: context.ip |
| 1417 | properties: { subscriptionId: sub |
| 1418 | }); |
| 1419 | |
| 1420 | return { newPeriodEnd |
| 1421 | }), |
| 1422 | |
| 1423 | cancelSubscription: protectedProcedure |
| 1424 | .input(z.object |
| 1425 | .handler(async ( |
| 1426 | const sub = |
| 1427 | where: and( |
| 1428 | eq(billingSubscriptions.id |
| 1429 | eq(billingSubscriptions.userId |
| 1430 | ), |
| 1431 | }); |
| 1432 | if (!sub) |
| 1433 | await db |
| 1434 | .update(billingSubscriptions) |
| 1435 | .set({ cancelAtPeriodEnd: |
| 1436 | .where(eq(billingSubscriptions |
| 1437 | recordActivity({ |
| 1438 | eventType: "billing.subscription.cancel", |
| 1439 | userId: context.session |
| 1440 | ip: context.ip |
| 1441 | properties: { subscriptionId: sub |
| 1442 | }); |
| 1443 | }), |
| 1444 | |
| 1445 | adminGetUserWallet: adminProcedure |
| 1446 | .input(z.object |
| 1447 | .handler(async ( |
| 1448 | const row = |
| 1449 | where: eq(billingWallet |
| 1450 | }); |
| 1451 | if (!row) |
| 1452 | const currencyRow = |
| 1453 | where: eq(settings |
| 1454 | }); |
| 1455 | return { balanceCents: |
| 1456 | } |
| 1457 | return { balanceCents: |
| 1458 | }), |
| 1459 | |
| 1460 | adminListUserSubscriptions: adminProcedure |
| 1461 | .input(z.object |
| 1462 | .handler(async ( |
| 1463 | const rows = |
| 1464 | where: eq(billingSubscriptions |
| 1465 | orderBy: [desc(billingSubscriptions |
| 1466 | with: { |
| 1467 | plan: { with: { |
| 1468 | price: { columns: { |
| 1469 | }, |
| 1470 | }); |
| 1471 | return rows.map |
| 1472 | id: r.id |
| 1473 | status: r.status |
| 1474 | planName: r.plan |
| 1475 | productName: r.plan |
| 1476 | priceCents: r.price |
| 1477 | duration: r.price |
| 1478 | currency: r.currency |
| 1479 | currentPeriodStart: r.currentPeriodStart |
| 1480 | currentPeriodEnd: r.currentPeriodEnd |
| 1481 | cancelAtPeriodEnd: r.cancelAtPeriodEnd |
| 1482 | canceledAt: r.canceledAt |
| 1483 | createdAt: r.createdAt |
| 1484 | })); |
| 1485 | }), |
| 1486 | |
| 1487 | adminListUserWalletTransactions: adminProcedure |
| 1488 | .input(z.object |
| 1489 | userId: z.string |
| 1490 | limit: z.number |
| 1491 | offset: z.number |
| 1492 | })) |
| 1493 | .handler(async ( |
| 1494 | const rows = |
| 1495 | where: eq(billingWalletTransactions |
| 1496 | orderBy: [desc(billingWalletTransactions |
| 1497 | limit: input.limit |
| 1498 | offset: input.offset |
| 1499 | }); |
| 1500 | return rows.map |
| 1501 | id: r.id |
| 1502 | type: r.type |
| 1503 | amountCents: r.amountCents |
| 1504 | balanceAfterCents: r.balanceAfterCents |
| 1505 | currency: r.currency |
| 1506 | description: r.description |
| 1507 | createdAt: r.createdAt |
| 1508 | })); |
| 1509 | }), |
| 1510 | |
| 1511 | adminAdjustUserBalance: adminProcedure |
| 1512 | .input(z.object |
| 1513 | userId: z.string |
| 1514 | amountCents: z.number |
| 1515 | description: z.string |
| 1516 | })) |
| 1517 | .handler(async ( |
| 1518 | const settingsRows = |
| 1519 | const s = |
| 1520 | const defaultCurrency = |
| 1521 | |
| 1522 | let newBalanceCents = |
| 1523 | await db.transaction |
| 1524 | let wallet = |
| 1525 | where: eq(billingWallet |
| 1526 | }); |
| 1527 | if (!wallet) |
| 1528 | const walletId = |
| 1529 | await tx.insert |
| 1530 | id: walletId, |
| 1531 | userId: input.userId |
| 1532 | balanceCents: 0, |
| 1533 | currency: defaultCurrency, |
| 1534 | }); |
| 1535 | wallet = await |
| 1536 | where: eq(billingWallet |
| 1537 | }); |
| 1538 | } |
| 1539 | await tx |
| 1540 | .update(billingWallet) |
| 1541 | .set({ balanceCents: |
| 1542 | .where(eq(billingWallet |
| 1543 | const refreshed = |
| 1544 | where: eq(billingWallet |
| 1545 | columns: { balanceCents: true |
| 1546 | }); |
| 1547 | const balanceAfter = |
| 1548 | await tx.insert |
| 1549 | id: randomUUID(), |
| 1550 | userId: input.userId |
| 1551 | amountCents: input.amountCents |
| 1552 | balanceAfterCents: balanceAfter, |
| 1553 | currency: wallet!.currency |
| 1554 | type: "adjustment", |
| 1555 | description: input.description |
| 1556 | }); |
| 1557 | newBalanceCents = balanceAfter; |
| 1558 | }); |
| 1559 | |
| 1560 | recordActivity({ |
| 1561 | eventType: "admin:billing.wallet.adjust", |
| 1562 | userId: context.session |
| 1563 | ip: context.ip |
| 1564 | properties: { targetUserId: input |
| 1565 | }); |
| 1566 | |
| 1567 | return { newBalanceCents |
| 1568 | }), |
| 1569 | }; |