@develit-services/ledger 0.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.
@@ -0,0 +1,764 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const cloudflare_workers = require('cloudflare:workers');
6
+ const backendSdk = require('@develit-io/backend-sdk');
7
+ const updateTransactionConfirmationSentAt = require('../shared/ledger.D1MIlhpb.cjs');
8
+ require('@develit-io/general-codes');
9
+ const database_schema = require('../shared/ledger.DGu3Pj-Y.cjs');
10
+ const drizzleOrm = require('drizzle-orm');
11
+ const d1 = require('drizzle-orm/d1');
12
+ require('zod');
13
+ require('drizzle-orm/sqlite-core');
14
+
15
+ const tables = database_schema.schema;
16
+
17
+ const createAccountCommand = async (db, input) => {
18
+ const command = db.insert(tables.account).values(input).returning();
19
+ return { command };
20
+ };
21
+
22
+ const createAccountIdentifierCommand = async (db, input) => {
23
+ const command = db.insert(tables.accountIdentifier).values(input).returning();
24
+ return { command };
25
+ };
26
+
27
+ const deleteAccountCommand = async (db, id) => {
28
+ const accountIdentifierMappingCommand = db.delete(tables.accountIdentifierMapping).where(drizzleOrm.eq(tables.accountIdentifierMapping.accountId, id));
29
+ const accountCommand = db.delete(tables.account).where(drizzleOrm.eq(tables.account.id, id));
30
+ return { accountIdentifierMappingCommand, accountCommand };
31
+ };
32
+
33
+ const linkAccountIdentifierCommand = async (db, accountId, identifierId) => {
34
+ const command = db.insert(tables.accountIdentifierMapping).values({ accountId, identifierId }).returning();
35
+ return { command };
36
+ };
37
+
38
+ const updateAccountCommand = async (db, id, input) => {
39
+ const command = db.update(tables.account).set(input).where(drizzleOrm.eq(tables.account.id, id)).returning();
40
+ return { command };
41
+ };
42
+
43
+ const updateTransactionStatusCommand = async (db, transactionId, status, completedAt) => {
44
+ const updateData = {
45
+ status,
46
+ updatedAt: /* @__PURE__ */ new Date(),
47
+ ...completedAt && { completedAt }
48
+ };
49
+ const command = db.update(tables.transaction).set(updateData).where(drizzleOrm.eq(tables.transaction.id, transactionId)).returning();
50
+ return { command };
51
+ };
52
+
53
+ const updateTransactionConfirmationSentAtCommand = ({
54
+ db,
55
+ transactionId,
56
+ confirmationSentAt
57
+ }) => {
58
+ const command = db.update(tables.transaction).set({ confirmationSentAt, updatedAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(tables.transaction.id, transactionId));
59
+ return {
60
+ command
61
+ };
62
+ };
63
+
64
+ const findAccountByIdentifierQuery = async (db, searchParams) => {
65
+ const conditions = [];
66
+ if (searchParams.iban) {
67
+ conditions.push(drizzleOrm.eq(tables.accountIdentifier.iban, searchParams.iban));
68
+ }
69
+ if (searchParams.accountNumber && searchParams.bankCode) {
70
+ conditions.push(
71
+ drizzleOrm.and(
72
+ drizzleOrm.eq(tables.accountIdentifier.accountNumber, searchParams.accountNumber),
73
+ drizzleOrm.eq(tables.accountIdentifier.bankCode, searchParams.bankCode)
74
+ )
75
+ );
76
+ }
77
+ if (searchParams.swift) {
78
+ conditions.push(drizzleOrm.eq(tables.accountIdentifier.swift, searchParams.swift));
79
+ }
80
+ if (searchParams.cryptoAddress) {
81
+ conditions.push(
82
+ drizzleOrm.eq(tables.accountIdentifier.cryptoAddress, searchParams.cryptoAddress)
83
+ );
84
+ }
85
+ if (conditions.length === 0) return void 0;
86
+ const result = await db.select({
87
+ account: tables.account,
88
+ identifier: tables.accountIdentifier
89
+ }).from(tables.accountIdentifier).innerJoin(
90
+ tables.accountIdentifierMapping,
91
+ drizzleOrm.eq(
92
+ tables.accountIdentifier.id,
93
+ tables.accountIdentifierMapping.identifierId
94
+ )
95
+ ).innerJoin(
96
+ tables.account,
97
+ drizzleOrm.eq(tables.accountIdentifierMapping.accountId, tables.account.id)
98
+ ).where(
99
+ drizzleOrm.inArray(
100
+ tables.account.id,
101
+ db.select({ accountId: tables.account.id }).from(tables.accountIdentifier).innerJoin(
102
+ tables.accountIdentifierMapping,
103
+ drizzleOrm.eq(
104
+ tables.accountIdentifier.id,
105
+ tables.accountIdentifierMapping.identifierId
106
+ )
107
+ ).innerJoin(
108
+ tables.account,
109
+ drizzleOrm.eq(tables.accountIdentifierMapping.accountId, tables.account.id)
110
+ ).where(drizzleOrm.or(...conditions))
111
+ )
112
+ );
113
+ if (result.length === 0) return void 0;
114
+ const account = result[0].account;
115
+ const identifiers = result.map((row) => ({
116
+ identifierId: row.identifier.id,
117
+ accountId: account.id
118
+ }));
119
+ return {
120
+ ...account,
121
+ identifiers
122
+ };
123
+ };
124
+
125
+ const getAccountBalanceByIdQuery = async (db, accountId) => {
126
+ const entries = await db.select().from(tables.entry).where(drizzleOrm.eq(tables.entry.accountId, accountId));
127
+ return entries.map((entry) => {
128
+ return entry.creditAmount - entry.debitAmount;
129
+ }).reduce((acc, curr) => acc + curr, 0);
130
+ };
131
+
132
+ const getAccountByIdQuery = async (db, id) => {
133
+ return await db.select().from(tables.account).where(drizzleOrm.eq(tables.account.id, id)).then(backendSdk.first);
134
+ };
135
+
136
+ const getAccountIdentifierByIdQuery = async (db, id) => {
137
+ return await db.select().from(tables.accountIdentifier).where(drizzleOrm.eq(tables.accountIdentifier.id, id)).then(backendSdk.first);
138
+ };
139
+
140
+ const getAccountWithIdentifiersQuery = async (db, accountId) => {
141
+ const result = await db.select({
142
+ account: tables.account,
143
+ identifier: tables.accountIdentifier
144
+ }).from(tables.account).innerJoin(
145
+ tables.accountIdentifierMapping,
146
+ drizzleOrm.eq(tables.account.id, tables.accountIdentifierMapping.accountId)
147
+ ).innerJoin(
148
+ tables.accountIdentifier,
149
+ drizzleOrm.eq(
150
+ tables.accountIdentifierMapping.identifierId,
151
+ tables.accountIdentifier.id
152
+ )
153
+ ).where(drizzleOrm.eq(tables.account.id, accountId));
154
+ if (result.length === 0) return void 0;
155
+ const account = result[0].account;
156
+ const identifiers = result.map((row) => row.identifier);
157
+ return {
158
+ ...account,
159
+ identifiers: identifiers.map((identifier) => ({
160
+ identifierId: identifier.id,
161
+ accountId
162
+ }))
163
+ };
164
+ };
165
+
166
+ const getAccountsByOwnerQuery = async (db, ownerId) => {
167
+ return await db.select().from(tables.account).where(drizzleOrm.eq(tables.account.ownerId, ownerId));
168
+ };
169
+
170
+ const getTransactionByIdQuery = async (db, id) => {
171
+ return await db.select().from(tables.transaction).where(drizzleOrm.eq(tables.transaction.id, id)).then(backendSdk.first);
172
+ };
173
+
174
+ const getTransactionsByCorrelationIdQuery = async (db, correlationId) => {
175
+ return await db.select().from(tables.transaction).where(drizzleOrm.eq(tables.transaction.correlationId, correlationId)).execute();
176
+ };
177
+
178
+ const getTransactionsByReferenceIdQuery = async (db, referenceType, referenceId) => {
179
+ return await db.select().from(tables.transaction).where(
180
+ drizzleOrm.and(
181
+ drizzleOrm.eq(tables.transaction.referenceType, referenceType),
182
+ drizzleOrm.eq(tables.transaction.referenceId, referenceId)
183
+ )
184
+ ).execute();
185
+ };
186
+
187
+ const listAccountIdentifiersQuery = async (db, accountId) => {
188
+ const result = await db.select({
189
+ identifier: tables.accountIdentifier
190
+ }).from(tables.accountIdentifierMapping).innerJoin(
191
+ tables.accountIdentifier,
192
+ drizzleOrm.eq(
193
+ tables.accountIdentifierMapping.identifierId,
194
+ tables.accountIdentifier.id
195
+ )
196
+ ).where(drizzleOrm.eq(tables.accountIdentifierMapping.accountId, accountId));
197
+ return result.map((row) => row.identifier);
198
+ };
199
+
200
+ const listAccountsQuery = async (db, filters = {}, pagination = { limit: 100, offset: 0 }) => {
201
+ const conditions = [];
202
+ if (filters.ownerId) {
203
+ conditions.push(drizzleOrm.eq(tables.account.ownerId, filters.ownerId));
204
+ }
205
+ if (filters.accountType) {
206
+ conditions.push(drizzleOrm.eq(tables.account.accountType, filters.accountType));
207
+ }
208
+ if (filters.assetType) {
209
+ conditions.push(drizzleOrm.eq(tables.account.assetType, filters.assetType));
210
+ }
211
+ if (filters.currency) {
212
+ conditions.push(drizzleOrm.eq(tables.account.currency, filters.currency));
213
+ }
214
+ if (filters.parentAccountId) {
215
+ conditions.push(drizzleOrm.eq(tables.account.parentAccountId, filters.parentAccountId));
216
+ }
217
+ const whereClause = conditions.length > 0 ? drizzleOrm.and(...conditions) : void 0;
218
+ const [{ total }] = await db.select({ total: drizzleOrm.count() }).from(tables.account).where(whereClause);
219
+ const accounts = await db.select().from(tables.account).where(whereClause).limit(pagination.limit).offset(pagination.offset);
220
+ return { accounts, total };
221
+ };
222
+
223
+ const buildSearchConditions = (search, columns, opts = {}) => {
224
+ const { wrap = "both" } = opts;
225
+ if (!search || search.trim() === "" || columns.length === 0) return void 0;
226
+ const searchTerm = search.toLowerCase();
227
+ const pattern = wrap === "both" ? `%${searchTerm}%` : wrap === "prefix" ? `%${searchTerm}` : wrap === "suffix" ? `${searchTerm}%` : searchTerm;
228
+ const parts = columns.map((col) => drizzleOrm.sql`LOWER(${col} || '') LIKE ${pattern}`);
229
+ return parts.length === 1 ? parts[0] : drizzleOrm.or(...parts);
230
+ };
231
+
232
+ const resolveColumn = (table, column, fallback = "updatedAt") => {
233
+ const key = column && column in table ? column : fallback;
234
+ return table[key];
235
+ };
236
+
237
+ const getTransactionsWithPaginationQuery = async ({
238
+ db,
239
+ pagination: {
240
+ limit,
241
+ page,
242
+ sort,
243
+ filterTransactionCorrelationId,
244
+ filterTransactionReferenceType,
245
+ filterTransactionReferenceId,
246
+ filterTransactionType,
247
+ filterTransactionDescription,
248
+ filterTransactionDateFrom,
249
+ filterTransactionDateTo,
250
+ filterTransactionCompletedAt,
251
+ filterTransactionStatus,
252
+ search
253
+ }
254
+ }) => {
255
+ const searchConditions = buildSearchConditions(search, [
256
+ tables.transaction.status,
257
+ tables.transaction.description,
258
+ tables.transaction.type,
259
+ tables.transaction.referenceId,
260
+ tables.transaction.correlationId
261
+ ]);
262
+ const whereConditions = drizzleOrm.and(
263
+ searchConditions ? searchConditions : void 0,
264
+ filterTransactionCorrelationId ? drizzleOrm.eq(tables.transaction.correlationId, filterTransactionCorrelationId) : void 0,
265
+ filterTransactionReferenceType ? drizzleOrm.eq(tables.transaction.referenceType, filterTransactionReferenceType) : void 0,
266
+ filterTransactionReferenceId ? drizzleOrm.eq(tables.transaction.referenceId, filterTransactionReferenceId) : void 0,
267
+ filterTransactionType ? drizzleOrm.eq(tables.transaction.type, filterTransactionType) : void 0,
268
+ filterTransactionDescription ? drizzleOrm.eq(tables.transaction.description, filterTransactionDescription) : void 0,
269
+ filterTransactionDateFrom ? drizzleOrm.gte(tables.transaction.createdAt, filterTransactionDateFrom) : void 0,
270
+ filterTransactionDateTo ? drizzleOrm.lte(tables.transaction.createdAt, filterTransactionDateTo) : void 0,
271
+ filterTransactionCompletedAt ? drizzleOrm.eq(tables.transaction.completedAt, filterTransactionCompletedAt) : void 0,
272
+ filterTransactionStatus ? drizzleOrm.eq(tables.transaction.status, filterTransactionStatus) : void 0
273
+ );
274
+ const sortColumn = resolveColumn(tables.transaction, sort.column);
275
+ const [{ totalCount }] = await db.select({ totalCount: drizzleOrm.sql`count(*)` }).from(tables.transaction).where(whereConditions);
276
+ const transactionIds = await db.select({ id: tables.transaction.id }).from(tables.transaction).where(whereConditions).limit(limit).offset((page - 1) * limit).orderBy(sort.direction === "asc" ? drizzleOrm.asc(sortColumn) : drizzleOrm.desc(sortColumn));
277
+ if (transactionIds.length === 0) {
278
+ return {
279
+ transactions: [],
280
+ totalCount
281
+ };
282
+ }
283
+ const transactions = await db.select().from(tables.transaction).where(
284
+ drizzleOrm.inArray(
285
+ tables.transaction.id,
286
+ transactionIds.map((o) => o.id)
287
+ )
288
+ ).orderBy(sort.direction === "asc" ? drizzleOrm.asc(sortColumn) : drizzleOrm.desc(sortColumn));
289
+ return {
290
+ transactions,
291
+ totalCount
292
+ };
293
+ };
294
+
295
+ var __defProp = Object.defineProperty;
296
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
297
+ var __decorateClass = (decorators, target, key, kind) => {
298
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
299
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
300
+ if (decorator = decorators[i])
301
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
302
+ if (kind && result) __defProp(target, key, result);
303
+ return result;
304
+ };
305
+ let LedgerServiceBase = class extends backendSdk.develitWorker(cloudflare_workers.WorkerEntrypoint) {
306
+ constructor(ctx, env) {
307
+ super(ctx, env);
308
+ this.db = d1.drizzle(this.env.LEDGER_D1, { schema: tables });
309
+ }
310
+ async queue(_batch) {
311
+ }
312
+ async createTransaction(input) {
313
+ return this.handleAction(
314
+ {
315
+ data: input,
316
+ schema: updateTransactionConfirmationSentAt.createTransactionInputSchema
317
+ },
318
+ { successMessage: "Transaction successfully created." },
319
+ async (params) => {
320
+ const {
321
+ correlationId,
322
+ referenceType,
323
+ referenceId,
324
+ type,
325
+ description,
326
+ paymentId,
327
+ metadata
328
+ // TODO: entries will be implemented later
329
+ // entries: inputEntries,
330
+ } = params;
331
+ await getTransactionsByCorrelationIdQuery(
332
+ this.db,
333
+ correlationId
334
+ );
335
+ const transactionId = backendSdk.uuidv4();
336
+ const timestamp = /* @__PURE__ */ new Date();
337
+ const transaction = {
338
+ id: transactionId,
339
+ correlationId,
340
+ referenceType,
341
+ referenceId,
342
+ type,
343
+ description,
344
+ createdAt: timestamp,
345
+ completedAt: null,
346
+ status: "WAITING_FOR_PAYMENT",
347
+ //todo: get from input?
348
+ paymentId,
349
+ metadata,
350
+ updatedAt: timestamp
351
+ };
352
+ const [data, error] = await backendSdk.useResult(
353
+ this.db.insert(tables.transaction).values(transaction).returning().then(backendSdk.first)
354
+ );
355
+ if (error) {
356
+ throw backendSdk.createInternalError(null, {
357
+ message: "Failed to create transaction",
358
+ status: 500,
359
+ code: "INTERNAL_ERROR"
360
+ });
361
+ }
362
+ const result = {
363
+ transaction: data
364
+ // TODO: entries will be implemented later
365
+ // entries: createdEntries,
366
+ };
367
+ await this.pushToQueue(
368
+ this.env.QUEUE_BUS_QUEUE,
369
+ {
370
+ eventType: "LEDGER_TRANSACTION",
371
+ ledgerTransaction: result.transaction,
372
+ metadata: {
373
+ correlationId: backendSdk.uuidv4(),
374
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
375
+ }
376
+ }
377
+ );
378
+ return {
379
+ transaction: result.transaction
380
+ // TODO: entries will be implemented later
381
+ // entries: result.entries,
382
+ // isBalanced: false,
383
+ // imbalancedCurrencies:
384
+ // imbalancedCurrencies.length > 0 ? imbalancedCurrencies : undefined,
385
+ };
386
+ }
387
+ );
388
+ }
389
+ async updateTransaction(input) {
390
+ return this.handleAction(
391
+ { data: input, schema: updateTransactionConfirmationSentAt.updateTransactionInputSchema },
392
+ { successMessage: "Transaction successfully updated." },
393
+ async (params) => {
394
+ const { transactionId, status, completedAt } = params;
395
+ const existingTransaction = await getTransactionByIdQuery(
396
+ this.db,
397
+ transactionId
398
+ );
399
+ if (!existingTransaction) {
400
+ throw backendSdk.createInternalError(null, {
401
+ message: "Transaction not found",
402
+ status: 404,
403
+ code: "NOT_FOUND"
404
+ });
405
+ }
406
+ const { command } = await updateTransactionStatusCommand(
407
+ this.db,
408
+ transactionId,
409
+ status,
410
+ completedAt
411
+ );
412
+ const [updatedTransaction] = await this.db.batch([command]);
413
+ if (!updatedTransaction) {
414
+ throw backendSdk.createInternalError(null, {
415
+ message: "Failed to update transaction",
416
+ status: 500,
417
+ code: "INTERNAL_ERROR"
418
+ });
419
+ }
420
+ const transaction = backendSdk.first(updatedTransaction);
421
+ await this.pushToQueue(
422
+ this.env.QUEUE_BUS_QUEUE,
423
+ {
424
+ eventType: "LEDGER_TRANSACTION",
425
+ ledgerTransaction: transaction,
426
+ metadata: {
427
+ correlationId: backendSdk.uuidv4(),
428
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
429
+ }
430
+ }
431
+ );
432
+ return transaction;
433
+ }
434
+ );
435
+ }
436
+ async getTransactionById(input) {
437
+ return this.handleAction(
438
+ { data: input, schema: updateTransactionConfirmationSentAt.getTransactionByIdInputSchema },
439
+ { successMessage: "Transaction successfully obtained." },
440
+ async (params) => {
441
+ const { id } = params;
442
+ const transaction = await getTransactionByIdQuery(this.db, id);
443
+ return transaction;
444
+ }
445
+ );
446
+ }
447
+ async getTransactionsByReferenceId(input) {
448
+ return this.handleAction(
449
+ { data: input, schema: updateTransactionConfirmationSentAt.getTransactionsByReferenceIdInputSchema },
450
+ { successMessage: "Transaction successfully obtained." },
451
+ async (params) => {
452
+ const { referenceType, referenceId } = params;
453
+ const transactions = await getTransactionsByReferenceIdQuery(
454
+ this.db,
455
+ referenceType,
456
+ referenceId
457
+ );
458
+ return transactions;
459
+ }
460
+ );
461
+ }
462
+ async getTransactions(input) {
463
+ return this.handleAction(
464
+ { data: input, schema: updateTransactionConfirmationSentAt.getTransactionsInputSchema },
465
+ { successMessage: "Transactions fetched successfully" },
466
+ async (pagination) => {
467
+ const { transactions, totalCount } = await getTransactionsWithPaginationQuery({
468
+ db: this.db,
469
+ pagination
470
+ });
471
+ return { transactions, totalCount };
472
+ }
473
+ );
474
+ }
475
+ async createAccount(input) {
476
+ return this.handleAction(
477
+ { data: input, schema: updateTransactionConfirmationSentAt.createAccountInputSchema },
478
+ { successMessage: "Account successfully created." },
479
+ async (params) => {
480
+ const { identifier, ...accountData } = params;
481
+ const { command } = await createAccountCommand(this.db, {
482
+ id: backendSdk.uuidv4(),
483
+ ...accountData,
484
+ createdAt: /* @__PURE__ */ new Date()
485
+ });
486
+ const [[account]] = await this.db.batch([command]);
487
+ if (!account) {
488
+ throw backendSdk.createInternalError(null, {
489
+ message: "Failed to create account",
490
+ status: 500,
491
+ code: "INTERNAL_SERVER_ERROR"
492
+ });
493
+ }
494
+ if (identifier) {
495
+ const { command: command2 } = await createAccountIdentifierCommand(this.db, {
496
+ id: backendSdk.uuidv4(),
497
+ ...identifier,
498
+ createdAt: /* @__PURE__ */ new Date()
499
+ });
500
+ const [[accountIdentifier]] = await this.db.batch([command2]);
501
+ if (accountIdentifier) {
502
+ const { command: command3 } = await linkAccountIdentifierCommand(
503
+ this.db,
504
+ account.id,
505
+ accountIdentifier.id
506
+ );
507
+ await this.db.batch([command3]);
508
+ }
509
+ return { account, identifier: accountIdentifier };
510
+ }
511
+ return { account, identifier: void 0 };
512
+ }
513
+ );
514
+ }
515
+ async updateAccount(input) {
516
+ return this.handleAction(
517
+ { data: input, schema: updateTransactionConfirmationSentAt.updateAccountInputSchema },
518
+ { successMessage: "Account successfully updated." },
519
+ async (params) => {
520
+ const { accountId, ...updateData } = params;
521
+ if (Object.keys(input).length === 0) {
522
+ const account2 = await getAccountByIdQuery(this.db, accountId);
523
+ if (!account2) {
524
+ throw backendSdk.createInternalError(null, {
525
+ message: "Account not found or update failed",
526
+ status: 404,
527
+ code: "NOT_FOUND"
528
+ });
529
+ }
530
+ return account2;
531
+ }
532
+ const { command } = await updateAccountCommand(
533
+ this.db,
534
+ accountId,
535
+ updateData
536
+ );
537
+ const [account] = await this.db.batch([command]);
538
+ if (!account) {
539
+ throw backendSdk.createInternalError(null, {
540
+ message: "Account not found or update failed",
541
+ status: 404,
542
+ code: "NOT_FOUND"
543
+ });
544
+ }
545
+ return backendSdk.first(account);
546
+ }
547
+ );
548
+ }
549
+ async deleteAccount(input) {
550
+ return this.handleAction(
551
+ { data: input, schema: updateTransactionConfirmationSentAt.deleteAccountInputSchema },
552
+ { successMessage: "Account successfully deleted." },
553
+ async (params) => {
554
+ const { accountId } = params;
555
+ const { accountIdentifierMappingCommand, accountCommand } = await deleteAccountCommand(this.db, accountId);
556
+ const [result] = await this.db.batch([
557
+ accountIdentifierMappingCommand,
558
+ accountCommand
559
+ ]);
560
+ return result.success;
561
+ }
562
+ );
563
+ }
564
+ async getAccount(input) {
565
+ return this.handleAction(
566
+ { data: input, schema: updateTransactionConfirmationSentAt.getAccountInputSchema },
567
+ { successMessage: "Account successfully retrieved." },
568
+ async (params) => {
569
+ const { accountId } = params;
570
+ const account = await getAccountWithIdentifiersQuery(this.db, accountId);
571
+ if (!account) {
572
+ throw backendSdk.createInternalError(null, {
573
+ message: "Account not found",
574
+ status: 404,
575
+ code: "NOT_FOUND"
576
+ });
577
+ }
578
+ return account;
579
+ }
580
+ );
581
+ }
582
+ async getAccountsByOwner(input) {
583
+ return this.handleAction(
584
+ { data: input, schema: updateTransactionConfirmationSentAt.getAccountsByOwnerInputSchema },
585
+ { successMessage: "Accounts successfully retrieved." },
586
+ async (params) => {
587
+ const { ownerId } = params;
588
+ const accounts = await getAccountsByOwnerQuery(this.db, ownerId);
589
+ return accounts;
590
+ }
591
+ );
592
+ }
593
+ async listAccounts(input) {
594
+ return this.handleAction(
595
+ { data: input, schema: updateTransactionConfirmationSentAt.listAccountsInputSchema },
596
+ { successMessage: "Accounts successfully listed." },
597
+ async (params) => {
598
+ const {
599
+ ownerId,
600
+ accountType,
601
+ assetType,
602
+ currency,
603
+ parentAccountId,
604
+ limit,
605
+ offset
606
+ } = params;
607
+ const result = await listAccountsQuery(
608
+ this.db,
609
+ { ownerId, accountType, assetType, currency, parentAccountId },
610
+ { limit, offset }
611
+ );
612
+ return {
613
+ accounts: result.accounts,
614
+ total: result.total,
615
+ limit,
616
+ offset
617
+ };
618
+ }
619
+ );
620
+ }
621
+ async getAccountIdentifierById(input) {
622
+ return this.handleAction(
623
+ { data: input, schema: updateTransactionConfirmationSentAt.getAccountIdentifierInputSchema },
624
+ { successMessage: "Account identifier successfully retrieved." },
625
+ async (params) => {
626
+ const { identifierId } = params;
627
+ const identifier = await getAccountIdentifierByIdQuery(
628
+ this.db,
629
+ identifierId
630
+ );
631
+ if (!identifier) {
632
+ throw backendSdk.createInternalError(null, {
633
+ message: "Account identifier not found",
634
+ status: 404,
635
+ code: "NOT_FOUND"
636
+ });
637
+ }
638
+ return identifier;
639
+ }
640
+ );
641
+ }
642
+ async listAccountIdentifiers(input) {
643
+ return this.handleAction(
644
+ { data: input, schema: updateTransactionConfirmationSentAt.listAccountIdentifiersInputSchema },
645
+ { successMessage: "Account identifiers successfully listed." },
646
+ async (params) => {
647
+ const { accountId } = params;
648
+ const identifiers = await listAccountIdentifiersQuery(
649
+ this.db,
650
+ accountId
651
+ );
652
+ return identifiers;
653
+ }
654
+ );
655
+ }
656
+ async findAccountByIdentifier(input) {
657
+ return this.handleAction(
658
+ { data: input, schema: updateTransactionConfirmationSentAt.findAccountByIdentifierInputSchema },
659
+ { successMessage: "Account search completed." },
660
+ async (params) => {
661
+ const searchParams = params;
662
+ const account = await findAccountByIdentifierQuery(
663
+ this.db,
664
+ searchParams
665
+ );
666
+ return account;
667
+ }
668
+ );
669
+ }
670
+ async getAccountBalance(input) {
671
+ return this.handleAction(
672
+ { data: input, schema: updateTransactionConfirmationSentAt.getAccountBalanceInputSchema },
673
+ { successMessage: "Balance successfully obtained." },
674
+ async (params) => {
675
+ const { accountId } = params;
676
+ const account = await getAccountByIdQuery(this.db, accountId);
677
+ if (!account) {
678
+ throw new Error(`Account ${accountId} not found`);
679
+ }
680
+ const balance = await getAccountBalanceByIdQuery(this.db, accountId);
681
+ return { balance };
682
+ }
683
+ );
684
+ }
685
+ async updateTransactionConfirmationSentAt(input) {
686
+ return this.handleAction(
687
+ { data: input, schema: updateTransactionConfirmationSentAt.updateTransactionConfirmationSentAtInputSchema },
688
+ { successMessage: "Confirmation email sent successfully" },
689
+ async ({ transactionId }) => {
690
+ const { command: transactionCommand } = updateTransactionConfirmationSentAtCommand({
691
+ db: this.db,
692
+ transactionId,
693
+ confirmationSentAt: /* @__PURE__ */ new Date()
694
+ });
695
+ await this.db.batch([transactionCommand]);
696
+ }
697
+ );
698
+ }
699
+ };
700
+ __decorateClass([
701
+ backendSdk.cloudflareQueue({ baseDelay: 60 })
702
+ ], LedgerServiceBase.prototype, "queue", 1);
703
+ __decorateClass([
704
+ backendSdk.action("create-transaction")
705
+ ], LedgerServiceBase.prototype, "createTransaction", 1);
706
+ __decorateClass([
707
+ backendSdk.action("update-transaction")
708
+ ], LedgerServiceBase.prototype, "updateTransaction", 1);
709
+ __decorateClass([
710
+ backendSdk.action("get-transaction-by-id")
711
+ ], LedgerServiceBase.prototype, "getTransactionById", 1);
712
+ __decorateClass([
713
+ backendSdk.action("get-transactions-by-reference-id")
714
+ ], LedgerServiceBase.prototype, "getTransactionsByReferenceId", 1);
715
+ __decorateClass([
716
+ backendSdk.action("get-transactions")
717
+ ], LedgerServiceBase.prototype, "getTransactions", 1);
718
+ __decorateClass([
719
+ backendSdk.action("create-account")
720
+ ], LedgerServiceBase.prototype, "createAccount", 1);
721
+ __decorateClass([
722
+ backendSdk.action("update-account")
723
+ ], LedgerServiceBase.prototype, "updateAccount", 1);
724
+ __decorateClass([
725
+ backendSdk.action("delete-account")
726
+ ], LedgerServiceBase.prototype, "deleteAccount", 1);
727
+ __decorateClass([
728
+ backendSdk.action("get-account")
729
+ ], LedgerServiceBase.prototype, "getAccount", 1);
730
+ __decorateClass([
731
+ backendSdk.action("get-accounts-by-owner")
732
+ ], LedgerServiceBase.prototype, "getAccountsByOwner", 1);
733
+ __decorateClass([
734
+ backendSdk.action("list-accounts")
735
+ ], LedgerServiceBase.prototype, "listAccounts", 1);
736
+ __decorateClass([
737
+ backendSdk.action("get-account-identifier")
738
+ ], LedgerServiceBase.prototype, "getAccountIdentifierById", 1);
739
+ __decorateClass([
740
+ backendSdk.action("list-account-identifiers")
741
+ ], LedgerServiceBase.prototype, "listAccountIdentifiers", 1);
742
+ __decorateClass([
743
+ backendSdk.action("find-account-by-identifier")
744
+ ], LedgerServiceBase.prototype, "findAccountByIdentifier", 1);
745
+ __decorateClass([
746
+ backendSdk.action("get-account-balance")
747
+ ], LedgerServiceBase.prototype, "getAccountBalance", 1);
748
+ __decorateClass([
749
+ backendSdk.action("update-transaction-confirmation-sent-at")
750
+ ], LedgerServiceBase.prototype, "updateTransactionConfirmationSentAt", 1);
751
+ LedgerServiceBase = __decorateClass([
752
+ backendSdk.service("ledger")
753
+ ], LedgerServiceBase);
754
+ function defineLedgerService() {
755
+ return class LedgerService extends LedgerServiceBase {
756
+ constructor(ctx, env) {
757
+ super(ctx, env);
758
+ }
759
+ };
760
+ }
761
+ const LedgerService = defineLedgerService();
762
+
763
+ exports.default = LedgerService;
764
+ exports.defineLedgerService = defineLedgerService;