@windrun-huaiin/backend-core 10.0.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.
Files changed (198) hide show
  1. package/LICENSE +21 -0
  2. package/dist/app/api/stripe/checkout/route.d.ts +19 -0
  3. package/dist/app/api/stripe/checkout/route.d.ts.map +1 -0
  4. package/dist/app/api/stripe/checkout/route.js +120 -0
  5. package/dist/app/api/stripe/checkout/route.mjs +118 -0
  6. package/dist/app/api/stripe/customer-portal/route.d.ts +11 -0
  7. package/dist/app/api/stripe/customer-portal/route.d.ts.map +1 -0
  8. package/dist/app/api/stripe/customer-portal/route.js +73 -0
  9. package/dist/app/api/stripe/customer-portal/route.mjs +71 -0
  10. package/dist/app/api/user/anonymous/init/route.d.ts +7 -0
  11. package/dist/app/api/user/anonymous/init/route.d.ts.map +1 -0
  12. package/dist/app/api/user/anonymous/init/route.js +210 -0
  13. package/dist/app/api/user/anonymous/init/route.mjs +208 -0
  14. package/dist/app/api/webhook/clerk/user/route.d.ts +7 -0
  15. package/dist/app/api/webhook/clerk/user/route.d.ts.map +1 -0
  16. package/dist/app/api/webhook/clerk/user/route.js +202 -0
  17. package/dist/app/api/webhook/clerk/user/route.mjs +200 -0
  18. package/dist/app/api/webhook/stripe/route.d.ts +8 -0
  19. package/dist/app/api/webhook/stripe/route.d.ts.map +1 -0
  20. package/dist/app/api/webhook/stripe/route.js +70 -0
  21. package/dist/app/api/webhook/stripe/route.mjs +67 -0
  22. package/dist/index.d.ts +7 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +83 -0
  25. package/dist/index.mjs +18 -0
  26. package/dist/lib/auth-utils.d.ts +46 -0
  27. package/dist/lib/auth-utils.d.ts.map +1 -0
  28. package/dist/lib/auth-utils.js +107 -0
  29. package/dist/lib/auth-utils.mjs +102 -0
  30. package/dist/lib/credit-init.d.ts +8 -0
  31. package/dist/lib/credit-init.d.ts.map +1 -0
  32. package/dist/lib/credit-init.js +16 -0
  33. package/dist/lib/credit-init.mjs +10 -0
  34. package/dist/lib/index.d.ts +5 -0
  35. package/dist/lib/index.d.ts.map +1 -0
  36. package/dist/lib/index.js +31 -0
  37. package/dist/lib/index.mjs +4 -0
  38. package/dist/lib/money-price-config.d.ts +51 -0
  39. package/dist/lib/money-price-config.d.ts.map +1 -0
  40. package/dist/lib/money-price-config.js +156 -0
  41. package/dist/lib/money-price-config.mjs +151 -0
  42. package/dist/lib/stripe-config.d.ts +31 -0
  43. package/dist/lib/stripe-config.d.ts.map +1 -0
  44. package/dist/lib/stripe-config.js +278 -0
  45. package/dist/lib/stripe-config.mjs +268 -0
  46. package/dist/node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.js +48 -0
  47. package/dist/node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.mjs +45 -0
  48. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/errors.js +54 -0
  49. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/errors.mjs +51 -0
  50. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/iso.js +44 -0
  51. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/iso.mjs +35 -0
  52. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/parse.js +31 -0
  53. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/parse.mjs +18 -0
  54. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/schemas.js +587 -0
  55. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/classic/schemas.mjs +527 -0
  56. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/api.js +447 -0
  57. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/api.mjs +399 -0
  58. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/checks.js +245 -0
  59. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/checks.mjs +232 -0
  60. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/core.js +68 -0
  61. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/core.mjs +62 -0
  62. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/doc.js +39 -0
  63. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/doc.mjs +37 -0
  64. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/errors.js +80 -0
  65. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/errors.mjs +75 -0
  66. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/parse.js +101 -0
  67. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/parse.mjs +86 -0
  68. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/regexes.js +102 -0
  69. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/regexes.mjs +76 -0
  70. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/registries.js +56 -0
  71. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/registries.mjs +52 -0
  72. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/schemas.js +1205 -0
  73. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/schemas.mjs +1157 -0
  74. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/util.js +407 -0
  75. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/util.mjs +374 -0
  76. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/versions.js +9 -0
  77. package/dist/node_modules/.pnpm/zod@4.1.12/node_modules/zod/v4/core/versions.mjs +7 -0
  78. package/dist/prisma/client.d.ts +2 -0
  79. package/dist/prisma/client.d.ts.map +1 -0
  80. package/dist/prisma/client.js +12 -0
  81. package/dist/prisma/client.mjs +1 -0
  82. package/dist/prisma/index.d.ts +4 -0
  83. package/dist/prisma/index.d.ts.map +1 -0
  84. package/dist/prisma/index.js +10 -0
  85. package/dist/prisma/index.mjs +2 -0
  86. package/dist/prisma/prisma-transaction-util.d.ts +3 -0
  87. package/dist/prisma/prisma-transaction-util.d.ts.map +1 -0
  88. package/dist/prisma/prisma-transaction-util.js +29 -0
  89. package/dist/prisma/prisma-transaction-util.mjs +27 -0
  90. package/dist/prisma/prisma.d.ts +4 -0
  91. package/dist/prisma/prisma.d.ts.map +1 -0
  92. package/dist/prisma/prisma.js +109 -0
  93. package/dist/prisma/prisma.mjs +106 -0
  94. package/dist/services/aggregate/billing.aggregate.service.d.ts +83 -0
  95. package/dist/services/aggregate/billing.aggregate.service.d.ts.map +1 -0
  96. package/dist/services/aggregate/billing.aggregate.service.js +308 -0
  97. package/dist/services/aggregate/billing.aggregate.service.mjs +306 -0
  98. package/dist/services/aggregate/index.d.ts +3 -0
  99. package/dist/services/aggregate/index.d.ts.map +1 -0
  100. package/dist/services/aggregate/index.js +9 -0
  101. package/dist/services/aggregate/index.mjs +2 -0
  102. package/dist/services/aggregate/user.aggregate.service.d.ts +34 -0
  103. package/dist/services/aggregate/user.aggregate.service.d.ts.map +1 -0
  104. package/dist/services/aggregate/user.aggregate.service.js +136 -0
  105. package/dist/services/aggregate/user.aggregate.service.mjs +133 -0
  106. package/dist/services/context/index.d.ts +2 -0
  107. package/dist/services/context/index.d.ts.map +1 -0
  108. package/dist/services/context/index.js +13 -0
  109. package/dist/services/context/index.mjs +1 -0
  110. package/dist/services/context/user-context-service.d.ts +30 -0
  111. package/dist/services/context/user-context-service.d.ts.map +1 -0
  112. package/dist/services/context/user-context-service.js +170 -0
  113. package/dist/services/context/user-context-service.mjs +162 -0
  114. package/dist/services/database/apilog.service.d.ts +39 -0
  115. package/dist/services/database/apilog.service.d.ts.map +1 -0
  116. package/dist/services/database/apilog.service.js +174 -0
  117. package/dist/services/database/apilog.service.mjs +170 -0
  118. package/dist/services/database/constants.d.ts +73 -0
  119. package/dist/services/database/constants.d.ts.map +1 -0
  120. package/dist/services/database/constants.js +135 -0
  121. package/dist/services/database/constants.mjs +117 -0
  122. package/dist/services/database/credit.service.d.ts +107 -0
  123. package/dist/services/database/credit.service.d.ts.map +1 -0
  124. package/dist/services/database/credit.service.js +515 -0
  125. package/dist/services/database/credit.service.mjs +512 -0
  126. package/dist/services/database/creditAuditLog.service.d.ts +73 -0
  127. package/dist/services/database/creditAuditLog.service.d.ts.map +1 -0
  128. package/dist/services/database/creditAuditLog.service.js +305 -0
  129. package/dist/services/database/creditAuditLog.service.mjs +302 -0
  130. package/dist/services/database/index.d.ts +10 -0
  131. package/dist/services/database/index.d.ts.map +1 -0
  132. package/dist/services/database/index.js +38 -0
  133. package/dist/services/database/index.mjs +8 -0
  134. package/dist/services/database/prisma-model-type.d.ts +3 -0
  135. package/dist/services/database/prisma-model-type.d.ts.map +1 -0
  136. package/dist/services/database/subscription.service.d.ts +48 -0
  137. package/dist/services/database/subscription.service.d.ts.map +1 -0
  138. package/dist/services/database/subscription.service.js +267 -0
  139. package/dist/services/database/subscription.service.mjs +264 -0
  140. package/dist/services/database/transaction.service.d.ts +92 -0
  141. package/dist/services/database/transaction.service.d.ts.map +1 -0
  142. package/dist/services/database/transaction.service.js +326 -0
  143. package/dist/services/database/transaction.service.mjs +323 -0
  144. package/dist/services/database/user.service.d.ts +45 -0
  145. package/dist/services/database/user.service.d.ts.map +1 -0
  146. package/dist/services/database/user.service.js +180 -0
  147. package/dist/services/database/user.service.mjs +177 -0
  148. package/dist/services/database/userBackup.service.d.ts +45 -0
  149. package/dist/services/database/userBackup.service.d.ts.map +1 -0
  150. package/dist/services/database/userBackup.service.js +249 -0
  151. package/dist/services/database/userBackup.service.mjs +246 -0
  152. package/dist/services/stripe/index.d.ts +2 -0
  153. package/dist/services/stripe/index.d.ts.map +1 -0
  154. package/dist/services/stripe/index.js +7 -0
  155. package/dist/services/stripe/index.mjs +1 -0
  156. package/dist/services/stripe/webhook-handler.d.ts +6 -0
  157. package/dist/services/stripe/webhook-handler.d.ts.map +1 -0
  158. package/dist/services/stripe/webhook-handler.js +537 -0
  159. package/dist/services/stripe/webhook-handler.mjs +535 -0
  160. package/migrations/create.sql +176 -0
  161. package/migrations/db.init.sql +13 -0
  162. package/migrations/init-schema.sql +19 -0
  163. package/migrations/purge.sql +27 -0
  164. package/migrations/test-check.sql +167 -0
  165. package/package.json +123 -0
  166. package/prisma/schema.prisma +191 -0
  167. package/src/app/api/stripe/checkout/route.ts +145 -0
  168. package/src/app/api/stripe/customer-portal/route.ts +83 -0
  169. package/src/app/api/user/anonymous/init/route.ts +284 -0
  170. package/src/app/api/webhook/clerk/user/route.ts +249 -0
  171. package/src/app/api/webhook/stripe/route.ts +93 -0
  172. package/src/index.ts +6 -0
  173. package/src/lib/auth-utils.ts +101 -0
  174. package/src/lib/credit-init.ts +9 -0
  175. package/src/lib/index.ts +4 -0
  176. package/src/lib/money-price-config.ts +168 -0
  177. package/src/lib/stripe-config.ts +333 -0
  178. package/src/prisma/client.ts +2 -0
  179. package/src/prisma/index.ts +3 -0
  180. package/src/prisma/prisma-transaction-util.ts +24 -0
  181. package/src/prisma/prisma.ts +122 -0
  182. package/src/services/aggregate/billing.aggregate.service.ts +498 -0
  183. package/src/services/aggregate/index.ts +2 -0
  184. package/src/services/aggregate/user.aggregate.service.ts +168 -0
  185. package/src/services/context/index.ts +1 -0
  186. package/src/services/context/user-context-service.ts +200 -0
  187. package/src/services/database/apilog.service.ts +185 -0
  188. package/src/services/database/constants.ts +148 -0
  189. package/src/services/database/credit.service.ts +747 -0
  190. package/src/services/database/creditAuditLog.service.ts +402 -0
  191. package/src/services/database/index.ts +41 -0
  192. package/src/services/database/prisma-model-type.ts +13 -0
  193. package/src/services/database/subscription.service.ts +319 -0
  194. package/src/services/database/transaction.service.ts +447 -0
  195. package/src/services/database/user.service.ts +218 -0
  196. package/src/services/database/userBackup.service.ts +290 -0
  197. package/src/services/stripe/index.ts +1 -0
  198. package/src/services/stripe/webhook-handler.ts +648 -0
@@ -0,0 +1,305 @@
1
+ 'use strict';
2
+
3
+ var tslib_es6 = require('../../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.js');
4
+ var client = require('@prisma/client');
5
+ var constants = require('./constants.js');
6
+ var prisma = require('../../prisma/prisma.js');
7
+
8
+ /* eslint-disable @typescript-eslint/no-explicit-any */
9
+ class CreditAuditLogService {
10
+ // Record Credit Audit
11
+ recordAuditLog(data, tx) {
12
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
13
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
14
+ return yield client.creditAuditLog.create({
15
+ data: {
16
+ userId: data.userId,
17
+ feature: data.feature,
18
+ operationReferId: data.operationReferId,
19
+ creditType: data.creditType,
20
+ operationType: data.operationType,
21
+ creditsChange: data.creditsChange,
22
+ },
23
+ });
24
+ });
25
+ }
26
+ // Record Credit Operation (alias for recordUsage)
27
+ recordCreditOperation(data, tx) {
28
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
29
+ return this.recordAuditLog(data, tx);
30
+ });
31
+ }
32
+ // Batch Record Credit Audit
33
+ recordBatchAudit(auditLogs, tx) {
34
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
35
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
36
+ const result = yield client.creditAuditLog.createMany({
37
+ data: auditLogs,
38
+ });
39
+ return result.count;
40
+ });
41
+ }
42
+ // Get User Credit Audit History
43
+ getUserCreditAuditHistory(userId, params, tx) {
44
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
45
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
46
+ const where = { userId, deleted: 0 };
47
+ if (params === null || params === void 0 ? void 0 : params.creditType) {
48
+ where.creditType = params.creditType;
49
+ }
50
+ if (params === null || params === void 0 ? void 0 : params.operationType) {
51
+ where.operationType = params.operationType;
52
+ }
53
+ if (params === null || params === void 0 ? void 0 : params.feature) {
54
+ where.feature = params.feature;
55
+ }
56
+ if ((params === null || params === void 0 ? void 0 : params.startDate) || (params === null || params === void 0 ? void 0 : params.endDate)) {
57
+ where.createdAt = {};
58
+ if (params.startDate)
59
+ where.createdAt.gte = params.startDate;
60
+ if (params.endDate)
61
+ where.createdAt.lte = params.endDate;
62
+ }
63
+ const [creditAudit, total] = yield Promise.all([
64
+ client.creditAuditLog.findMany({
65
+ where,
66
+ skip: (params === null || params === void 0 ? void 0 : params.skip) || 0,
67
+ take: (params === null || params === void 0 ? void 0 : params.take) || 20,
68
+ orderBy: (params === null || params === void 0 ? void 0 : params.orderBy) || { createdAt: 'desc' },
69
+ }),
70
+ client.creditAuditLog.count({ where }),
71
+ ]);
72
+ return { creditAudit, total };
73
+ });
74
+ }
75
+ // Get Credit Audit Record by operationReferId
76
+ getCreditAuditList(operationReferId, tx) {
77
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
78
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
79
+ return yield client.creditAuditLog.findMany({
80
+ where: { operationReferId, deleted: 0 },
81
+ orderBy: { createdAt: 'desc' },
82
+ });
83
+ });
84
+ }
85
+ // Get User Credit Audit Statistics
86
+ getUserCreditAuditStats(userId, startDate, endDate, tx) {
87
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
88
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
89
+ const where = { userId, deleted: 0 };
90
+ if (startDate || endDate) {
91
+ where.createdAt = {};
92
+ if (startDate)
93
+ where.createdAt.gte = startDate;
94
+ if (endDate)
95
+ where.createdAt.lte = endDate;
96
+ }
97
+ // Get all creditAudit records
98
+ const allUsage = yield client.creditAuditLog.findMany({
99
+ where,
100
+ select: {
101
+ creditType: true,
102
+ operationType: true,
103
+ creditsChange: true,
104
+ feature: true,
105
+ },
106
+ });
107
+ // Calculate statistics
108
+ const stats = {
109
+ totalConsumed: 0,
110
+ totalRecharged: 0,
111
+ freeConsumed: 0,
112
+ paidConsumed: 0,
113
+ freeRecharged: 0,
114
+ paidRecharged: 0,
115
+ featureUsage: [],
116
+ };
117
+ // Calculate creditAudit statistics by feature
118
+ const featureMap = new Map();
119
+ allUsage.forEach((creditAudit) => {
120
+ if (creditAudit.operationType === constants.OperationType.CONSUME) {
121
+ stats.totalConsumed += creditAudit.creditsChange;
122
+ if (creditAudit.creditType === constants.CreditType.FREE) {
123
+ stats.freeConsumed += creditAudit.creditsChange;
124
+ }
125
+ else {
126
+ stats.paidConsumed += creditAudit.creditsChange;
127
+ }
128
+ if (creditAudit.feature) {
129
+ featureMap.set(creditAudit.feature, (featureMap.get(creditAudit.feature) || 0) + creditAudit.creditsChange);
130
+ }
131
+ }
132
+ else if (creditAudit.operationType === constants.OperationType.RECHARGE) {
133
+ stats.totalRecharged += creditAudit.creditsChange;
134
+ if (creditAudit.creditType === constants.CreditType.FREE) {
135
+ stats.freeRecharged += creditAudit.creditsChange;
136
+ }
137
+ else {
138
+ stats.paidRecharged += creditAudit.creditsChange;
139
+ }
140
+ }
141
+ });
142
+ // Convert feature creditAudit statistics to array
143
+ stats.featureUsage = Array.from(featureMap.entries())
144
+ .map(([feature, credits]) => ({ feature, credits }))
145
+ .sort((a, b) => b.credits - a.credits);
146
+ return stats;
147
+ });
148
+ }
149
+ // Get Popular Features
150
+ getPopularFeatures() {
151
+ return tslib_es6.__awaiter(this, arguments, void 0, function* (limit = 10, startDate, endDate, tx) {
152
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
153
+ const where = {
154
+ operationType: constants.OperationType.CONSUME,
155
+ feature: { not: null },
156
+ deleted: 0,
157
+ };
158
+ if (startDate || endDate) {
159
+ where.createdAt = {};
160
+ if (startDate)
161
+ where.createdAt.gte = startDate;
162
+ if (endDate)
163
+ where.createdAt.lte = endDate;
164
+ }
165
+ const result = yield client.creditAuditLog.groupBy({
166
+ by: ['feature'],
167
+ where,
168
+ _sum: {
169
+ creditsChange: true,
170
+ },
171
+ _count: true,
172
+ orderBy: {
173
+ _sum: {
174
+ creditsChange: 'desc',
175
+ },
176
+ },
177
+ take: limit,
178
+ });
179
+ return result.map((item) => ({
180
+ feature: item.feature,
181
+ totalCredits: item._sum.creditsChange || 0,
182
+ usageCount: item._count,
183
+ }));
184
+ });
185
+ }
186
+ // Get Daily Credit Usage Trend
187
+ getDailyUsageTrend() {
188
+ return tslib_es6.__awaiter(this, arguments, void 0, function* (days = 30, userId, tx) {
189
+ const startDate = new Date();
190
+ startDate.setDate(startDate.getDate() - days);
191
+ const client$1 = prisma.checkAndFallbackWithNonTCClient(tx);
192
+ const userFilter = userId ? client.Prisma.sql `AND user_id = ${userId}` : client.Prisma.sql ``;
193
+ const result = yield client$1.$queryRaw `
194
+ SELECT
195
+ DATE(created_at) as date,
196
+ SUM(CASE WHEN operation_type = 'consume' THEN credits_used ELSE 0 END) as consumed,
197
+ SUM(CASE WHEN operation_type = 'recharge' THEN credits_used ELSE 0 END) as recharged,
198
+ SUM(CASE WHEN credit_type = 'free' AND operation_type = 'consume'
199
+ THEN credits_used ELSE 0 END) as free_consumed,
200
+ SUM(CASE WHEN credit_type = 'paid' AND operation_type = 'consume'
201
+ THEN credits_used ELSE 0 END) as paid_consumed,
202
+ COUNT(DISTINCT user_id) as unique_users
203
+ FROM credit_usage
204
+ WHERE created_at >= ${startDate}
205
+ AND deleted = 0
206
+ ${userFilter}
207
+ GROUP BY DATE(created_at)
208
+ ORDER BY date DESC
209
+ `;
210
+ return result;
211
+ });
212
+ }
213
+ // Get Recent Credit Usage Operations
214
+ getRecentOperations(userId_1) {
215
+ return tslib_es6.__awaiter(this, arguments, void 0, function* (userId, limit = 10, tx) {
216
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
217
+ return yield client.creditAuditLog.findMany({
218
+ where: { userId, deleted: 0 },
219
+ orderBy: { createdAt: 'desc' },
220
+ take: limit,
221
+ });
222
+ });
223
+ }
224
+ // Soft Delete Old Credit Usage Records
225
+ deleteOldRecords() {
226
+ return tslib_es6.__awaiter(this, arguments, void 0, function* (daysToKeep = 365, tx) {
227
+ const cutoffDate = new Date();
228
+ cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
229
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
230
+ const result = yield client.creditAuditLog.updateMany({
231
+ where: {
232
+ createdAt: {
233
+ lt: cutoffDate,
234
+ },
235
+ deleted: 0,
236
+ },
237
+ data: {
238
+ deleted: 1,
239
+ },
240
+ });
241
+ return result.count;
242
+ });
243
+ }
244
+ // Get System-wide Credit Usage Statistics
245
+ getSystemStats(tx) {
246
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
247
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
248
+ const [totalUsers, totalOperations, consumeStats, rechargeStats,] = yield Promise.all([
249
+ client.creditAuditLog.groupBy({
250
+ by: ['userId'],
251
+ where: { deleted: 0 },
252
+ }).then((result) => result.length),
253
+ client.creditAuditLog.count({ where: { deleted: 0 } }),
254
+ client.creditAuditLog.aggregate({
255
+ where: { operationType: constants.OperationType.CONSUME, deleted: 0 },
256
+ _sum: { creditsChange: true },
257
+ _count: true,
258
+ }),
259
+ client.creditAuditLog.aggregate({
260
+ where: { operationType: constants.OperationType.RECHARGE, deleted: 0 },
261
+ _sum: { creditsChange: true },
262
+ _count: true,
263
+ }),
264
+ ]);
265
+ // Calculate operating days (from first record to now)
266
+ const firstRecord = yield client.creditAuditLog.findFirst({
267
+ where: { deleted: 0 },
268
+ orderBy: { createdAt: 'asc' },
269
+ select: { createdAt: true },
270
+ });
271
+ const operatingDays = firstRecord && firstRecord.createdAt
272
+ ? Math.ceil((Date.now() - firstRecord.createdAt.getTime()) / (1000 * 60 * 60 * 24))
273
+ : 1;
274
+ const totalConsumed = consumeStats._sum.creditsChange || 0;
275
+ const totalRecharged = rechargeStats._sum.creditsChange || 0;
276
+ return {
277
+ totalUsers,
278
+ totalOperations,
279
+ totalConsumed,
280
+ totalRecharged,
281
+ avgDailyConsumption: Math.round(totalConsumed / operatingDays),
282
+ avgDailyRecharge: Math.round(totalRecharged / operatingDays),
283
+ };
284
+ });
285
+ }
286
+ // Check for Duplicate Operations
287
+ isDuplicateOperation(userId, operationReferId, operationType, tx) {
288
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
289
+ const client = prisma.checkAndFallbackWithNonTCClient(tx);
290
+ const count = yield client.creditAuditLog.count({
291
+ where: {
292
+ userId,
293
+ operationReferId,
294
+ operationType,
295
+ deleted: 0,
296
+ },
297
+ });
298
+ return count > 0;
299
+ });
300
+ }
301
+ }
302
+ const creditAuditLogService = new CreditAuditLogService();
303
+
304
+ exports.CreditAuditLogService = CreditAuditLogService;
305
+ exports.creditAuditLogService = creditAuditLogService;
@@ -0,0 +1,302 @@
1
+ import { __awaiter } from '../../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.mjs';
2
+ import { Prisma } from '@prisma/client';
3
+ import { OperationType, CreditType } from './constants.mjs';
4
+ import { checkAndFallbackWithNonTCClient } from '../../prisma/prisma.mjs';
5
+
6
+ /* eslint-disable @typescript-eslint/no-explicit-any */
7
+ class CreditAuditLogService {
8
+ // Record Credit Audit
9
+ recordAuditLog(data, tx) {
10
+ return __awaiter(this, void 0, void 0, function* () {
11
+ const client = checkAndFallbackWithNonTCClient(tx);
12
+ return yield client.creditAuditLog.create({
13
+ data: {
14
+ userId: data.userId,
15
+ feature: data.feature,
16
+ operationReferId: data.operationReferId,
17
+ creditType: data.creditType,
18
+ operationType: data.operationType,
19
+ creditsChange: data.creditsChange,
20
+ },
21
+ });
22
+ });
23
+ }
24
+ // Record Credit Operation (alias for recordUsage)
25
+ recordCreditOperation(data, tx) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ return this.recordAuditLog(data, tx);
28
+ });
29
+ }
30
+ // Batch Record Credit Audit
31
+ recordBatchAudit(auditLogs, tx) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ const client = checkAndFallbackWithNonTCClient(tx);
34
+ const result = yield client.creditAuditLog.createMany({
35
+ data: auditLogs,
36
+ });
37
+ return result.count;
38
+ });
39
+ }
40
+ // Get User Credit Audit History
41
+ getUserCreditAuditHistory(userId, params, tx) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ const client = checkAndFallbackWithNonTCClient(tx);
44
+ const where = { userId, deleted: 0 };
45
+ if (params === null || params === void 0 ? void 0 : params.creditType) {
46
+ where.creditType = params.creditType;
47
+ }
48
+ if (params === null || params === void 0 ? void 0 : params.operationType) {
49
+ where.operationType = params.operationType;
50
+ }
51
+ if (params === null || params === void 0 ? void 0 : params.feature) {
52
+ where.feature = params.feature;
53
+ }
54
+ if ((params === null || params === void 0 ? void 0 : params.startDate) || (params === null || params === void 0 ? void 0 : params.endDate)) {
55
+ where.createdAt = {};
56
+ if (params.startDate)
57
+ where.createdAt.gte = params.startDate;
58
+ if (params.endDate)
59
+ where.createdAt.lte = params.endDate;
60
+ }
61
+ const [creditAudit, total] = yield Promise.all([
62
+ client.creditAuditLog.findMany({
63
+ where,
64
+ skip: (params === null || params === void 0 ? void 0 : params.skip) || 0,
65
+ take: (params === null || params === void 0 ? void 0 : params.take) || 20,
66
+ orderBy: (params === null || params === void 0 ? void 0 : params.orderBy) || { createdAt: 'desc' },
67
+ }),
68
+ client.creditAuditLog.count({ where }),
69
+ ]);
70
+ return { creditAudit, total };
71
+ });
72
+ }
73
+ // Get Credit Audit Record by operationReferId
74
+ getCreditAuditList(operationReferId, tx) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ const client = checkAndFallbackWithNonTCClient(tx);
77
+ return yield client.creditAuditLog.findMany({
78
+ where: { operationReferId, deleted: 0 },
79
+ orderBy: { createdAt: 'desc' },
80
+ });
81
+ });
82
+ }
83
+ // Get User Credit Audit Statistics
84
+ getUserCreditAuditStats(userId, startDate, endDate, tx) {
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ const client = checkAndFallbackWithNonTCClient(tx);
87
+ const where = { userId, deleted: 0 };
88
+ if (startDate || endDate) {
89
+ where.createdAt = {};
90
+ if (startDate)
91
+ where.createdAt.gte = startDate;
92
+ if (endDate)
93
+ where.createdAt.lte = endDate;
94
+ }
95
+ // Get all creditAudit records
96
+ const allUsage = yield client.creditAuditLog.findMany({
97
+ where,
98
+ select: {
99
+ creditType: true,
100
+ operationType: true,
101
+ creditsChange: true,
102
+ feature: true,
103
+ },
104
+ });
105
+ // Calculate statistics
106
+ const stats = {
107
+ totalConsumed: 0,
108
+ totalRecharged: 0,
109
+ freeConsumed: 0,
110
+ paidConsumed: 0,
111
+ freeRecharged: 0,
112
+ paidRecharged: 0,
113
+ featureUsage: [],
114
+ };
115
+ // Calculate creditAudit statistics by feature
116
+ const featureMap = new Map();
117
+ allUsage.forEach((creditAudit) => {
118
+ if (creditAudit.operationType === OperationType.CONSUME) {
119
+ stats.totalConsumed += creditAudit.creditsChange;
120
+ if (creditAudit.creditType === CreditType.FREE) {
121
+ stats.freeConsumed += creditAudit.creditsChange;
122
+ }
123
+ else {
124
+ stats.paidConsumed += creditAudit.creditsChange;
125
+ }
126
+ if (creditAudit.feature) {
127
+ featureMap.set(creditAudit.feature, (featureMap.get(creditAudit.feature) || 0) + creditAudit.creditsChange);
128
+ }
129
+ }
130
+ else if (creditAudit.operationType === OperationType.RECHARGE) {
131
+ stats.totalRecharged += creditAudit.creditsChange;
132
+ if (creditAudit.creditType === CreditType.FREE) {
133
+ stats.freeRecharged += creditAudit.creditsChange;
134
+ }
135
+ else {
136
+ stats.paidRecharged += creditAudit.creditsChange;
137
+ }
138
+ }
139
+ });
140
+ // Convert feature creditAudit statistics to array
141
+ stats.featureUsage = Array.from(featureMap.entries())
142
+ .map(([feature, credits]) => ({ feature, credits }))
143
+ .sort((a, b) => b.credits - a.credits);
144
+ return stats;
145
+ });
146
+ }
147
+ // Get Popular Features
148
+ getPopularFeatures() {
149
+ return __awaiter(this, arguments, void 0, function* (limit = 10, startDate, endDate, tx) {
150
+ const client = checkAndFallbackWithNonTCClient(tx);
151
+ const where = {
152
+ operationType: OperationType.CONSUME,
153
+ feature: { not: null },
154
+ deleted: 0,
155
+ };
156
+ if (startDate || endDate) {
157
+ where.createdAt = {};
158
+ if (startDate)
159
+ where.createdAt.gte = startDate;
160
+ if (endDate)
161
+ where.createdAt.lte = endDate;
162
+ }
163
+ const result = yield client.creditAuditLog.groupBy({
164
+ by: ['feature'],
165
+ where,
166
+ _sum: {
167
+ creditsChange: true,
168
+ },
169
+ _count: true,
170
+ orderBy: {
171
+ _sum: {
172
+ creditsChange: 'desc',
173
+ },
174
+ },
175
+ take: limit,
176
+ });
177
+ return result.map((item) => ({
178
+ feature: item.feature,
179
+ totalCredits: item._sum.creditsChange || 0,
180
+ usageCount: item._count,
181
+ }));
182
+ });
183
+ }
184
+ // Get Daily Credit Usage Trend
185
+ getDailyUsageTrend() {
186
+ return __awaiter(this, arguments, void 0, function* (days = 30, userId, tx) {
187
+ const startDate = new Date();
188
+ startDate.setDate(startDate.getDate() - days);
189
+ const client = checkAndFallbackWithNonTCClient(tx);
190
+ const userFilter = userId ? Prisma.sql `AND user_id = ${userId}` : Prisma.sql ``;
191
+ const result = yield client.$queryRaw `
192
+ SELECT
193
+ DATE(created_at) as date,
194
+ SUM(CASE WHEN operation_type = 'consume' THEN credits_used ELSE 0 END) as consumed,
195
+ SUM(CASE WHEN operation_type = 'recharge' THEN credits_used ELSE 0 END) as recharged,
196
+ SUM(CASE WHEN credit_type = 'free' AND operation_type = 'consume'
197
+ THEN credits_used ELSE 0 END) as free_consumed,
198
+ SUM(CASE WHEN credit_type = 'paid' AND operation_type = 'consume'
199
+ THEN credits_used ELSE 0 END) as paid_consumed,
200
+ COUNT(DISTINCT user_id) as unique_users
201
+ FROM credit_usage
202
+ WHERE created_at >= ${startDate}
203
+ AND deleted = 0
204
+ ${userFilter}
205
+ GROUP BY DATE(created_at)
206
+ ORDER BY date DESC
207
+ `;
208
+ return result;
209
+ });
210
+ }
211
+ // Get Recent Credit Usage Operations
212
+ getRecentOperations(userId_1) {
213
+ return __awaiter(this, arguments, void 0, function* (userId, limit = 10, tx) {
214
+ const client = checkAndFallbackWithNonTCClient(tx);
215
+ return yield client.creditAuditLog.findMany({
216
+ where: { userId, deleted: 0 },
217
+ orderBy: { createdAt: 'desc' },
218
+ take: limit,
219
+ });
220
+ });
221
+ }
222
+ // Soft Delete Old Credit Usage Records
223
+ deleteOldRecords() {
224
+ return __awaiter(this, arguments, void 0, function* (daysToKeep = 365, tx) {
225
+ const cutoffDate = new Date();
226
+ cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
227
+ const client = checkAndFallbackWithNonTCClient(tx);
228
+ const result = yield client.creditAuditLog.updateMany({
229
+ where: {
230
+ createdAt: {
231
+ lt: cutoffDate,
232
+ },
233
+ deleted: 0,
234
+ },
235
+ data: {
236
+ deleted: 1,
237
+ },
238
+ });
239
+ return result.count;
240
+ });
241
+ }
242
+ // Get System-wide Credit Usage Statistics
243
+ getSystemStats(tx) {
244
+ return __awaiter(this, void 0, void 0, function* () {
245
+ const client = checkAndFallbackWithNonTCClient(tx);
246
+ const [totalUsers, totalOperations, consumeStats, rechargeStats,] = yield Promise.all([
247
+ client.creditAuditLog.groupBy({
248
+ by: ['userId'],
249
+ where: { deleted: 0 },
250
+ }).then((result) => result.length),
251
+ client.creditAuditLog.count({ where: { deleted: 0 } }),
252
+ client.creditAuditLog.aggregate({
253
+ where: { operationType: OperationType.CONSUME, deleted: 0 },
254
+ _sum: { creditsChange: true },
255
+ _count: true,
256
+ }),
257
+ client.creditAuditLog.aggregate({
258
+ where: { operationType: OperationType.RECHARGE, deleted: 0 },
259
+ _sum: { creditsChange: true },
260
+ _count: true,
261
+ }),
262
+ ]);
263
+ // Calculate operating days (from first record to now)
264
+ const firstRecord = yield client.creditAuditLog.findFirst({
265
+ where: { deleted: 0 },
266
+ orderBy: { createdAt: 'asc' },
267
+ select: { createdAt: true },
268
+ });
269
+ const operatingDays = firstRecord && firstRecord.createdAt
270
+ ? Math.ceil((Date.now() - firstRecord.createdAt.getTime()) / (1000 * 60 * 60 * 24))
271
+ : 1;
272
+ const totalConsumed = consumeStats._sum.creditsChange || 0;
273
+ const totalRecharged = rechargeStats._sum.creditsChange || 0;
274
+ return {
275
+ totalUsers,
276
+ totalOperations,
277
+ totalConsumed,
278
+ totalRecharged,
279
+ avgDailyConsumption: Math.round(totalConsumed / operatingDays),
280
+ avgDailyRecharge: Math.round(totalRecharged / operatingDays),
281
+ };
282
+ });
283
+ }
284
+ // Check for Duplicate Operations
285
+ isDuplicateOperation(userId, operationReferId, operationType, tx) {
286
+ return __awaiter(this, void 0, void 0, function* () {
287
+ const client = checkAndFallbackWithNonTCClient(tx);
288
+ const count = yield client.creditAuditLog.count({
289
+ where: {
290
+ userId,
291
+ operationReferId,
292
+ operationType,
293
+ deleted: 0,
294
+ },
295
+ });
296
+ return count > 0;
297
+ });
298
+ }
299
+ }
300
+ const creditAuditLogService = new CreditAuditLogService();
301
+
302
+ export { CreditAuditLogService, creditAuditLogService };
@@ -0,0 +1,10 @@
1
+ export { userService } from './user.service';
2
+ export { subscriptionService } from './subscription.service';
3
+ export { creditService } from './credit.service';
4
+ export { transactionService } from './transaction.service';
5
+ export { creditAuditLogService } from './creditAuditLog.service';
6
+ export { userBackupService } from './userBackup.service';
7
+ export { apilogService, Apilogger } from './apilog.service';
8
+ export { UserStatus, SubscriptionStatus, OrderStatus, TransactionType, CreditType, OperationType, PaySupplier, BillingReason, PaymentStatus, isValidUserStatus, isValidSubscriptionStatus, isValidOrderStatus, isValidTransactionType, isValidCreditType, isValidOperationType, isValidBillingReason, isValidPaymentStatus, } from './constants';
9
+ export type { UserStatus as UserStatusType, SubscriptionStatus as SubscriptionStatusType, OrderStatus as OrderStatusType, TransactionType as TransactionTypeType, CreditType as CreditTypeType, OperationType as OperationTypeType, PaySupplier as PaySupplierType, BillingReason as BillingReasonType, PaymentStatus as PaymentStatusType, } from './constants';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/services/database/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAG5D,OAAO,EACL,UAAU,EACV,kBAAkB,EAClB,WAAW,EACX,eAAe,EACf,UAAU,EACV,aAAa,EACb,WAAW,EACX,aAAa,EACb,aAAa,EACb,iBAAiB,EACjB,yBAAyB,EACzB,kBAAkB,EAClB,sBAAsB,EACtB,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,aAAa,CAAC;AAGrB,YAAY,EACV,UAAU,IAAI,cAAc,EAC5B,kBAAkB,IAAI,sBAAsB,EAC5C,WAAW,IAAI,eAAe,EAC9B,eAAe,IAAI,mBAAmB,EACtC,UAAU,IAAI,cAAc,EAC5B,aAAa,IAAI,iBAAiB,EAClC,WAAW,IAAI,eAAe,EAC9B,aAAa,IAAI,iBAAiB,EAClC,aAAa,IAAI,iBAAiB,GACnC,MAAM,aAAa,CAAC"}
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ var user_service = require('./user.service.js');
4
+ var subscription_service = require('./subscription.service.js');
5
+ var credit_service = require('./credit.service.js');
6
+ var transaction_service = require('./transaction.service.js');
7
+ var creditAuditLog_service = require('./creditAuditLog.service.js');
8
+ var userBackup_service = require('./userBackup.service.js');
9
+ var apilog_service = require('./apilog.service.js');
10
+ var constants = require('./constants.js');
11
+
12
+
13
+
14
+ exports.userService = user_service.userService;
15
+ exports.subscriptionService = subscription_service.subscriptionService;
16
+ exports.creditService = credit_service.creditService;
17
+ exports.transactionService = transaction_service.transactionService;
18
+ exports.creditAuditLogService = creditAuditLog_service.creditAuditLogService;
19
+ exports.userBackupService = userBackup_service.userBackupService;
20
+ exports.Apilogger = apilog_service.Apilogger;
21
+ exports.apilogService = apilog_service.apilogService;
22
+ exports.BillingReason = constants.BillingReason;
23
+ exports.CreditType = constants.CreditType;
24
+ exports.OperationType = constants.OperationType;
25
+ exports.OrderStatus = constants.OrderStatus;
26
+ exports.PaySupplier = constants.PaySupplier;
27
+ exports.PaymentStatus = constants.PaymentStatus;
28
+ exports.SubscriptionStatus = constants.SubscriptionStatus;
29
+ exports.TransactionType = constants.TransactionType;
30
+ exports.UserStatus = constants.UserStatus;
31
+ exports.isValidBillingReason = constants.isValidBillingReason;
32
+ exports.isValidCreditType = constants.isValidCreditType;
33
+ exports.isValidOperationType = constants.isValidOperationType;
34
+ exports.isValidOrderStatus = constants.isValidOrderStatus;
35
+ exports.isValidPaymentStatus = constants.isValidPaymentStatus;
36
+ exports.isValidSubscriptionStatus = constants.isValidSubscriptionStatus;
37
+ exports.isValidTransactionType = constants.isValidTransactionType;
38
+ exports.isValidUserStatus = constants.isValidUserStatus;
@@ -0,0 +1,8 @@
1
+ export { userService } from './user.service.mjs';
2
+ export { subscriptionService } from './subscription.service.mjs';
3
+ export { creditService } from './credit.service.mjs';
4
+ export { transactionService } from './transaction.service.mjs';
5
+ export { creditAuditLogService } from './creditAuditLog.service.mjs';
6
+ export { userBackupService } from './userBackup.service.mjs';
7
+ export { Apilogger, apilogService } from './apilog.service.mjs';
8
+ export { BillingReason, CreditType, OperationType, OrderStatus, PaySupplier, PaymentStatus, SubscriptionStatus, TransactionType, UserStatus, isValidBillingReason, isValidCreditType, isValidOperationType, isValidOrderStatus, isValidPaymentStatus, isValidSubscriptionStatus, isValidTransactionType, isValidUserStatus } from './constants.mjs';
@@ -0,0 +1,3 @@
1
+ export type { User, Subscription, Credit, CreditAuditLog, Transaction, Apilog, UserBackup, } from '@prisma/client';
2
+ export { Prisma } from '@prisma/client';
3
+ //# sourceMappingURL=prisma-model-type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma-model-type.d.ts","sourceRoot":"","sources":["../../../src/services/database/prisma-model-type.ts"],"names":[],"mappings":"AACA,YAAY,EACV,IAAI,EACJ,YAAY,EACZ,MAAM,EACN,cAAc,EACd,WAAW,EACX,MAAM,EACN,UAAU,GACX,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC"}